lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `ThemeBuilder`: the theme editor frame, plus a ready-made `ThemeBuilderEditor` and the token
//! model that turns hues and appearance choices into Lumen theme tokens.

mod model;

pub use model::*;

use std::fmt::Write as _;

use dioxus::prelude::*;

use crate::class::{Glass, compose};
use crate::hooks::{use_controllable, use_unique_id};
use crate::{Button, ButtonSize, ButtonVariant, Input, Label};

/// Props for [`ThemeBuilder`].
#[derive(Props, Clone, PartialEq)]
pub struct ThemeBuilderProps {
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<section>` or global attribute.
    #[props(extends = GlobalAttributes, extends = section)]
    pub attributes: Vec<Attribute>,
    /// Token controls, previews, and export actions, such as a [`ThemeBuilderEditor`].
    pub children: Element,
}

/// Frames token previews and theme export controls.
///
/// Like lumen-react it is a styled `<section>`. Lumen's web runtime turns `data-ui-theme-*`
/// markup inside it into a live editor; Dioxus has no such runtime, so use
/// [`ThemeBuilderEditor`] or the model functions such as [`create_theme_builder_tokens`].
#[component]
pub fn ThemeBuilder(props: ThemeBuilderProps) -> Element {
    let glass = props.glass.class("ui-theme-builder");
    let class = compose([
        Some("ui-theme-builder"),
        glass.as_deref(),
        props.class.as_deref(),
    ]);

    rsx! {
        section { class, "data-ui-theme-builder": "true", ..props.attributes, {props.children} }
    }
}

/// Inline CSS that applies theme tokens as custom properties, for a preview region.
pub fn theme_builder_style(tokens: &ThemeBuilderTokens, scheme: ThemeBuilderScheme) -> String {
    let mut style = format!("color-scheme:{}", scheme.as_str());

    for (name, value) in tokens.iter() {
        let _ = write!(style, ";--{name}:{value}");
    }

    style
}

/// Props for [`ThemeBuilderEditor`].
#[derive(Props, Clone, PartialEq)]
pub struct ThemeBuilderEditorProps {
    /// Controlled options.
    pub options: Option<ThemeBuilderOptions>,
    /// Initial options when uncontrolled. Defaults to hue 264 (the Lumen violet family).
    #[props(default = ThemeBuilderOptions { hue: Some(264.0), ..ThemeBuilderOptions::default() })]
    pub default_options: ThemeBuilderOptions,
    /// Called with the new options after every edit.
    pub on_options_change: Option<EventHandler<ThemeBuilderOptions>>,
    /// Called with the generated tokens after every edit.
    pub on_change: Option<EventHandler<ThemeBuilderResult>>,
    /// Heading. Defaults to `Theme`.
    #[props(default = "Theme".to_string(), into)]
    pub title: String,
    /// Glass intensity of the frame.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Preview content, themed with the generated tokens. Defaults to brand and accent swatches.
    pub children: Element,
}

fn range_value(event: &FormEvent) -> Option<f64> {
    parse_theme_builder_number(&event.value())
}

/// A complete theme editor: brand and accent hues, light or dark scheme, generated or manual
/// colors, radius and spacing scales, a live preview, and the exported CSS.
///
/// The preview applies the tokens as CSS custom properties, so it works on every renderer. Copy
/// uses the clipboard through `document::eval` on web and desktop; on Dioxus Native the button
/// reports that copying is unavailable and the CSS stays selectable in the output.
#[component]
#[allow(clippy::too_many_lines)]
pub fn ThemeBuilderEditor(props: ThemeBuilderEditorProps) -> Element {
    let id = use_unique_id();
    let options = use_controllable(
        props.options.clone(),
        || props.default_options.clone(),
        props.on_options_change,
    );
    let current = options.get();
    let result = create_theme_builder_tokens(&current);
    let css = export_theme_builder_css(&result.tokens, result.scheme);
    let style = theme_builder_style(&result.tokens, result.scheme);
    let mut copy_status = use_signal(String::new);
    let on_change = props.on_change;
    let update = move |change: &dyn Fn(&mut ThemeBuilderOptions)| {
        let mut next = options.peek();
        change(&mut next);

        if let Some(handler) = on_change {
            handler.call(create_theme_builder_tokens(&next));
        }

        options.set(next);
    };
    let manual = current.mode == ThemeBuilderMode::Manual;
    let primary_valid = current
        .primary_color
        .as_deref()
        .is_none_or(|hex| normalize_theme_builder_hex(hex).is_some());
    let secondary_valid = current
        .secondary_color
        .as_deref()
        .is_none_or(|hex| normalize_theme_builder_hex(hex).is_some());
    let has_preview = super::has_content(&props.children);
    let copy_css = css.clone();

    rsx! {
        ThemeBuilder { class: props.class.clone(), glass: props.glass,
            header { h3 { "{props.title}" } }
            div { class: "ui-theme-builder__controls", style: "display:grid;gap:0.5rem",
                Label { r#for: "{id}-hue", "Brand hue" }
                input {
                    class: "ui-slider",
                    "data-ui-theme-brand-hue": "true",
                    id: "{id}-hue",
                    max: "359",
                    min: "0",
                    r#type: "range",
                    value: "{result.hue}",
                    oninput: move |event| {
                        if let Some(hue) = range_value(&event) {
                            update(&|next| next.hue = Some(hue));
                        }
                    },
                }
                Label { r#for: "{id}-accent", "Accent hue" }
                input {
                    class: "ui-slider",
                    "data-ui-theme-accent-hue": "true",
                    id: "{id}-accent",
                    max: "359",
                    min: "0",
                    r#type: "range",
                    value: "{result.accent_hue}",
                    oninput: move |event| {
                        if let Some(hue) = range_value(&event) {
                            update(&|next| next.accent_hue = Some(hue));
                        }
                    },
                }
                div { aria_label: "Color scheme", role: "group", style: "display:flex;gap:0.5rem",
                    for scheme in [ThemeBuilderScheme::Light, ThemeBuilderScheme::Dark] {
                        Button {
                            key: "{scheme.as_str()}",
                            aria_pressed: if current.scheme == scheme { "true" } else { "false" },
                            "data-ui-theme-scheme": scheme.as_str(),
                            size: ButtonSize::Sm,
                            variant: if current.scheme == scheme { ButtonVariant::Secondary } else { ButtonVariant::Outline },
                            onclick: move |_| update(&|next| next.scheme = scheme),
                            if scheme == ThemeBuilderScheme::Light { "Light" } else { "Dark" }
                        }
                    }
                }
                div { aria_label: "Color mode", role: "group", style: "display:flex;gap:0.5rem",
                    for mode in [ThemeBuilderMode::Generated, ThemeBuilderMode::Manual] {
                        Button {
                            key: "{mode.as_str()}",
                            aria_pressed: if current.mode == mode { "true" } else { "false" },
                            "data-ui-theme-mode": mode.as_str(),
                            size: ButtonSize::Sm,
                            variant: if current.mode == mode { ButtonVariant::Secondary } else { ButtonVariant::Outline },
                            onclick: move |_| update(&|next| next.mode = mode),
                            if mode == ThemeBuilderMode::Generated { "Generated" } else { "Manual" }
                        }
                    }
                }
                if manual {
                    Label { r#for: "{id}-primary", "Primary color" }
                    Input {
                        aria_invalid: (!primary_valid).then_some("true"),
                        "data-ui-theme-primary-hex": "true",
                        id: "{id}-primary",
                        placeholder: "#6d28d9",
                        value: current.primary_color.clone().unwrap_or_default(),
                        oninput: move |event: FormEvent| update(&|next| next.primary_color = Some(event.value()).filter(|hex| !hex.is_empty())),
                    }
                    Label { r#for: "{id}-secondary", "Secondary color" }
                    Input {
                        aria_invalid: (!secondary_valid).then_some("true"),
                        "data-ui-theme-secondary-hex": "true",
                        id: "{id}-secondary",
                        placeholder: "#0d9488",
                        value: current.secondary_color.clone().unwrap_or_default(),
                        oninput: move |event: FormEvent| update(&|next| next.secondary_color = Some(event.value()).filter(|hex| !hex.is_empty())),
                    }
                }
                Label { r#for: "{id}-radius", "Radius scale" }
                input {
                    class: "ui-slider",
                    "data-ui-theme-radius-scale": "true",
                    id: "{id}-radius",
                    max: "2",
                    min: "0",
                    step: "0.05",
                    r#type: "range",
                    value: "{current.radius_scale.unwrap_or(1.0)}",
                    oninput: move |event| {
                        if let Some(scale) = range_value(&event) {
                            update(&|next| next.radius_scale = Some(scale));
                        }
                    },
                }
                Label { r#for: "{id}-spacing", "Spacing scale" }
                input {
                    class: "ui-slider",
                    "data-ui-theme-spacing-scale": "true",
                    id: "{id}-spacing",
                    max: "1.5",
                    min: "0.5",
                    step: "0.05",
                    r#type: "range",
                    value: "{current.spacing_scale.unwrap_or(1.0)}",
                    oninput: move |event| {
                        if let Some(scale) = range_value(&event) {
                            update(&|next| next.spacing_scale = Some(scale));
                        }
                    },
                }
            }
            div { "data-ui-theme-preview": "true", style: "{style}",
                if has_preview {
                    {props.children}
                } else {
                    div { style: "display:flex;gap:0.5rem;padding:0.5rem",
                        span { "data-ui-swatch": "true", style: "--ui-swatch:hsl(var(--brand))" }
                        span { "data-ui-swatch": "true", style: "--ui-swatch:hsl(var(--accent))" }
                    }
                }
            }
            div { style: "display:flex;gap:0.5rem;flex-wrap:wrap;align-items:center",
                Button {
                    "data-ui-theme-export": "true",
                    onclick: move |_| {
                        let css = copy_css.clone();

                        spawn(async move {
                            let eval = document::eval(
                                "const css = await dioxus.recv(); await navigator.clipboard.writeText(css); return true;",
                            );
                            let copied = eval.send(css).is_ok() && eval.await.is_ok();

                            copy_status.set(if copied { "Copied".to_string() } else { "Copy unavailable".to_string() });
                        });
                    },
                    "Copy CSS"
                }
                span { aria_live: "polite", role: "status", "{copy_status}" }
            }
            textarea {
                aria_label: "Theme CSS",
                class: "ui-textarea",
                "data-ui-theme-output": "true",
                readonly: true,
                rows: "8",
                value: "{css}",
            }
        }
    }
}