Skip to main content

lumen_dioxus/inputs/
checkbox_group.rs

1//! `CheckboxGroup` and `CheckboxGroupItem`: a fieldset of independent checkboxes.
2//!
3//! lumen-react's `CheckboxGroup` is a styled `<fieldset>` with an optional legend; each checkbox
4//! inside keeps its own state and submits its own value, like native checkboxes that share a
5//! `name`. [`CheckboxGroupItem`] is a labelled checkbox row that works on every renderer: the whole
6//! row toggles on click and the control toggles on Space, including on Dioxus Native.
7
8// cspell:words fieldset
9
10use std::rc::Rc;
11
12use dioxus::prelude::*;
13
14use super::radio_group::is_space;
15use crate::class::{Orientation, compose};
16use crate::hooks::use_controllable;
17use crate::overlay::focus_element;
18
19/// Group state that the checkboxes inside a [`CheckboxGroup`] read.
20#[derive(Clone, Copy)]
21struct CheckboxGroupContext {
22    disabled: Memo<bool>,
23}
24
25/// Whether the enclosing [`CheckboxGroup`] is disabled. Subscribes the caller.
26pub(crate) fn use_checkbox_group_disabled() -> bool {
27    try_use_context::<CheckboxGroupContext>().is_some_and(|group| *group.disabled.read())
28}
29
30/// Props for [`CheckboxGroup`].
31#[derive(Props, Clone, PartialEq)]
32pub struct CheckboxGroupProps {
33    /// The group's visible label, rendered as its `<legend>`.
34    #[props(into)]
35    pub legend: Option<String>,
36    /// Marks the group as invalid (`aria-invalid` and `data-invalid`).
37    #[props(default)]
38    pub invalid: bool,
39    /// Direction of the choices. Defaults to vertical, like lumen-react.
40    #[props(default = Orientation::Vertical)]
41    pub orientation: Orientation,
42    /// Disables the fieldset and the [`CheckboxGroupItem`]s and
43    /// [`CheckboxCard`](crate::CheckboxCard)s in it. Use this prop rather than a raw `disabled`
44    /// attribute, so row clicks are ignored on every renderer.
45    #[props(default)]
46    pub disabled: bool,
47    /// Extra classes appended after the Lumen classes.
48    #[props(into)]
49    pub class: Option<String>,
50    /// Any other `<fieldset>` or global attribute.
51    #[props(extends = GlobalAttributes, extends = fieldset)]
52    pub attributes: Vec<Attribute>,
53    /// The checkboxes: [`CheckboxGroupItem`]s, [`CheckboxCard`](crate::CheckboxCard)s, or labelled
54    /// [`Checkbox`](crate::Checkbox)es.
55    pub children: Element,
56}
57
58/// A fieldset without a frame that groups related checkboxes under one legend.
59#[component]
60pub fn CheckboxGroup(props: CheckboxGroupProps) -> Element {
61    let disabled = use_memo(use_reactive((&props.disabled,), |(disabled,)| disabled));
62    use_context_provider(|| CheckboxGroupContext { disabled });
63
64    let orientation = props.orientation.as_str();
65    let orientation_class = format!("ui-checkbox-group--{orientation}");
66    let class = compose([
67        Some("ui-checkbox-group"),
68        Some(orientation_class.as_str()),
69        props.class.as_deref(),
70    ]);
71    let invalid = props.invalid.then_some("true");
72    let legend = props.legend.filter(|legend| !legend.is_empty());
73
74    rsx! {
75        fieldset {
76            aria_invalid: invalid,
77            class,
78            "data-invalid": invalid,
79            "data-orientation": orientation,
80            "data-ui-checkbox-group": "true",
81            disabled: props.disabled,
82            ..props.attributes,
83            if let Some(legend) = legend {
84                legend { "{legend}" }
85            }
86            {props.children}
87        }
88    }
89}
90
91/// Props for [`CheckboxGroupItem`].
92#[derive(Props, Clone, PartialEq)]
93pub struct CheckboxGroupItemProps {
94    /// Controlled state. Leave unset to let the checkbox manage itself.
95    pub checked: Option<bool>,
96    /// Initial state when uncontrolled.
97    #[props(default)]
98    pub default_checked: bool,
99    /// Shows the mixed state (`aria-checked="mixed"`), as for a "select all" row. Activating it
100    /// reports `true`; clear this prop when the app resolves the mix.
101    #[props(default)]
102    pub indeterminate: bool,
103    /// Disables the checkbox.
104    #[props(default)]
105    pub disabled: bool,
106    /// Form field name. When set and checked, a hidden input submits `value`.
107    #[props(into)]
108    pub name: Option<String>,
109    /// Submitted value when checked. Defaults to `on`, like a native checkbox.
110    #[props(default = "on".to_string(), into)]
111    pub value: String,
112    /// Called with the new checked state.
113    pub onchange: Option<EventHandler<bool>>,
114    /// Extra classes appended to the row `<label>`.
115    #[props(into)]
116    pub class: Option<String>,
117    /// Any other `<button>` or global attribute, applied to the checkbox control.
118    #[props(extends = GlobalAttributes, extends = button)]
119    pub attributes: Vec<Attribute>,
120    /// The visible label.
121    pub children: Element,
122}
123
124/// One labelled checkbox in a [`CheckboxGroup`].
125///
126/// Renders `<label class="ui-label">` around the same `<button role="checkbox" class="ui-checkbox">`
127/// as [`Checkbox`](crate::Checkbox), followed by the label text. A click anywhere on the row
128/// toggles it, and so does Space on every renderer.
129#[component]
130pub fn CheckboxGroupItem(props: CheckboxGroupItemProps) -> Element {
131    let state = use_controllable(props.checked, || props.default_checked, props.onchange);
132    let mut mounted = use_hook(|| CopyValue::new(None::<Rc<MountedData>>));
133    let group_disabled = use_checkbox_group_disabled();
134    let checked = state.get();
135    let disabled = props.disabled || group_disabled;
136    let indeterminate = props.indeterminate;
137    let onchange = props.onchange;
138    let aria_checked = match (indeterminate, checked) {
139        (true, _) => "mixed",
140        (false, true) => "true",
141        (false, false) => "false",
142    };
143    let class = compose([Some("ui-label"), props.class.as_deref()]);
144    let control_value = props.value.clone();
145    let submitted = props
146        .name
147        .clone()
148        .filter(|_| checked && !indeterminate && !disabled);
149
150    let toggle = move || {
151        if !indeterminate {
152            state.set(!state.peek());
153        } else if state.peek() {
154            // Already checked underneath the mix: still report the activation.
155            if let Some(handler) = onchange {
156                handler.call(true);
157            }
158        } else {
159            state.set(true);
160        }
161    };
162
163    rsx! {
164        label {
165            class,
166            onclick: move |event| {
167                // The row handles the click itself, so the browser must not forward it to the
168                // checkbox a second time.
169                event.prevent_default();
170
171                if !disabled {
172                    toggle();
173                    focus_element(mounted.peek().clone());
174                }
175            },
176            button {
177                aria_checked,
178                class: "ui-checkbox",
179                disabled,
180                role: "checkbox",
181                r#type: "button",
182                value: control_value,
183                onkeyup: move |event| {
184                    // Browsers toggle a focused button on Space key-up; preventing that default and
185                    // toggling here gives one toggle on the web and on Dioxus Native.
186                    if !disabled && is_space(&event.key()) {
187                        event.prevent_default();
188                        toggle();
189                    }
190                },
191                onmounted: move |event| mounted.set(Some(event.data())),
192                ..props.attributes,
193            }
194            " "
195            {props.children}
196        }
197        if let Some(name) = submitted {
198            input { r#type: "hidden", name, value: props.value }
199        }
200    }
201}