Skip to main content

lumen_dioxus/
form.rs

1//! Form primitives: `Label`, `Input`, `Textarea`, `Field`, `FieldError`, `Checkbox`, and `Switch`.
2
3use dioxus::prelude::*;
4
5use crate::class::{Glass, compose};
6
7/// Field state shared with the controls and error inside a [`Field`].
8#[derive(Clone, Debug, PartialEq)]
9struct FieldContext {
10    control_id: Option<String>,
11    invalid: bool,
12}
13
14impl FieldContext {
15    fn error_id(&self) -> Option<String> {
16        self.control_id.as_ref().map(|id| format!("{id}-error"))
17    }
18}
19
20fn use_field() -> Option<FieldContext> {
21    try_use_context::<Signal<FieldContext>>().map(|field| field.read().clone())
22}
23
24/// `aria-invalid` and `aria-describedby` for a control inside a [`Field`], mirroring what the
25/// Lumen web runtime sets after hydration.
26pub(crate) fn use_field_control_aria() -> (Option<&'static str>, Option<String>) {
27    match use_field() {
28        Some(field) if field.invalid => (Some("true"), field.error_id()),
29        _ => (None, None),
30    }
31}
32
33/// Removes the app's own `aria-describedby` from spread attributes and joins it with the field
34/// error id, so a control inside an invalid [`Field`] renders one attribute listing both.
35pub(crate) fn merge_described_by(
36    attributes: &mut Vec<Attribute>,
37    field_error: Option<&str>,
38) -> Option<String> {
39    let own = attributes
40        .iter()
41        .position(|attribute| attribute.name == "aria-describedby")
42        .and_then(|index| match attributes.remove(index).value {
43            dioxus::dioxus_core::AttributeValue::Text(text) => Some(text),
44            _ => None,
45        });
46    let mut ids: Vec<&str> = Vec::new();
47
48    for id in own
49        .as_deref()
50        .into_iter()
51        .chain(field_error)
52        .flat_map(str::split_whitespace)
53    {
54        if !ids.contains(&id) {
55            ids.push(id);
56        }
57    }
58
59    (!ids.is_empty()).then(|| ids.join(" "))
60}
61
62/// Props for [`Label`].
63#[derive(Props, Clone, PartialEq)]
64pub struct LabelProps {
65    /// Extra classes appended after the Lumen class.
66    #[props(into)]
67    pub class: Option<String>,
68    /// Any other `<label>` or global attribute, such as `r#for`.
69    #[props(extends = GlobalAttributes, extends = label)]
70    pub attributes: Vec<Attribute>,
71    /// Label text.
72    pub children: Element,
73}
74
75/// A form label.
76#[component]
77pub fn Label(props: LabelProps) -> Element {
78    let class = compose([Some("ui-label"), props.class.as_deref()]);
79
80    rsx! {
81        label { class, ..props.attributes, {props.children} }
82    }
83}
84
85/// Height of a text control.
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
87#[non_exhaustive]
88pub enum ControlSize {
89    /// Default control height.
90    #[default]
91    Default,
92    /// Compact control.
93    Sm,
94    /// Large control.
95    Lg,
96}
97
98impl ControlSize {
99    fn input_class(self) -> Option<&'static str> {
100        match self {
101            Self::Default => None,
102            Self::Sm => Some("ui-input--sm"),
103            Self::Lg => Some("ui-input--lg"),
104        }
105    }
106}
107
108/// Props for [`Input`].
109#[derive(Props, Clone, PartialEq)]
110pub struct InputProps {
111    /// The native input type. Defaults to `text`.
112    #[props(default = "text".to_string(), into)]
113    pub r#type: String,
114    /// Control height.
115    #[props(default)]
116    pub visual_size: ControlSize,
117    /// Extra classes appended after the Lumen classes.
118    #[props(into)]
119    pub class: Option<String>,
120    /// Fires on every edit.
121    pub oninput: Option<EventHandler<FormEvent>>,
122    /// Fires when the value is committed.
123    pub onchange: Option<EventHandler<FormEvent>>,
124    /// Any other `<input>` or global attribute, such as `id`, `value`, or `placeholder`.
125    #[props(extends = GlobalAttributes, extends = input)]
126    pub attributes: Vec<Attribute>,
127}
128
129/// A single-line text input.
130#[component]
131pub fn Input(mut props: InputProps) -> Element {
132    let (aria_invalid, field_error) = use_field_control_aria();
133    let aria_describedby = merge_described_by(&mut props.attributes, field_error.as_deref());
134    let class = compose([
135        Some("ui-input"),
136        props.visual_size.input_class(),
137        props.class.as_deref(),
138    ]);
139    let (oninput, onchange) = (props.oninput, props.onchange);
140
141    rsx! {
142        input {
143            aria_describedby,
144            aria_invalid,
145            class,
146            r#type: props.r#type,
147            oninput: move |event| {
148                if let Some(handler) = oninput {
149                    handler.call(event);
150                }
151            },
152            onchange: move |event| {
153                if let Some(handler) = onchange {
154                    handler.call(event);
155                }
156            },
157            ..props.attributes,
158        }
159    }
160}
161
162/// Props for [`Textarea`].
163#[derive(Props, Clone, PartialEq)]
164pub struct TextareaProps {
165    /// Visible rows. Defaults to 4.
166    #[props(default = 4)]
167    pub rows: u32,
168    /// Extra classes appended after the Lumen class.
169    #[props(into)]
170    pub class: Option<String>,
171    /// Fires on every edit.
172    pub oninput: Option<EventHandler<FormEvent>>,
173    /// Any other `<textarea>` or global attribute, such as `id` or `value`.
174    #[props(extends = GlobalAttributes, extends = textarea)]
175    pub attributes: Vec<Attribute>,
176}
177
178/// A multi-line text input.
179#[component]
180pub fn Textarea(mut props: TextareaProps) -> Element {
181    let (aria_invalid, field_error) = use_field_control_aria();
182    let aria_describedby = merge_described_by(&mut props.attributes, field_error.as_deref());
183    let class = compose([Some("ui-textarea"), props.class.as_deref()]);
184    let oninput = props.oninput;
185
186    rsx! {
187        textarea {
188            aria_describedby,
189            aria_invalid,
190            class,
191            rows: "{props.rows}",
192            oninput: move |event| {
193                if let Some(handler) = oninput {
194                    handler.call(event);
195                }
196            },
197            ..props.attributes,
198        }
199    }
200}
201
202/// Props for [`Field`].
203#[derive(Props, Clone, PartialEq)]
204pub struct FieldProps {
205    /// Id of the control this field labels and validates.
206    #[props(into)]
207    pub control_id: Option<String>,
208    /// Ids of descriptions for the control, added to `data-ui-field-describedby`.
209    #[props(into)]
210    pub described_by: Option<String>,
211    /// `aria-describedby` of the field element itself; also added to `data-ui-field-describedby`.
212    #[props(into)]
213    pub aria_describedby: Option<String>,
214    /// Marks the field and its control as invalid.
215    #[props(default)]
216    pub invalid: bool,
217    /// Glass intensity.
218    #[props(default, into)]
219    pub glass: Glass,
220    /// Extra classes appended after the Lumen classes.
221    #[props(into)]
222    pub class: Option<String>,
223    /// Any other `<div>` or global attribute.
224    #[props(extends = GlobalAttributes, extends = div)]
225    pub attributes: Vec<Attribute>,
226    /// Label, control, description, and error.
227    pub children: Element,
228}
229
230/// Groups a label, a control, and its validation message.
231///
232/// Controls inside an invalid field get `aria-invalid="true"` and point `aria-describedby`
233/// at the [`FieldError`], which is what the web runtime does after hydration.
234#[component]
235pub fn Field(props: FieldProps) -> Element {
236    let context = FieldContext {
237        control_id: props.control_id.clone(),
238        invalid: props.invalid,
239    };
240    let mut shared = use_context_provider(|| Signal::new(context.clone()));
241
242    use_effect(use_reactive((&context,), move |(context,)| {
243        if *shared.peek() != context {
244            shared.set(context);
245        }
246    }));
247
248    let glass = props.glass.class("ui-field");
249    let class = compose([Some("ui-field"), glass.as_deref(), props.class.as_deref()]);
250    let field_described_by = Some(compose([
251        props.aria_describedby.as_deref(),
252        props.described_by.as_deref(),
253    ]))
254    .filter(|ids| !ids.is_empty());
255
256    rsx! {
257        div {
258            aria_describedby: props.aria_describedby,
259            class,
260            "data-invalid": props.invalid.then_some("true"),
261            "data-ui-field": "true",
262            "data-ui-field-control": props.control_id,
263            "data-ui-field-describedby": field_described_by,
264            ..props.attributes,
265            {props.children}
266        }
267    }
268}
269
270/// Props for [`FieldError`].
271#[derive(Props, Clone, PartialEq)]
272pub struct FieldErrorProps {
273    /// The validation message. The element is hidden while there is no message.
274    #[props(into)]
275    pub message: Option<String>,
276    /// Extra classes appended after the Lumen class.
277    #[props(into)]
278    pub class: Option<String>,
279    /// Any other `<p>` or global attribute.
280    #[props(extends = GlobalAttributes, extends = p)]
281    pub attributes: Vec<Attribute>,
282}
283
284/// The validation message of a [`Field`].
285#[component]
286pub fn FieldError(props: FieldErrorProps) -> Element {
287    let id = use_field().and_then(|field| field.error_id());
288    let class = compose([Some("ui-field-error"), props.class.as_deref()]);
289    let hidden = props.message.as_deref().is_none_or(str::is_empty);
290
291    rsx! {
292        p {
293            class,
294            "data-ui-field-error": "true",
295            hidden,
296            id,
297            ..props.attributes,
298            if let Some(message) = props.message {
299                "{message}"
300            }
301        }
302    }
303}
304
305/// Props for [`Checkbox`] and [`Switch`].
306#[derive(Props, Clone, PartialEq)]
307pub struct CheckboxProps {
308    /// Controlled state. Leave unset to let the control manage itself.
309    pub checked: Option<bool>,
310    /// Initial state when uncontrolled.
311    #[props(default)]
312    pub default_checked: bool,
313    /// Shows the mixed state (`aria-checked="mixed"`), as for a "select all" row. Activating the
314    /// control still reports `true`; clear this prop when the app resolves the mix.
315    #[props(default)]
316    pub indeterminate: bool,
317    /// Disables the control.
318    #[props(default)]
319    pub disabled: bool,
320    /// Form field name. When set and checked, a hidden input submits `value`.
321    #[props(into)]
322    pub name: Option<String>,
323    /// Submitted value when checked. Defaults to `on`, like a native checkbox.
324    #[props(default = "on".to_string(), into)]
325    pub value: String,
326    /// Called with the new checked state.
327    pub onchange: Option<EventHandler<bool>>,
328    /// Extra classes appended after the Lumen class.
329    #[props(into)]
330    pub class: Option<String>,
331    /// Any other `<button>` or global attribute. Name the control with `aria_label`,
332    /// `aria_labelledby`, or a wrapping `<label>`.
333    #[props(extends = GlobalAttributes, extends = button)]
334    pub attributes: Vec<Attribute>,
335}
336
337fn checked_control(base: &'static str, role: &'static str, mut props: CheckboxProps) -> Element {
338    let mut internal = use_signal(|| props.default_checked);
339    let controlled = props.checked;
340    let checked = controlled.unwrap_or_else(|| *internal.read());
341    let aria_checked = match (props.indeterminate, checked) {
342        (true, _) => "mixed",
343        (false, true) => "true",
344        (false, false) => "false",
345    };
346    let (aria_invalid, field_error) = use_field_control_aria();
347    let aria_describedby = merge_described_by(&mut props.attributes, field_error.as_deref());
348    let class = compose([Some(base), props.class.as_deref()]);
349    let onchange = props.onchange;
350    let disabled = props.disabled;
351    let indeterminate = props.indeterminate;
352    let submitted = props.name.filter(|_| checked && !indeterminate);
353
354    rsx! {
355        button {
356            aria_checked,
357            aria_describedby,
358            aria_invalid,
359            class,
360            disabled,
361            role,
362            r#type: "button",
363            onclick: move |_| {
364                if disabled {
365                    return;
366                }
367
368                let next = indeterminate || !checked;
369
370                if controlled.is_none() {
371                    internal.set(next);
372                }
373
374                if let Some(handler) = onchange {
375                    handler.call(next);
376                }
377            },
378            ..props.attributes,
379        }
380        if let Some(name) = submitted {
381            input { r#type: "hidden", name, value: props.value }
382        }
383    }
384}
385
386/// Props for [`Switch`]; the same as [`CheckboxProps`].
387pub type SwitchProps = CheckboxProps;
388
389/// A checkbox that renders the same in browsers and in Dioxus Native.
390///
391/// It is a `<button role="checkbox">` with `aria-checked`, because Blitz does not yet support
392/// `appearance: none` on native inputs. Space and click toggle it.
393#[component]
394pub fn Checkbox(props: CheckboxProps) -> Element {
395    checked_control("ui-checkbox", "checkbox", props)
396}
397
398/// An on/off switch, rendered as `<button role="switch">` for the same reason as [`Checkbox`].
399#[component]
400pub fn Switch(props: SwitchProps) -> Element {
401    checked_control("ui-switch", "switch", props)
402}