Skip to main content

euv_ui/component/theme/hook/
impl.rs

1use super::*;
2
3/// Implementation of theme state functionality.
4///
5/// Provides methods for creating theme state, detecting system theme changes,
6/// and managing theme-related reactive state.
7impl ThemeState {
8    /// Creates theme state for managing light/dark mode and root CSS classes.
9    ///
10    /// Detects the system color scheme preference at startup and initializes the
11    /// theme signal accordingly. Uses `watch!` to reactively update the root class
12    /// whenever the theme or mobile signal changes.
13    ///
14    /// # Arguments
15    ///
16    /// - `Signal<bool>` - The reactive signal indicating whether the viewport is mobile-sized.
17    ///
18    /// # Returns
19    ///
20    /// - `ThemeState` - The reactive theme state containing the theme signal and root class signal.
21    pub fn use_theme_state(mobile_signal: Signal<bool>) -> ThemeState {
22        let theme: Signal<String> = App::use_signal(Self::detect_system_theme);
23        Self::use_system_theme_change(theme);
24        let initial_theme: String = theme.get();
25        let initial_mobile: bool = mobile_signal.get();
26        let initial_root: &'static str = if initial_mobile {
27            c_mobile_app_root().get_name()
28        } else {
29            c_app_root().get_name()
30        };
31        let root_class: Signal<String> = App::use_signal(|| {
32            format!(
33                "{initial_root} {theme_class}",
34                theme_class = Self::theme_class_name(&initial_theme)
35            )
36        });
37        watch!(mobile_signal, theme, |mobile: bool, theme_value: String| {
38            let root: &'static str = if mobile {
39                c_mobile_app_root().get_name()
40            } else {
41                c_app_root().get_name()
42            };
43            root_class.set(format!(
44                "{root} {theme_class}",
45                theme_class = Self::theme_class_name(&theme_value)
46            ));
47        });
48        ThemeState { theme, root_class }
49    }
50
51    /// Subscribes to system color scheme changes and updates the theme signal.
52    ///
53    /// Creates a `MediaQueryList` for `prefers-color-scheme: dark` and listens
54    /// for `change` events. When the system theme changes, the theme signal is
55    /// updated accordingly. The listener is automatically cleaned up when the
56    /// hook context is cleared.
57    ///
58    /// # Arguments
59    ///
60    /// - `Signal<String>` - The theme signal to update when the system theme changes.
61    pub fn use_system_theme_change(theme_signal: Signal<String>) {
62        let Some(window) = window() else {
63            return;
64        };
65        let media_query: Option<MediaQueryList> = window
66            .match_media("(prefers-color-scheme: dark)")
67            .ok()
68            .flatten();
69        let Some(mql) = media_query else {
70            return;
71        };
72        let closure: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
73            let detected: String = Self::detect_system_theme();
74            let current: String = theme_signal.get();
75            if current != detected {
76                theme_signal.set(detected);
77            }
78        }));
79        let _: Result<(), JsValue> =
80            mql.add_event_listener_with_callback("change", closure.as_ref().unchecked_ref());
81        closure.forget();
82    }
83
84    /// Detects the current system color scheme preference.
85    ///
86    /// Uses `window.matchMedia("(prefers-color-scheme: dark)")` to check whether
87    /// the operating system is in dark mode. Falls back to light theme if the
88    /// detection fails.
89    ///
90    /// # Returns
91    ///
92    /// - `String` - The detected system theme name ("light" or "dark").
93    pub fn detect_system_theme() -> String {
94        let Some(window) = window() else {
95            return THEME_LIGHT.to_string();
96        };
97        let is_dark: bool = window
98            .match_media("(prefers-color-scheme: dark)")
99            .ok()
100            .flatten()
101            .map(|mql: MediaQueryList| mql.matches())
102            .unwrap_or_default();
103        if is_dark {
104            THEME_DARK.to_string()
105        } else {
106            THEME_LIGHT.to_string()
107        }
108    }
109
110    /// Returns the CSS class name for the given theme value.
111    ///
112    /// # Arguments
113    ///
114    /// - `&str` - The theme name ("light" or "dark").
115    ///
116    /// # Returns
117    ///
118    /// - `&'static str` - The CSS class name for the theme.
119    pub(crate) fn theme_class_name(theme: &str) -> &'static str {
120        if theme == THEME_DARK {
121            c_theme_dark().get_name()
122        } else {
123            c_theme_light().get_name()
124        }
125    }
126
127    /// Creates a click event handler that toggles the theme between "light" and "dark".
128    ///
129    /// The switch stays smooth even on pages with many elements (e.g. the list
130    /// page) because individual components no longer carry their own colour
131    /// (`background` / `color` / `border-color`) transitions — only the app root
132    /// container animates its colour change, so the page fades as a whole while
133    /// each component snaps to the new theme instantly. This avoids hundreds of
134    /// elements running simultaneous colour transitions, which previously caused
135    /// dropped frames.
136    ///
137    /// # Arguments
138    ///
139    /// - `Signal<String>` - The theme signal to toggle.
140    ///
141    /// # Returns
142    ///
143    /// - `Option<Rc<dyn Fn(Event)>>` - A click event handler that flips the theme value.
144    pub fn toggle(theme_signal: Signal<String>) -> Option<Rc<dyn Fn(Event)>> {
145        Some(Rc::new(move |_: Event| {
146            let current: String = theme_signal.get();
147            if current == THEME_LIGHT {
148                theme_signal.set(THEME_DARK.to_string());
149            } else {
150                theme_signal.set(THEME_LIGHT.to_string());
151            }
152        }))
153    }
154}