azul_css/
hot_reload.rs

1//! Traits and datatypes associated with reloading styles at runtime.
2
3use crate::css::Css;
4use std::time::Duration;
5
6/// Interface that can be used to reload a stylesheet while an application is running.
7/// Initialize the `Window::new` with a `Box<HotReloadHandle>` - this allows the hot-reloading
8/// to be independent of the source format, making CSS only one frontend format.
9///
10/// You can, for example, parse and load styles directly from a SASS, LESS or JSON parser.
11/// The default parser is `azul-css-parser`.
12pub trait HotReloadHandler {
13    /// Reloads the style from the source format. Should return Ok() when the CSS has be correctly
14    /// reloaded, and an human-readable error string otherwise (since the error needs to be printed
15    /// to stdout when hot-reloading).
16    fn reload_style(&self) -> Result<Css, String>;
17    /// Returns how quickly the hot-reloader should reload the source format.
18    fn get_reload_interval(&self) -> Duration;
19}
20
21/// Custom hot-reloader combinator that can be used to merge hot-reloaded styles onto a base style.
22/// Can be useful when working from a base configuration, such as the OS-native styles.
23pub struct HotReloadOverrideHandler {
24    /// The base style, usually provided by `azul-native-style`.
25    pub base_style: Css,
26    /// The style that will be added on top of the `base_style`.
27    pub hot_reloader: Box<dyn HotReloadHandler>,
28}
29
30impl HotReloadOverrideHandler {
31    /// Creates a new `HotReloadHandler` that merges styles onto the given base style
32    /// (usually the system-native style, in order to let the user override properties).
33    pub fn new(base_style: Css, hot_reloader: Box<dyn HotReloadHandler>) -> Self {
34        Self {
35            base_style,
36            hot_reloader,
37        }
38    }
39}
40
41impl HotReloadHandler for HotReloadOverrideHandler {
42    fn reload_style(&self) -> Result<Css, String> {
43        let mut css = Css::empty();
44        for stylesheet in self.base_style.clone().stylesheets {
45            css.append_stylesheet(stylesheet);
46        }
47        for stylesheet in self.hot_reloader.reload_style()?.stylesheets {
48            css.append_stylesheet(stylesheet);
49        }
50        Ok(css)
51    }
52
53    fn get_reload_interval(&self) -> Duration {
54        self.hot_reloader.get_reload_interval()
55    }
56}