lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `CheckboxGroup` and `CheckboxGroupItem`: a fieldset of independent checkboxes.
//!
//! lumen-react's `CheckboxGroup` is a styled `<fieldset>` with an optional legend; each checkbox
//! inside keeps its own state and submits its own value, like native checkboxes that share a
//! `name`. [`CheckboxGroupItem`] is a labelled checkbox row that works on every renderer: the whole
//! row toggles on click and the control toggles on Space, including on Dioxus Native.

// cspell:words fieldset

use std::rc::Rc;

use dioxus::prelude::*;

use super::radio_group::is_space;
use crate::class::{Orientation, compose};
use crate::hooks::use_controllable;
use crate::overlay::focus_element;

/// Group state that the checkboxes inside a [`CheckboxGroup`] read.
#[derive(Clone, Copy)]
struct CheckboxGroupContext {
    disabled: Memo<bool>,
}

/// Whether the enclosing [`CheckboxGroup`] is disabled. Subscribes the caller.
pub(crate) fn use_checkbox_group_disabled() -> bool {
    try_use_context::<CheckboxGroupContext>().is_some_and(|group| *group.disabled.read())
}

/// Props for [`CheckboxGroup`].
#[derive(Props, Clone, PartialEq)]
pub struct CheckboxGroupProps {
    /// The group's visible label, rendered as its `<legend>`.
    #[props(into)]
    pub legend: Option<String>,
    /// Marks the group as invalid (`aria-invalid` and `data-invalid`).
    #[props(default)]
    pub invalid: bool,
    /// Direction of the choices. Defaults to vertical, like lumen-react.
    #[props(default = Orientation::Vertical)]
    pub orientation: Orientation,
    /// Disables the fieldset and the [`CheckboxGroupItem`]s and
    /// [`CheckboxCard`](crate::CheckboxCard)s in it. Use this prop rather than a raw `disabled`
    /// attribute, so row clicks are ignored on every renderer.
    #[props(default)]
    pub disabled: bool,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<fieldset>` or global attribute.
    #[props(extends = GlobalAttributes, extends = fieldset)]
    pub attributes: Vec<Attribute>,
    /// The checkboxes: [`CheckboxGroupItem`]s, [`CheckboxCard`](crate::CheckboxCard)s, or labelled
    /// [`Checkbox`](crate::Checkbox)es.
    pub children: Element,
}

/// A fieldset without a frame that groups related checkboxes under one legend.
#[component]
pub fn CheckboxGroup(props: CheckboxGroupProps) -> Element {
    let disabled = use_memo(use_reactive((&props.disabled,), |(disabled,)| disabled));
    use_context_provider(|| CheckboxGroupContext { disabled });

    let orientation = props.orientation.as_str();
    let orientation_class = format!("ui-checkbox-group--{orientation}");
    let class = compose([
        Some("ui-checkbox-group"),
        Some(orientation_class.as_str()),
        props.class.as_deref(),
    ]);
    let invalid = props.invalid.then_some("true");
    let legend = props.legend.filter(|legend| !legend.is_empty());

    rsx! {
        fieldset {
            aria_invalid: invalid,
            class,
            "data-invalid": invalid,
            "data-orientation": orientation,
            "data-ui-checkbox-group": "true",
            disabled: props.disabled,
            ..props.attributes,
            if let Some(legend) = legend {
                legend { "{legend}" }
            }
            {props.children}
        }
    }
}

/// Props for [`CheckboxGroupItem`].
#[derive(Props, Clone, PartialEq)]
pub struct CheckboxGroupItemProps {
    /// Controlled state. Leave unset to let the checkbox manage itself.
    pub checked: Option<bool>,
    /// Initial state when uncontrolled.
    #[props(default)]
    pub default_checked: bool,
    /// Shows the mixed state (`aria-checked="mixed"`), as for a "select all" row. Activating it
    /// reports `true`; clear this prop when the app resolves the mix.
    #[props(default)]
    pub indeterminate: bool,
    /// Disables the checkbox.
    #[props(default)]
    pub disabled: bool,
    /// Form field name. When set and checked, a hidden input submits `value`.
    #[props(into)]
    pub name: Option<String>,
    /// Submitted value when checked. Defaults to `on`, like a native checkbox.
    #[props(default = "on".to_string(), into)]
    pub value: String,
    /// Called with the new checked state.
    pub onchange: Option<EventHandler<bool>>,
    /// Extra classes appended to the row `<label>`.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<button>` or global attribute, applied to the checkbox control.
    #[props(extends = GlobalAttributes, extends = button)]
    pub attributes: Vec<Attribute>,
    /// The visible label.
    pub children: Element,
}

/// One labelled checkbox in a [`CheckboxGroup`].
///
/// Renders `<label class="ui-label">` around the same `<button role="checkbox" class="ui-checkbox">`
/// as [`Checkbox`](crate::Checkbox), followed by the label text. A click anywhere on the row
/// toggles it, and so does Space on every renderer.
#[component]
pub fn CheckboxGroupItem(props: CheckboxGroupItemProps) -> Element {
    let state = use_controllable(props.checked, || props.default_checked, props.onchange);
    let mut mounted = use_hook(|| CopyValue::new(None::<Rc<MountedData>>));
    let group_disabled = use_checkbox_group_disabled();
    let checked = state.get();
    let disabled = props.disabled || group_disabled;
    let indeterminate = props.indeterminate;
    let onchange = props.onchange;
    let aria_checked = match (indeterminate, checked) {
        (true, _) => "mixed",
        (false, true) => "true",
        (false, false) => "false",
    };
    let class = compose([Some("ui-label"), props.class.as_deref()]);
    let control_value = props.value.clone();
    let submitted = props
        .name
        .clone()
        .filter(|_| checked && !indeterminate && !disabled);

    let toggle = move || {
        if !indeterminate {
            state.set(!state.peek());
        } else if state.peek() {
            // Already checked underneath the mix: still report the activation.
            if let Some(handler) = onchange {
                handler.call(true);
            }
        } else {
            state.set(true);
        }
    };

    rsx! {
        label {
            class,
            onclick: move |event| {
                // The row handles the click itself, so the browser must not forward it to the
                // checkbox a second time.
                event.prevent_default();

                if !disabled {
                    toggle();
                    focus_element(mounted.peek().clone());
                }
            },
            button {
                aria_checked,
                class: "ui-checkbox",
                disabled,
                role: "checkbox",
                r#type: "button",
                value: control_value,
                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 !disabled && is_space(&event.key()) {
                        event.prevent_default();
                        toggle();
                    }
                },
                onmounted: move |event| mounted.set(Some(event.data())),
                ..props.attributes,
            }
            " "
            {props.children}
        }
        if let Some(name) = submitted {
            input { r#type: "hidden", name, value: props.value }
        }
    }
}