Skip to main content

lumen_dioxus/inputs/
selection_card.rs

1//! `CheckboxCard` and `RadioCard`: descriptive choices that read as cards.
2//!
3//! lumen-react renders a native `<input type="checkbox|radio">` inside the card's `<label>`. Blitz
4//! (Dioxus Native) draws native inputs itself and ignores `appearance: none`, so these cards render
5//! the control as a `<button role="checkbox|radio">` with `aria-checked`, like the foundation
6//! [`Checkbox`](crate::Checkbox). The card root mirrors the state in `data-state`, `data-disabled`,
7//! and `data-invalid`, because Blitz cannot parse the `:has()` selectors that style the web card.
8
9use std::rc::Rc;
10
11use dioxus::prelude::*;
12
13use super::checkbox_group::use_checkbox_group_disabled;
14use super::radio_group::{
15    RadioGroupContext, is_space, use_radio_group_context, use_radio_registration,
16};
17use crate::class::compose;
18use crate::hooks::{use_controllable, use_id_or};
19use crate::overlay::focus_element;
20
21/// Surface style of a [`CheckboxCard`] or [`RadioCard`].
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
23#[non_exhaustive]
24pub enum CheckboxCardVariant {
25    /// A bordered card on the surface color.
26    #[default]
27    Outline,
28    /// A bordered card on the muted surface color.
29    Soft,
30}
31
32impl CheckboxCardVariant {
33    fn class(self) -> &'static str {
34        match self {
35            Self::Outline => "ui-selection-card--outline",
36            Self::Soft => "ui-selection-card--soft",
37        }
38    }
39}
40
41/// Surface style of a [`RadioCard`]; the same type as [`CheckboxCardVariant`].
42pub type RadioCardVariant = CheckboxCardVariant;
43
44/// Props for [`CheckboxCard`] and [`RadioCard`].
45#[derive(Props, Clone, PartialEq)]
46pub struct CheckboxCardProps {
47    /// The visible label. It names the control unless `aria_label` or `aria_labelledby` is set.
48    #[props(into)]
49    pub label: String,
50    /// Supporting text below the label, added to the control's `aria-describedby`.
51    #[props(into)]
52    pub description: Option<String>,
53    /// Decorative content before the text, hidden from assistive technology.
54    pub icon: Option<Element>,
55    /// Surface style.
56    #[props(default)]
57    pub variant: CheckboxCardVariant,
58    /// Marks the choice as invalid (`aria-invalid="true"`).
59    #[props(default)]
60    pub invalid: bool,
61    /// Disables the card.
62    #[props(default)]
63    pub disabled: bool,
64    /// Controlled state. Leave unset to let the card manage itself. Ignored inside a
65    /// [`RadioGroup`](crate::RadioGroup), which owns the selection.
66    pub checked: Option<bool>,
67    /// Initial state when uncontrolled. Ignored inside a [`RadioGroup`](crate::RadioGroup).
68    #[props(default)]
69    pub default_checked: bool,
70    /// Called with the new checked state. A radio card only reports `true`, when it becomes
71    /// selected. Not called inside a [`RadioGroup`](crate::RadioGroup); use its
72    /// `on_value_change`.
73    pub onchange: Option<EventHandler<bool>>,
74    /// Form field name. When set and checked, a hidden input submits `value`. Inside a
75    /// [`RadioGroup`](crate::RadioGroup), set the group's `name` instead.
76    #[props(into)]
77    pub name: Option<String>,
78    /// Submitted value, and the value a radio card selects inside a
79    /// [`RadioGroup`](crate::RadioGroup). Defaults to `on`, like a native input.
80    #[props(default = "on".to_string(), into)]
81    pub value: String,
82    /// Id of the control; generated when unset. The label and description ids derive from it.
83    #[props(into)]
84    pub id: Option<String>,
85    /// Accessible name that replaces the visible label.
86    #[props(into)]
87    pub aria_label: Option<String>,
88    /// Ids of elements that name the control, instead of the visible label.
89    #[props(into)]
90    pub aria_labelledby: Option<String>,
91    /// Ids of extra descriptions, such as an external error, kept before the card description.
92    #[props(into)]
93    pub aria_describedby: Option<String>,
94    /// Extra classes appended to the card root.
95    #[props(into)]
96    pub class: Option<String>,
97    /// Any other `<button>` or global attribute, applied to the control.
98    #[props(extends = GlobalAttributes, extends = button)]
99    pub attributes: Vec<Attribute>,
100    /// Non-interactive metadata below the description.
101    pub children: Element,
102}
103
104/// Props for [`RadioCard`]; the same as [`CheckboxCardProps`].
105pub type RadioCardProps = CheckboxCardProps;
106
107#[derive(Clone, Copy, PartialEq, Eq)]
108enum SelectionKind {
109    Checkbox,
110    Radio,
111}
112
113/// Whether an element was passed, as opposed to the default empty placeholder.
114fn has_content(element: &Element) -> bool {
115    element
116        .as_ref()
117        .is_ok_and(|node| *node != VNode::placeholder())
118}
119
120#[allow(clippy::too_many_lines)]
121fn selection_card(kind: SelectionKind, props: CheckboxCardProps) -> Element {
122    let control_id = use_id_or(props.id.as_deref());
123    let group: Option<RadioGroupContext> = match kind {
124        SelectionKind::Radio => use_radio_group_context(),
125        SelectionKind::Checkbox => None,
126    };
127    let state = use_controllable(props.checked, || props.default_checked, props.onchange);
128    let order = use_radio_registration(group.as_ref(), &props.value, props.disabled);
129    let mut mounted = use_hook(|| CopyValue::new(None::<Rc<MountedData>>));
130    let checkbox_group_disabled = use_checkbox_group_disabled();
131
132    let checked = group.map_or_else(|| state.get(), |group| group.is_selected(&props.value));
133    let disabled =
134        props.disabled || checkbox_group_disabled || group.is_some_and(|group| group.is_disabled());
135    let tab_stop = group.map(|group| group.is_tab_stop(order, &props.value, props.disabled));
136
137    let label_id = format!("{control_id}-label");
138    let description = props.description.clone().filter(|text| !text.is_empty());
139    let description_id = description
140        .as_ref()
141        .map(|_| format!("{control_id}-description"));
142    let described_by = Some(compose([
143        props.aria_describedby.as_deref(),
144        description_id.as_deref(),
145    ]))
146    .filter(|ids| !ids.is_empty());
147    let aria_label = props.aria_label.clone().filter(|label| !label.is_empty());
148    let labelled_by = props
149        .aria_labelledby
150        .clone()
151        .or_else(|| aria_label.is_none().then(|| label_id.clone()));
152
153    let (type_class, slot, control_class, role) = match kind {
154        SelectionKind::Checkbox => (
155            "ui-checkbox-card",
156            "checkbox-card",
157            "ui-checkbox",
158            "checkbox",
159        ),
160        SelectionKind::Radio => ("ui-radio-card", "radio-card", "ui-dioxus-radio", "radio"),
161    };
162    let class = compose([
163        Some("ui-selection-card"),
164        Some(type_class),
165        Some(props.variant.class()),
166        props.class.as_deref(),
167    ]);
168    let submitted = props
169        .name
170        .clone()
171        .filter(|_| group.is_none() && checked && !disabled);
172    let value = props.value.clone();
173    let click_value = props.value.clone();
174
175    // Checkbox: toggle. Radio: select (a selected radio stays selected); inside a group the group
176    // owns the value.
177    let activate = move |value: &str| match (kind, group) {
178        (SelectionKind::Checkbox, _) => state.set(!state.peek()),
179        (SelectionKind::Radio, Some(group)) => group.activate(order, value),
180        (SelectionKind::Radio, None) => state.set(true),
181    };
182
183    rsx! {
184        span {
185            class,
186            "data-disabled": disabled.then_some("true"),
187            "data-invalid": props.invalid.then_some("true"),
188            "data-slot": slot,
189            "data-state": if checked { "checked" } else { "unchecked" },
190            label {
191                onclick: move |event| {
192                    // The card handles the click itself, so the browser must not forward it to the
193                    // control a second time.
194                    event.prevent_default();
195
196                    if disabled {
197                        return;
198                    }
199
200                    activate(&click_value);
201
202                    if group.is_none() {
203                        focus_element(mounted.peek().clone());
204                    }
205                },
206                button {
207                    aria_checked: if checked { "true" } else { "false" },
208                    aria_describedby: described_by,
209                    aria_invalid: props.invalid.then_some("true"),
210                    aria_label,
211                    aria_labelledby: labelled_by,
212                    class: control_class,
213                    disabled,
214                    id: control_id,
215                    role,
216                    tabindex: tab_stop.map(|stop| if stop { "0" } else { "-1" }),
217                    r#type: "button",
218                    value,
219                    onkeydown: move |event| {
220                        if disabled {
221                            return;
222                        }
223
224                        match (kind, group) {
225                            (SelectionKind::Radio, Some(group)) => group.handle_key(order, &event),
226                            (SelectionKind::Radio, None) if is_space(&event.key()) => {
227                                event.prevent_default();
228                                activate("");
229                            }
230                            _ => {}
231                        }
232                    },
233                    onkeyup: move |event| {
234                        // Browsers toggle a focused button on Space key-up; preventing that default
235                        // and toggling here gives one toggle on the web and on Dioxus Native.
236                        if kind == SelectionKind::Checkbox && !disabled && is_space(&event.key()) {
237                            event.prevent_default();
238                            activate("");
239                        }
240                    },
241                    onfocus: move |_| {
242                        if let Some(group) = group {
243                            group.remember(order);
244                        }
245                    },
246                    onmounted: move |event| {
247                        let data = event.data();
248
249                        if let Some(group) = group {
250                            group.set_mounted(order, data.clone());
251                        }
252
253                        mounted.set(Some(data));
254                    },
255                    ..props.attributes,
256                }
257                if let Some(icon) = props.icon {
258                    span { aria_hidden: "true", "data-slot": "selection-card-icon", {icon} }
259                }
260                span { "data-slot": "selection-card-content",
261                    span { "data-slot": "selection-card-label", id: label_id, "{props.label}" }
262                    if let (Some(description), Some(id)) = (description, description_id) {
263                        span { "data-slot": "selection-card-description", id, "{description}" }
264                    }
265                    if has_content(&props.children) {
266                        span { "data-slot": "selection-card-addon", {props.children} }
267                    }
268                }
269            }
270            if let Some(name) = submitted {
271                input { r#type: "hidden", name, value: props.value }
272            }
273        }
274    }
275}
276
277/// A descriptive checkbox choice: a card with a label, an optional description, icon, and
278/// metadata.
279///
280/// The control is a `<button role="checkbox" class="ui-checkbox">`, named by the visible label and
281/// described by the description. A click anywhere on the card toggles it, and so does Space on
282/// every renderer. When `name` is set and the card is checked, a hidden input submits `value`.
283#[component]
284pub fn CheckboxCard(props: CheckboxCardProps) -> Element {
285    selection_card(SelectionKind::Checkbox, props)
286}
287
288/// A descriptive radio choice: a card with a label, an optional description, icon, and metadata.
289///
290/// Put radio cards in a [`RadioGroup`](crate::RadioGroup) with a `legend`: the group owns the
291/// selected value (each card selects its `value`), submits it, and gives the cards arrow-key
292/// navigation. Outside a group, a radio card keeps its own `checked` state, so exclusive choices
293/// need `checked` from app state. The control is a `<button role="radio" class="ui-dioxus-radio">`.
294#[component]
295pub fn RadioCard(props: RadioCardProps) -> Element {
296    selection_card(SelectionKind::Radio, props)
297}