Skip to main content

lumen_dioxus/inputs/
input_form.rs

1//! `Form`: a form with Lumen's spacing and a submission status.
2
3// cspell:words onreset
4
5use dioxus::prelude::*;
6
7use crate::class::compose;
8
9/// Where a [`Form`] is in its submission, also its `data-status` value.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
11#[non_exhaustive]
12pub enum FormStatus {
13    /// Nothing is happening.
14    #[default]
15    Idle,
16    /// The values are being checked.
17    Validating,
18    /// The values are being sent. The form sets `aria-busy="true"`.
19    Submitting,
20    /// The submission succeeded. Password fields in the form hide their text again.
21    Success,
22    /// The submission failed.
23    Error,
24}
25
26impl FormStatus {
27    /// The `data-status` value.
28    pub fn as_str(self) -> &'static str {
29        match self {
30            Self::Idle => "idle",
31            Self::Validating => "validating",
32            Self::Submitting => "submitting",
33            Self::Success => "success",
34            Self::Error => "error",
35        }
36    }
37}
38
39/// Events a [`Form`] shares with the controls inside it: how many times the status became
40/// `Success` and how many times the form was reset. A [`PasswordField`](crate::PasswordField)
41/// hides its text when either changes.
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
43pub(crate) struct FormSignals {
44    pub(crate) successes: u64,
45    pub(crate) resets: u64,
46}
47
48/// The counters of the enclosing [`Form`], read reactively, or `None` outside a form.
49pub(crate) fn use_form_signals() -> Option<FormSignals> {
50    try_use_context::<Signal<FormSignals>>().map(|signals| *signals.read())
51}
52
53/// Props for [`Form`].
54#[derive(Props, Clone, PartialEq)]
55pub struct FormProps {
56    /// Submission status, exposed as `data-status`. `Submitting` also sets `aria-busy="true"`.
57    #[props(default)]
58    pub status: FormStatus,
59    /// Adds `data-ui-form`, which opts the form into Lumen's web runtime enhancements.
60    #[props(default)]
61    pub enhance: bool,
62    /// Overrides the `aria-busy` value that `status` implies.
63    pub aria_busy: Option<bool>,
64    /// Fires when the form is submitted. Call `prevent_default` to handle it in the app.
65    pub onsubmit: Option<EventHandler<FormEvent>>,
66    /// Fires when the form is reset.
67    pub onreset: Option<EventHandler<FormEvent>>,
68    /// Fires on every edit inside the form.
69    pub oninput: Option<EventHandler<FormEvent>>,
70    /// Fires when a control inside the form commits a change.
71    pub onchange: Option<EventHandler<FormEvent>>,
72    /// Extra classes appended after the Lumen class.
73    #[props(into)]
74    pub class: Option<String>,
75    /// Any other `<form>` or global attribute, such as `action`, `method`, or `novalidate`.
76    #[props(extends = GlobalAttributes, extends = form)]
77    pub attributes: Vec<Attribute>,
78    /// Fields and actions.
79    pub children: Element,
80}
81
82/// A form with Lumen's vertical rhythm and a `data-status` hook for submission states.
83#[component]
84pub fn Form(props: FormProps) -> Element {
85    let mut signals = use_context_provider(|| Signal::new(FormSignals::default()));
86    let mut last_status = use_hook(|| CopyValue::new(props.status));
87
88    // Count transitions into `Success` (not a form that mounts as successful), like lumen-react's
89    // observer on `data-status`.
90    use_effect(use_reactive((&props.status,), move |(status,)| {
91        if *last_status.peek() == status {
92            return;
93        }
94
95        last_status.set(status);
96
97        if status == FormStatus::Success {
98            signals.write().successes += 1;
99        }
100    }));
101
102    let class = compose([Some("ui-form"), props.class.as_deref()]);
103    let aria_busy = props
104        .aria_busy
105        .or((props.status == FormStatus::Submitting).then_some(true))
106        .map(|busy| if busy { "true" } else { "false" });
107    let (onsubmit, onreset, oninput, onchange) =
108        (props.onsubmit, props.onreset, props.oninput, props.onchange);
109
110    rsx! {
111        form {
112            aria_busy,
113            class,
114            "data-status": props.status.as_str(),
115            "data-ui-form": props.enhance.then_some("true"),
116            onsubmit: move |event| {
117                if let Some(handler) = onsubmit {
118                    handler.call(event);
119                }
120            },
121            onreset: move |event| {
122                signals.write().resets += 1;
123
124                if let Some(handler) = onreset {
125                    handler.call(event);
126                }
127            },
128            oninput: move |event| {
129                if let Some(handler) = oninput {
130                    handler.call(event);
131                }
132            },
133            onchange: move |event| {
134                if let Some(handler) = onchange {
135                    handler.call(event);
136                }
137            },
138            ..props.attributes,
139            {props.children}
140        }
141    }
142}