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 window: Window = window().expect("no global window exists");
63 let media_query: Option<MediaQueryList> = window
64 .match_media("(prefers-color-scheme: dark)")
65 .ok()
66 .flatten();
67 let Some(mql) = media_query else {
68 return;
69 };
70 let closure: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
71 let detected: String = Self::detect_system_theme();
72 let current: String = theme_signal.get();
73 if current != detected {
74 theme_signal.set(detected);
75 }
76 }));
77 let _: Result<(), JsValue> =
78 mql.add_event_listener_with_callback("change", closure.as_ref().unchecked_ref());
79 closure.forget();
80 }
81
82 /// Detects the current system color scheme preference.
83 ///
84 /// Uses `window.matchMedia("(prefers-color-scheme: dark)")` to check whether
85 /// the operating system is in dark mode. Falls back to light theme if the
86 /// detection fails.
87 ///
88 /// # Returns
89 ///
90 /// - `String` - The detected system theme name ("light" or "dark").
91 pub fn detect_system_theme() -> String {
92 let window: Window = window().expect("no global window exists");
93 let is_dark: bool = window
94 .match_media("(prefers-color-scheme: dark)")
95 .ok()
96 .flatten()
97 .map(|mql: MediaQueryList| mql.matches())
98 .unwrap_or(false);
99 if is_dark {
100 THEME_DARK.to_string()
101 } else {
102 THEME_LIGHT.to_string()
103 }
104 }
105
106 /// Returns the CSS class name for the given theme value.
107 ///
108 /// # Arguments
109 ///
110 /// - `&str` - The theme name ("light" or "dark").
111 ///
112 /// # Returns
113 ///
114 /// - `&'static str` - The CSS class name for the theme.
115 pub(crate) fn theme_class_name(theme: &str) -> &'static str {
116 if theme == THEME_DARK {
117 c_theme_dark().get_name()
118 } else {
119 c_theme_light().get_name()
120 }
121 }
122
123 /// Creates a click event handler that toggles the theme between "light" and "dark".
124 ///
125 /// The switch stays smooth even on pages with many elements (e.g. the list
126 /// page) because individual components no longer carry their own colour
127 /// (`background` / `color` / `border-color`) transitions — only the app root
128 /// container animates its colour change, so the page fades as a whole while
129 /// each component snaps to the new theme instantly. This avoids hundreds of
130 /// elements running simultaneous colour transitions, which previously caused
131 /// dropped frames.
132 ///
133 /// # Arguments
134 ///
135 /// - `Signal<String>` - The theme signal to toggle.
136 ///
137 /// # Returns
138 ///
139 /// - `Option<Rc<dyn Fn(Event)>>` - A click event handler that flips the theme value.
140 pub fn toggle(theme_signal: Signal<String>) -> Option<Rc<dyn Fn(Event)>> {
141 Some(Rc::new(move |_: Event| {
142 let current: String = theme_signal.get();
143 if current == THEME_LIGHT {
144 theme_signal.set(THEME_DARK.to_string());
145 } else {
146 theme_signal.set(THEME_LIGHT.to_string());
147 }
148 }))
149 }
150}