lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `CheckboxCard` and `RadioCard`: descriptive choices that read as cards.
//!
//! lumen-react renders a native `<input type="checkbox|radio">` inside the card's `<label>`. Blitz
//! (Dioxus Native) draws native inputs itself and ignores `appearance: none`, so these cards render
//! the control as a `<button role="checkbox|radio">` with `aria-checked`, like the foundation
//! [`Checkbox`](crate::Checkbox). The card root mirrors the state in `data-state`, `data-disabled`,
//! and `data-invalid`, because Blitz cannot parse the `:has()` selectors that style the web card.

use std::rc::Rc;

use dioxus::prelude::*;

use super::checkbox_group::use_checkbox_group_disabled;
use super::radio_group::{
    RadioGroupContext, is_space, use_radio_group_context, use_radio_registration,
};
use crate::class::compose;
use crate::hooks::{use_controllable, use_id_or};
use crate::overlay::focus_element;

/// Surface style of a [`CheckboxCard`] or [`RadioCard`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum CheckboxCardVariant {
    /// A bordered card on the surface color.
    #[default]
    Outline,
    /// A bordered card on the muted surface color.
    Soft,
}

impl CheckboxCardVariant {
    fn class(self) -> &'static str {
        match self {
            Self::Outline => "ui-selection-card--outline",
            Self::Soft => "ui-selection-card--soft",
        }
    }
}

/// Surface style of a [`RadioCard`]; the same type as [`CheckboxCardVariant`].
pub type RadioCardVariant = CheckboxCardVariant;

/// Props for [`CheckboxCard`] and [`RadioCard`].
#[derive(Props, Clone, PartialEq)]
pub struct CheckboxCardProps {
    /// The visible label. It names the control unless `aria_label` or `aria_labelledby` is set.
    #[props(into)]
    pub label: String,
    /// Supporting text below the label, added to the control's `aria-describedby`.
    #[props(into)]
    pub description: Option<String>,
    /// Decorative content before the text, hidden from assistive technology.
    pub icon: Option<Element>,
    /// Surface style.
    #[props(default)]
    pub variant: CheckboxCardVariant,
    /// Marks the choice as invalid (`aria-invalid="true"`).
    #[props(default)]
    pub invalid: bool,
    /// Disables the card.
    #[props(default)]
    pub disabled: bool,
    /// Controlled state. Leave unset to let the card manage itself. Ignored inside a
    /// [`RadioGroup`](crate::RadioGroup), which owns the selection.
    pub checked: Option<bool>,
    /// Initial state when uncontrolled. Ignored inside a [`RadioGroup`](crate::RadioGroup).
    #[props(default)]
    pub default_checked: bool,
    /// Called with the new checked state. A radio card only reports `true`, when it becomes
    /// selected. Not called inside a [`RadioGroup`](crate::RadioGroup); use its
    /// `on_value_change`.
    pub onchange: Option<EventHandler<bool>>,
    /// Form field name. When set and checked, a hidden input submits `value`. Inside a
    /// [`RadioGroup`](crate::RadioGroup), set the group's `name` instead.
    #[props(into)]
    pub name: Option<String>,
    /// Submitted value, and the value a radio card selects inside a
    /// [`RadioGroup`](crate::RadioGroup). Defaults to `on`, like a native input.
    #[props(default = "on".to_string(), into)]
    pub value: String,
    /// Id of the control; generated when unset. The label and description ids derive from it.
    #[props(into)]
    pub id: Option<String>,
    /// Accessible name that replaces the visible label.
    #[props(into)]
    pub aria_label: Option<String>,
    /// Ids of elements that name the control, instead of the visible label.
    #[props(into)]
    pub aria_labelledby: Option<String>,
    /// Ids of extra descriptions, such as an external error, kept before the card description.
    #[props(into)]
    pub aria_describedby: Option<String>,
    /// Extra classes appended to the card root.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<button>` or global attribute, applied to the control.
    #[props(extends = GlobalAttributes, extends = button)]
    pub attributes: Vec<Attribute>,
    /// Non-interactive metadata below the description.
    pub children: Element,
}

/// Props for [`RadioCard`]; the same as [`CheckboxCardProps`].
pub type RadioCardProps = CheckboxCardProps;

#[derive(Clone, Copy, PartialEq, Eq)]
enum SelectionKind {
    Checkbox,
    Radio,
}

/// Whether an element was passed, as opposed to the default empty placeholder.
fn has_content(element: &Element) -> bool {
    element
        .as_ref()
        .is_ok_and(|node| *node != VNode::placeholder())
}

#[allow(clippy::too_many_lines)]
fn selection_card(kind: SelectionKind, props: CheckboxCardProps) -> Element {
    let control_id = use_id_or(props.id.as_deref());
    let group: Option<RadioGroupContext> = match kind {
        SelectionKind::Radio => use_radio_group_context(),
        SelectionKind::Checkbox => None,
    };
    let state = use_controllable(props.checked, || props.default_checked, props.onchange);
    let order = use_radio_registration(group.as_ref(), &props.value, props.disabled);
    let mut mounted = use_hook(|| CopyValue::new(None::<Rc<MountedData>>));
    let checkbox_group_disabled = use_checkbox_group_disabled();

    let checked = group.map_or_else(|| state.get(), |group| group.is_selected(&props.value));
    let disabled =
        props.disabled || checkbox_group_disabled || group.is_some_and(|group| group.is_disabled());
    let tab_stop = group.map(|group| group.is_tab_stop(order, &props.value, props.disabled));

    let label_id = format!("{control_id}-label");
    let description = props.description.clone().filter(|text| !text.is_empty());
    let description_id = description
        .as_ref()
        .map(|_| format!("{control_id}-description"));
    let described_by = Some(compose([
        props.aria_describedby.as_deref(),
        description_id.as_deref(),
    ]))
    .filter(|ids| !ids.is_empty());
    let aria_label = props.aria_label.clone().filter(|label| !label.is_empty());
    let labelled_by = props
        .aria_labelledby
        .clone()
        .or_else(|| aria_label.is_none().then(|| label_id.clone()));

    let (type_class, slot, control_class, role) = match kind {
        SelectionKind::Checkbox => (
            "ui-checkbox-card",
            "checkbox-card",
            "ui-checkbox",
            "checkbox",
        ),
        SelectionKind::Radio => ("ui-radio-card", "radio-card", "ui-dioxus-radio", "radio"),
    };
    let class = compose([
        Some("ui-selection-card"),
        Some(type_class),
        Some(props.variant.class()),
        props.class.as_deref(),
    ]);
    let submitted = props
        .name
        .clone()
        .filter(|_| group.is_none() && checked && !disabled);
    let value = props.value.clone();
    let click_value = props.value.clone();

    // Checkbox: toggle. Radio: select (a selected radio stays selected); inside a group the group
    // owns the value.
    let activate = move |value: &str| match (kind, group) {
        (SelectionKind::Checkbox, _) => state.set(!state.peek()),
        (SelectionKind::Radio, Some(group)) => group.activate(order, value),
        (SelectionKind::Radio, None) => state.set(true),
    };

    rsx! {
        span {
            class,
            "data-disabled": disabled.then_some("true"),
            "data-invalid": props.invalid.then_some("true"),
            "data-slot": slot,
            "data-state": if checked { "checked" } else { "unchecked" },
            label {
                onclick: move |event| {
                    // The card handles the click itself, so the browser must not forward it to the
                    // control a second time.
                    event.prevent_default();

                    if disabled {
                        return;
                    }

                    activate(&click_value);

                    if group.is_none() {
                        focus_element(mounted.peek().clone());
                    }
                },
                button {
                    aria_checked: if checked { "true" } else { "false" },
                    aria_describedby: described_by,
                    aria_invalid: props.invalid.then_some("true"),
                    aria_label,
                    aria_labelledby: labelled_by,
                    class: control_class,
                    disabled,
                    id: control_id,
                    role,
                    tabindex: tab_stop.map(|stop| if stop { "0" } else { "-1" }),
                    r#type: "button",
                    value,
                    onkeydown: move |event| {
                        if disabled {
                            return;
                        }

                        match (kind, group) {
                            (SelectionKind::Radio, Some(group)) => group.handle_key(order, &event),
                            (SelectionKind::Radio, None) if is_space(&event.key()) => {
                                event.prevent_default();
                                activate("");
                            }
                            _ => {}
                        }
                    },
                    onkeyup: move |event| {
                        // Browsers toggle a focused button on Space key-up; preventing that default
                        // and toggling here gives one toggle on the web and on Dioxus Native.
                        if kind == SelectionKind::Checkbox && !disabled && is_space(&event.key()) {
                            event.prevent_default();
                            activate("");
                        }
                    },
                    onfocus: move |_| {
                        if let Some(group) = group {
                            group.remember(order);
                        }
                    },
                    onmounted: move |event| {
                        let data = event.data();

                        if let Some(group) = group {
                            group.set_mounted(order, data.clone());
                        }

                        mounted.set(Some(data));
                    },
                    ..props.attributes,
                }
                if let Some(icon) = props.icon {
                    span { aria_hidden: "true", "data-slot": "selection-card-icon", {icon} }
                }
                span { "data-slot": "selection-card-content",
                    span { "data-slot": "selection-card-label", id: label_id, "{props.label}" }
                    if let (Some(description), Some(id)) = (description, description_id) {
                        span { "data-slot": "selection-card-description", id, "{description}" }
                    }
                    if has_content(&props.children) {
                        span { "data-slot": "selection-card-addon", {props.children} }
                    }
                }
            }
            if let Some(name) = submitted {
                input { r#type: "hidden", name, value: props.value }
            }
        }
    }
}

/// A descriptive checkbox choice: a card with a label, an optional description, icon, and
/// metadata.
///
/// The control is a `<button role="checkbox" class="ui-checkbox">`, named by the visible label and
/// described by the description. A click anywhere on the card toggles it, and so does Space on
/// every renderer. When `name` is set and the card is checked, a hidden input submits `value`.
#[component]
pub fn CheckboxCard(props: CheckboxCardProps) -> Element {
    selection_card(SelectionKind::Checkbox, props)
}

/// A descriptive radio choice: a card with a label, an optional description, icon, and metadata.
///
/// Put radio cards in a [`RadioGroup`](crate::RadioGroup) with a `legend`: the group owns the
/// selected value (each card selects its `value`), submits it, and gives the cards arrow-key
/// navigation. Outside a group, a radio card keeps its own `checked` state, so exclusive choices
/// need `checked` from app state. The control is a `<button role="radio" class="ui-dioxus-radio">`.
#[component]
pub fn RadioCard(props: RadioCardProps) -> Element {
    selection_card(SelectionKind::Radio, props)
}