Skip to main content

lumen_dioxus/navigation/
theme.rs

1//! `ThemeToggle` and `LanguageToggle`: controlled switches for the color theme and the language.
2// cspell:words Français
3
4use dioxus::prelude::*;
5
6use crate::class::compose;
7use crate::hooks::use_controllable;
8use crate::icons::{Icon, lucide};
9
10use super::util::format_template;
11use super::web::{apply_root_lang, apply_root_theme};
12
13/// Whether `theme` is a dark theme: the configured dark theme or any `*-dark` preset, like the
14/// Lumen web runtime.
15pub fn theme_toggle_is_dark(theme: &str, dark_theme: &str) -> bool {
16    theme == dark_theme || theme.ends_with("-dark")
17}
18
19/// Props for [`ThemeToggle`].
20#[derive(Props, Clone, PartialEq)]
21pub struct ThemeToggleProps {
22    /// Controlled theme name, such as `light` or `dark`.
23    #[props(into)]
24    pub value: Option<String>,
25    /// Initial theme when uncontrolled. Defaults to `light_theme`.
26    #[props(into)]
27    pub default_value: Option<String>,
28    /// Called with the next theme name.
29    pub on_value_change: Option<EventHandler<String>>,
30    /// Theme selected when leaving the dark theme. Defaults to `light`.
31    #[props(default = "light".to_string(), into)]
32    pub light_theme: String,
33    /// Theme selected when leaving the light theme. Defaults to `dark`.
34    #[props(default = "dark".to_string(), into)]
35    pub dark_theme: String,
36    /// On web and desktop, also sets `data-theme` and the `dark` class on the document root
37    /// whenever the theme changes. Ignored on Dioxus Native.
38    #[props(default)]
39    pub apply_to_root: bool,
40    /// Screen-reader name. Defaults to `Toggle color theme`.
41    #[props(default = "Toggle color theme".to_string(), into)]
42    pub label: String,
43    /// Click handler, called before the theme changes.
44    pub onclick: Option<EventHandler<MouseEvent>>,
45    /// Extra classes appended after the Lumen class.
46    #[props(into)]
47    pub class: Option<String>,
48    /// Any other `<button>` or global attribute.
49    #[props(extends = GlobalAttributes, extends = button)]
50    pub attributes: Vec<Attribute>,
51}
52
53/// A sun and moon button that switches between a light and a dark theme.
54///
55/// It renders lumen-react's markup plus `aria-pressed`, which is `true` while the dark theme is
56/// active. Apply the theme by putting `data-theme` on an ancestor, such as the app's root element;
57/// `apply_to_root` does that for the document root on web and desktop.
58#[component]
59pub fn ThemeToggle(props: ThemeToggleProps) -> Element {
60    let light = props.light_theme.clone();
61    let theme = use_controllable(
62        props.value.clone(),
63        || props.default_value.clone().unwrap_or(light),
64        props.on_value_change,
65    );
66    let current = theme.get();
67    let dark = theme_toggle_is_dark(&current, &props.dark_theme);
68    let class = compose([Some("ui-theme-toggle"), props.class.as_deref()]);
69    let (light_theme, dark_theme) = (props.light_theme.clone(), props.dark_theme.clone());
70    let onclick = props.onclick;
71
72    use_effect(use_reactive(
73        (&current, &dark, &props.apply_to_root),
74        move |(current, dark, apply)| {
75            if apply {
76                apply_root_theme(current, dark);
77            }
78        },
79    ));
80
81    rsx! {
82        button {
83            aria_pressed: if dark { "true" } else { "false" },
84            class,
85            "data-slot": "theme-toggle",
86            r#type: "button",
87            onclick: move |event| {
88                if let Some(handler) = onclick {
89                    handler.call(event);
90                }
91
92                let next = if theme_toggle_is_dark(&theme.peek(), &dark_theme) {
93                    light_theme.clone()
94                } else {
95                    dark_theme.clone()
96                };
97
98                theme.set(next);
99            },
100            ..props.attributes,
101            span { class: "ui-sr-only", "{props.label}" }
102            Icon { class: "ui-theme-toggle__sun", "data-slot": "theme-toggle-sun", icon: &lucide::SUN }
103            Icon { class: "ui-theme-toggle__moon", "data-slot": "theme-toggle-moon", icon: &lucide::MOON }
104        }
105    }
106}
107
108/// One language offered by a [`LanguageToggle`].
109#[derive(Clone, Debug, PartialEq, Eq)]
110pub struct LanguageToggleLocale {
111    /// Name shown to users, in its own language, such as `Español`.
112    pub label: String,
113    /// Language tag, such as `es`.
114    pub value: String,
115}
116
117impl LanguageToggleLocale {
118    /// A locale with a label and a language tag.
119    pub fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
120        Self {
121            label: label.into(),
122            value: value.into(),
123        }
124    }
125}
126
127/// English and Spanish, the default locales of lumen-core.
128pub fn language_toggle_default_locales() -> Vec<LanguageToggleLocale> {
129    vec![
130        LanguageToggleLocale::new("English", "en"),
131        LanguageToggleLocale::new("Español", "es"),
132    ]
133}
134
135/// Trims locales and drops blank or duplicate entries, like `normalizeLumenLocales`. An empty
136/// result falls back to the defaults.
137pub fn language_toggle_locales(locales: &[LanguageToggleLocale]) -> Vec<LanguageToggleLocale> {
138    let mut normalized: Vec<LanguageToggleLocale> = Vec::new();
139
140    for locale in locales {
141        let label = locale.label.trim();
142        let value = locale.value.trim();
143
144        if label.is_empty()
145            || value.is_empty()
146            || normalized.iter().any(|entry| entry.value == value)
147        {
148            continue;
149        }
150
151        normalized.push(LanguageToggleLocale::new(label, value));
152    }
153
154    if normalized.is_empty() {
155        language_toggle_default_locales()
156    } else {
157        normalized
158    }
159}
160
161/// The current locale for `value` (the first locale when it is unknown) and the one after it,
162/// like `getLumenLocalePair`.
163pub fn language_toggle_pair(
164    locales: &[LanguageToggleLocale],
165    value: Option<&str>,
166) -> (LanguageToggleLocale, LanguageToggleLocale) {
167    let fallback = LanguageToggleLocale::new("English", "en");
168
169    if locales.is_empty() {
170        return (fallback.clone(), fallback);
171    }
172
173    let index = value
174        .and_then(|value| locales.iter().position(|locale| locale.value == value))
175        .unwrap_or(0);
176    let current = locales[index].clone();
177    let next = locales[(index + 1) % locales.len()].clone();
178
179    (current, next)
180}
181
182/// Props for [`LanguageToggle`].
183#[derive(Props, Clone, PartialEq)]
184pub struct LanguageToggleProps {
185    /// Controlled language tag.
186    #[props(into)]
187    pub value: Option<String>,
188    /// Initial language tag when uncontrolled. Defaults to the first locale.
189    #[props(into)]
190    pub default_value: Option<String>,
191    /// Called with the next language tag.
192    pub on_value_change: Option<EventHandler<String>>,
193    /// The languages to cycle through. Defaults to English and Spanish.
194    #[props(default = language_toggle_default_locales())]
195    pub locales: Vec<LanguageToggleLocale>,
196    /// Accessible name; `{current}` and `{next}` are locale labels.
197    #[props(default = "Change language from {current} to {next}".to_string(), into)]
198    pub label_template: String,
199    /// On web and desktop, also sets the document `lang` whenever the language changes. Ignored
200    /// on Dioxus Native.
201    #[props(default)]
202    pub apply_to_root: bool,
203    /// Click handler, called before the language changes.
204    pub onclick: Option<EventHandler<MouseEvent>>,
205    /// Extra classes appended after the Lumen class.
206    #[props(into)]
207    pub class: Option<String>,
208    /// Any other `<button>` or global attribute.
209    #[props(extends = GlobalAttributes, extends = button)]
210    pub attributes: Vec<Attribute>,
211    /// Custom content. Defaults to the next language's label.
212    pub children: Element,
213}
214
215/// A button that switches to the next language in a list.
216#[component]
217pub fn LanguageToggle(props: LanguageToggleProps) -> Element {
218    let locales = language_toggle_locales(&props.locales);
219    let initial = language_toggle_pair(&locales, props.default_value.as_deref())
220        .0
221        .value;
222    let language = use_controllable(props.value.clone(), || initial, props.on_value_change);
223    let value = language.get();
224    let (current, next) = language_toggle_pair(&locales, Some(&value));
225    let label = format_template(
226        &props.label_template,
227        &[("current", &current.label), ("next", &next.label)],
228    );
229    let class = compose([Some("ui-language-toggle"), props.class.as_deref()]);
230    let custom = super::util::has_content(&props.children);
231    let next_value = next.value.clone();
232    let onclick = props.onclick;
233
234    use_effect(use_reactive(
235        (&current.value, &props.apply_to_root),
236        move |(value, apply)| {
237            if apply {
238                apply_root_lang(value);
239            }
240        },
241    ));
242
243    rsx! {
244        button {
245            aria_label: label,
246            class,
247            "data-ui-language-next-value": next.value.clone(),
248            "data-ui-language-toggle": "true",
249            "data-ui-language-value": current.value.clone(),
250            r#type: "button",
251            onclick: move |event| {
252                if let Some(handler) = onclick {
253                    handler.call(event);
254                }
255
256                language.set(next_value.clone());
257            },
258            ..props.attributes,
259            if custom {
260                {props.children}
261            } else {
262                span { lang: next.value.clone(), "{next.label}" }
263            }
264        }
265    }
266}
267
268#[cfg(test)]
269mod tests {
270    use super::{
271        LanguageToggleLocale, language_toggle_locales, language_toggle_pair, theme_toggle_is_dark,
272    };
273
274    #[test]
275    fn dark_themes_include_presets() {
276        assert!(theme_toggle_is_dark("dark", "dark"));
277        assert!(theme_toggle_is_dark("paper-dark", "dark"));
278        assert!(!theme_toggle_is_dark("light", "dark"));
279        assert!(theme_toggle_is_dark("night", "night"));
280    }
281
282    #[test]
283    fn locales_normalize_and_cycle() {
284        let locales = language_toggle_locales(&[
285            LanguageToggleLocale::new(" English ", "en"),
286            LanguageToggleLocale::new("Duplicate", "en"),
287            LanguageToggleLocale::new("", "xx"),
288            LanguageToggleLocale::new("Français", "fr"),
289        ]);
290        assert_eq!(locales.len(), 2);
291        assert_eq!(locales[0].label, "English");
292        let (current, next) = language_toggle_pair(&locales, Some("fr"));
293        assert_eq!((current.value.as_str(), next.value.as_str()), ("fr", "en"));
294        let (current, _) = language_toggle_pair(&locales, Some("unknown"));
295        assert_eq!(current.value, "en");
296        assert_eq!(language_toggle_locales(&[]).len(), 2);
297    }
298}