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