azul_css_parser/
hot_reloader.rs

1//! Provides an implementation of the HotReloadHandler from the `azul_css` crate, allowing CSS
2//! files to be dynamically reloaded at runtime.
3
4use azul_css::{HotReloadHandler, Css};
5use std::time::Duration;
6use std::path::PathBuf;
7
8pub const DEFAULT_RELOAD_INTERVAL: Duration = Duration::from_millis(500);
9
10/// Allows dynamic reloading of a CSS file at application runtime.
11#[derive(Debug, Clone, PartialEq, Eq, Hash)]
12pub struct HotReloader {
13    file_path: PathBuf,
14    reload_interval: Duration,
15}
16
17impl HotReloader {
18    /// Creates a HotReloader that will load a style directly from the CSS file
19    /// at the given path.
20    pub fn new<P: Into<PathBuf>>(file_path: P) -> Self {
21        Self { file_path: file_path.into(), reload_interval: DEFAULT_RELOAD_INTERVAL }
22    }
23
24    pub fn with_reload_interval(self, reload_interval: Duration) -> Self {
25        Self { reload_interval, .. self }
26    }
27}
28
29impl HotReloadHandler for HotReloader {
30    fn reload_style(&self) -> Result<Css, String> {
31        use std::fs;
32        use crate::css;
33
34        let file_name = self.file_path.file_name().map(|os_str| os_str.to_string_lossy()).unwrap_or_default();
35
36        let reloaded_css = fs::read_to_string(&self.file_path)
37            .map_err(|e| format!("Error parsing CSS file: \"{}\":\r\nIO Error: {}", file_name, e))?;
38
39        css::new_from_str(&reloaded_css).map_err(|e| format!("Error parsing CSS file: \"{}\":\r\n{}", file_name, e))
40    }
41
42    fn get_reload_interval(&self) -> Duration {
43        self.reload_interval
44    }
45}