lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `ThemeToggle` and `LanguageToggle`: controlled switches for the color theme and the language.
// cspell:words Français

use dioxus::prelude::*;

use crate::class::compose;
use crate::hooks::use_controllable;
use crate::icons::{Icon, lucide};

use super::util::format_template;
use super::web::{apply_root_lang, apply_root_theme};

/// Whether `theme` is a dark theme: the configured dark theme or any `*-dark` preset, like the
/// Lumen web runtime.
pub fn theme_toggle_is_dark(theme: &str, dark_theme: &str) -> bool {
    theme == dark_theme || theme.ends_with("-dark")
}

/// Props for [`ThemeToggle`].
#[derive(Props, Clone, PartialEq)]
pub struct ThemeToggleProps {
    /// Controlled theme name, such as `light` or `dark`.
    #[props(into)]
    pub value: Option<String>,
    /// Initial theme when uncontrolled. Defaults to `light_theme`.
    #[props(into)]
    pub default_value: Option<String>,
    /// Called with the next theme name.
    pub on_value_change: Option<EventHandler<String>>,
    /// Theme selected when leaving the dark theme. Defaults to `light`.
    #[props(default = "light".to_string(), into)]
    pub light_theme: String,
    /// Theme selected when leaving the light theme. Defaults to `dark`.
    #[props(default = "dark".to_string(), into)]
    pub dark_theme: String,
    /// On web and desktop, also sets `data-theme` and the `dark` class on the document root
    /// whenever the theme changes. Ignored on Dioxus Native.
    #[props(default)]
    pub apply_to_root: bool,
    /// Screen-reader name. Defaults to `Toggle color theme`.
    #[props(default = "Toggle color theme".to_string(), into)]
    pub label: String,
    /// Click handler, called before the theme changes.
    pub onclick: Option<EventHandler<MouseEvent>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<button>` or global attribute.
    #[props(extends = GlobalAttributes, extends = button)]
    pub attributes: Vec<Attribute>,
}

/// A sun and moon button that switches between a light and a dark theme.
///
/// It renders lumen-react's markup plus `aria-pressed`, which is `true` while the dark theme is
/// active. Apply the theme by putting `data-theme` on an ancestor, such as the app's root element;
/// `apply_to_root` does that for the document root on web and desktop.
#[component]
pub fn ThemeToggle(props: ThemeToggleProps) -> Element {
    let light = props.light_theme.clone();
    let theme = use_controllable(
        props.value.clone(),
        || props.default_value.clone().unwrap_or(light),
        props.on_value_change,
    );
    let current = theme.get();
    let dark = theme_toggle_is_dark(&current, &props.dark_theme);
    let class = compose([Some("ui-theme-toggle"), props.class.as_deref()]);
    let (light_theme, dark_theme) = (props.light_theme.clone(), props.dark_theme.clone());
    let onclick = props.onclick;

    use_effect(use_reactive(
        (&current, &dark, &props.apply_to_root),
        move |(current, dark, apply)| {
            if apply {
                apply_root_theme(current, dark);
            }
        },
    ));

    rsx! {
        button {
            aria_pressed: if dark { "true" } else { "false" },
            class,
            "data-slot": "theme-toggle",
            r#type: "button",
            onclick: move |event| {
                if let Some(handler) = onclick {
                    handler.call(event);
                }

                let next = if theme_toggle_is_dark(&theme.peek(), &dark_theme) {
                    light_theme.clone()
                } else {
                    dark_theme.clone()
                };

                theme.set(next);
            },
            ..props.attributes,
            span { class: "ui-sr-only", "{props.label}" }
            Icon { class: "ui-theme-toggle__sun", "data-slot": "theme-toggle-sun", icon: &lucide::SUN }
            Icon { class: "ui-theme-toggle__moon", "data-slot": "theme-toggle-moon", icon: &lucide::MOON }
        }
    }
}

/// One language offered by a [`LanguageToggle`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LanguageToggleLocale {
    /// Name shown to users, in its own language, such as `Español`.
    pub label: String,
    /// Language tag, such as `es`.
    pub value: String,
}

impl LanguageToggleLocale {
    /// A locale with a label and a language tag.
    pub fn new(label: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            value: value.into(),
        }
    }
}

/// English and Spanish, the default locales of lumen-core.
pub fn language_toggle_default_locales() -> Vec<LanguageToggleLocale> {
    vec![
        LanguageToggleLocale::new("English", "en"),
        LanguageToggleLocale::new("Español", "es"),
    ]
}

/// Trims locales and drops blank or duplicate entries, like `normalizeLumenLocales`. An empty
/// result falls back to the defaults.
pub fn language_toggle_locales(locales: &[LanguageToggleLocale]) -> Vec<LanguageToggleLocale> {
    let mut normalized: Vec<LanguageToggleLocale> = Vec::new();

    for locale in locales {
        let label = locale.label.trim();
        let value = locale.value.trim();

        if label.is_empty()
            || value.is_empty()
            || normalized.iter().any(|entry| entry.value == value)
        {
            continue;
        }

        normalized.push(LanguageToggleLocale::new(label, value));
    }

    if normalized.is_empty() {
        language_toggle_default_locales()
    } else {
        normalized
    }
}

/// The current locale for `value` (the first locale when it is unknown) and the one after it,
/// like `getLumenLocalePair`.
pub fn language_toggle_pair(
    locales: &[LanguageToggleLocale],
    value: Option<&str>,
) -> (LanguageToggleLocale, LanguageToggleLocale) {
    let fallback = LanguageToggleLocale::new("English", "en");

    if locales.is_empty() {
        return (fallback.clone(), fallback);
    }

    let index = value
        .and_then(|value| locales.iter().position(|locale| locale.value == value))
        .unwrap_or(0);
    let current = locales[index].clone();
    let next = locales[(index + 1) % locales.len()].clone();

    (current, next)
}

/// Props for [`LanguageToggle`].
#[derive(Props, Clone, PartialEq)]
pub struct LanguageToggleProps {
    /// Controlled language tag.
    #[props(into)]
    pub value: Option<String>,
    /// Initial language tag when uncontrolled. Defaults to the first locale.
    #[props(into)]
    pub default_value: Option<String>,
    /// Called with the next language tag.
    pub on_value_change: Option<EventHandler<String>>,
    /// The languages to cycle through. Defaults to English and Spanish.
    #[props(default = language_toggle_default_locales())]
    pub locales: Vec<LanguageToggleLocale>,
    /// Accessible name; `{current}` and `{next}` are locale labels.
    #[props(default = "Change language from {current} to {next}".to_string(), into)]
    pub label_template: String,
    /// On web and desktop, also sets the document `lang` whenever the language changes. Ignored
    /// on Dioxus Native.
    #[props(default)]
    pub apply_to_root: bool,
    /// Click handler, called before the language changes.
    pub onclick: Option<EventHandler<MouseEvent>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<button>` or global attribute.
    #[props(extends = GlobalAttributes, extends = button)]
    pub attributes: Vec<Attribute>,
    /// Custom content. Defaults to the next language's label.
    pub children: Element,
}

/// A button that switches to the next language in a list.
#[component]
pub fn LanguageToggle(props: LanguageToggleProps) -> Element {
    let locales = language_toggle_locales(&props.locales);
    let initial = language_toggle_pair(&locales, props.default_value.as_deref())
        .0
        .value;
    let language = use_controllable(props.value.clone(), || initial, props.on_value_change);
    let value = language.get();
    let (current, next) = language_toggle_pair(&locales, Some(&value));
    let label = format_template(
        &props.label_template,
        &[("current", &current.label), ("next", &next.label)],
    );
    let class = compose([Some("ui-language-toggle"), props.class.as_deref()]);
    let custom = super::util::has_content(&props.children);
    let next_value = next.value.clone();
    let onclick = props.onclick;

    use_effect(use_reactive(
        (&current.value, &props.apply_to_root),
        move |(value, apply)| {
            if apply {
                apply_root_lang(value);
            }
        },
    ));

    rsx! {
        button {
            aria_label: label,
            class,
            "data-ui-language-next-value": next.value.clone(),
            "data-ui-language-toggle": "true",
            "data-ui-language-value": current.value.clone(),
            r#type: "button",
            onclick: move |event| {
                if let Some(handler) = onclick {
                    handler.call(event);
                }

                language.set(next_value.clone());
            },
            ..props.attributes,
            if custom {
                {props.children}
            } else {
                span { lang: next.value.clone(), "{next.label}" }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        LanguageToggleLocale, language_toggle_locales, language_toggle_pair, theme_toggle_is_dark,
    };

    #[test]
    fn dark_themes_include_presets() {
        assert!(theme_toggle_is_dark("dark", "dark"));
        assert!(theme_toggle_is_dark("paper-dark", "dark"));
        assert!(!theme_toggle_is_dark("light", "dark"));
        assert!(theme_toggle_is_dark("night", "night"));
    }

    #[test]
    fn locales_normalize_and_cycle() {
        let locales = language_toggle_locales(&[
            LanguageToggleLocale::new(" English ", "en"),
            LanguageToggleLocale::new("Duplicate", "en"),
            LanguageToggleLocale::new("", "xx"),
            LanguageToggleLocale::new("Français", "fr"),
        ]);
        assert_eq!(locales.len(), 2);
        assert_eq!(locales[0].label, "English");
        let (current, next) = language_toggle_pair(&locales, Some("fr"));
        assert_eq!((current.value.as_str(), next.value.as_str()), ("fr", "en"));
        let (current, _) = language_toggle_pair(&locales, Some("unknown"));
        assert_eq!(current.value, "en");
        assert_eq!(language_toggle_locales(&[]).len(), 2);
    }
}