use crate::*;
pub(crate) fn detect_system_theme() -> String {
let window: Window = window().expect("no global window exists");
let is_dark: bool = window
.match_media("(prefers-color-scheme: dark)")
.ok()
.flatten()
.map(|mql: MediaQueryList| mql.matches())
.unwrap_or(false);
if is_dark {
THEME_DARK.to_string()
} else {
THEME_LIGHT.to_string()
}
}
pub(crate) fn use_system_theme_change(theme_signal: Signal<String>) {
let window: Window = window().expect("no global window exists");
let media_query: Option<MediaQueryList> = window
.match_media("(prefers-color-scheme: dark)")
.ok()
.flatten();
let Some(mql) = media_query else {
return;
};
let closure: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_event: Event| {
let detected: String = detect_system_theme();
let current: String = theme_signal.get();
if current != detected {
theme_signal.set(detected);
}
}));
let _ = mql.add_event_listener_with_callback("change", closure.as_ref().unchecked_ref());
closure.forget();
}
pub(crate) fn use_theme(mobile_signal: Signal<bool>) -> ThemeState {
let theme: Signal<String> = use_signal(detect_system_theme);
use_system_theme_change(theme);
let initial_theme: String = theme.get();
let initial_mobile: bool = mobile_signal.get();
let initial_root: &'static str = if initial_mobile {
c_mobile_app_root().get_name()
} else {
c_app_root().get_name()
};
let root_class: Signal<String> = use_signal(|| {
format!(
"{initial_root} {theme_class}",
theme_class = theme_class_name(&initial_theme)
)
});
watch!(mobile_signal, theme, |mobile: bool, theme_value: String| {
let root: &'static str = if mobile {
c_mobile_app_root().get_name()
} else {
c_app_root().get_name()
};
root_class.set(format!(
"{root} {theme_class}",
theme_class = theme_class_name(&theme_value)
));
});
ThemeState { theme, root_class }
}
pub(crate) fn toggle_theme(theme_signal: Signal<String>) -> Option<Rc<dyn Fn(Event)>> {
Some(Rc::new(move |_event: Event| {
let current: String = theme_signal.get();
if current == THEME_LIGHT {
theme_signal.set(THEME_DARK.to_string());
} else {
theme_signal.set(THEME_LIGHT.to_string());
}
}))
}
pub(crate) fn theme_class_name(theme: &str) -> &'static str {
if theme == THEME_DARK {
c_theme_dark().get_name()
} else {
c_theme_light().get_name()
}
}