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