Skip to main content

lumen_dioxus/overlays/
dialog_form.rs

1//! `DialogForm`: the form of a [`Dialog`](super::Dialog) or [`AlertDialog`](super::AlertDialog)
2//! that runs a request, locks dismissal while it is pending, and shows the errors it returns.
3//!
4//! lumen-react's `DialogForm` validates the native controls and calls `submit` with the
5//! `FormData`. lumen-dioxus leaves native validation to the browser, passes the submitted values to
6//! an `async` request, and keeps the same pending lock, error focus, and close-on-success flow on
7//! every renderer.
8
9use std::cell::Cell;
10use std::future::Future;
11use std::pin::Pin;
12use std::rc::Rc;
13use std::time::Duration;
14
15use dioxus::prelude::*;
16
17use super::dialog::DialogHandle;
18use crate::FormErrors;
19use crate::class::compose;
20use crate::time::sleep;
21
22/// The message a failed request shows by default, like lumen-core's
23/// `lumenDialogFormFailureMessage`.
24const DEFAULT_FAILURE_MESSAGE: &str = "Something went wrong. Try again.";
25
26/// Web, desktop, and mobile: focuses the first control among the ids that exists inside a dialog
27/// form and is enabled, like lumen-core's `resolveLumenFormErrorFocusTarget`. The ids arrive
28/// through `dioxus.recv`, so they are never interpolated into the script.
29const FOCUS_ERROR_CONTROL: &str = r"
30const ids = await dioxus.recv();
31if (!Array.isArray(ids)) return false;
32for (const id of ids) {
33  if (typeof id !== 'string') continue;
34  const control = document.getElementById(id);
35  if (!(control instanceof HTMLElement) || control.matches(':disabled')) continue;
36  const owner = control.closest('[data-ui-dialog-form]') ?? control.form;
37  if (!(owner instanceof HTMLElement) || !owner.matches('[data-ui-dialog-form]')) continue;
38  control.focus();
39  if (document.activeElement === control) return true;
40}
41return false;
42";
43
44/// The values a [`DialogForm`] submitted, like the `FormData` lumen-react passes to `submit`.
45///
46/// They come from the form's named controls when it submits. [`DialogFormState::submit`] runs a
47/// submission without a submit event, as Dioxus Native needs, and passes no values: read
48/// controlled values from your own signals there.
49#[derive(Clone, Debug, Default, PartialEq)]
50pub struct DialogFormValues(Vec<(String, FormValue)>);
51
52impl DialogFormValues {
53    /// Every submitted entry, in form order, files included.
54    pub fn entries(&self) -> &[(String, FormValue)] {
55        &self.0
56    }
57
58    /// The first text value submitted under `name`.
59    pub fn get(&self, name: &str) -> Option<&str> {
60        self.0.iter().find_map(|(key, value)| match value {
61            FormValue::Text(text) if key == name => Some(text.as_str()),
62            _ => None,
63        })
64    }
65}
66
67impl From<Vec<(String, FormValue)>> for DialogFormValues {
68    fn from(entries: Vec<(String, FormValue)>) -> Self {
69        Self(entries)
70    }
71}
72
73/// A failed [`DialogForm`] request, like a rejected `submit` promise in lumen-react. The dialog
74/// stays open, keeps every value, and shows its `failure_message`.
75///
76/// Any [`std::error::Error`] converts into it, so `?` works inside a request.
77#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
78pub struct DialogFormFailure;
79
80impl<E: std::error::Error> From<E> for DialogFormFailure {
81    fn from(_: E) -> Self {
82        Self
83    }
84}
85
86/// What a [`DialogForm`] request resolves to: field and form errors keep the dialog open and show
87/// them, no errors close it, and a [`DialogFormFailure`] shows the failure message.
88pub type DialogFormResult = Result<FormErrors, DialogFormFailure>;
89
90/// The request a [`DialogForm`]'s `submit` callback starts. Return `Box::pin(async move { ... })`
91/// from a closure annotated `-> DialogFormFuture`.
92pub type DialogFormFuture = Pin<Box<dyn Future<Output = DialogFormResult>>>;
93
94/// What a [`DialogForm`] hands its `render` function, like the state lumen-react passes to a
95/// function child.
96#[derive(Clone, Debug, PartialEq)]
97pub struct DialogFormState {
98    /// The errors the last request returned, or the failure message. Pass them to an
99    /// [`ErrorSummary`](crate::ErrorSummary).
100    pub errors: FormErrors,
101    /// True while the request runs; the dialog can't be dismissed meanwhile. Pass it to the
102    /// submit [`Button`](crate::Button)'s `loading`.
103    pub pending: bool,
104    /// Submits the form without a submit event and without values. Dioxus Native reports no
105    /// submit events, so call it from the submit button's `onclick` after `prevent_default()`.
106    pub submit: Callback<()>,
107}
108
109/// Shared with the parts inside a [`DialogForm`]: [`DialogClose`](super::DialogClose) disables
110/// itself while the request is pending, and an [`ErrorSummary`](crate::ErrorSummary) registers
111/// itself so the form can focus it.
112#[derive(Clone, Copy)]
113pub(crate) struct DialogFormContext {
114    pending: Signal<bool>,
115    summary: CopyValue<Option<Rc<MountedData>>>,
116}
117
118impl DialogFormContext {
119    /// Whether the request is pending. Reading it subscribes the component.
120    pub(crate) fn is_pending(self) -> bool {
121        *self.pending.read()
122    }
123
124    /// Remembers the mounted `ErrorSummary` that error focus falls back to.
125    pub(crate) fn set_summary(self, summary: Rc<MountedData>) {
126        let mut stored = self.summary;
127        stored.set(Some(summary));
128    }
129}
130
131/// Props for [`DialogForm`].
132#[derive(Props, Clone, PartialEq)]
133pub struct DialogFormProps {
134    /// Receives the submitted values and starts the request. It resolves to field or form errors
135    /// to keep the dialog open and show them, to no errors to close the dialog, or to a failure.
136    /// Without it, submitting closes the dialog.
137    pub submit: Option<Callback<DialogFormValues, DialogFormFuture>>,
138    /// Called after a request resolves without errors, once the dialog starts closing.
139    pub on_success: Option<EventHandler<()>>,
140    /// Shown as a form error when the request fails; entered values stay. Defaults to
141    /// `Something went wrong. Try again.`
142    #[props(default = DEFAULT_FAILURE_MESSAGE.to_string(), into)]
143    pub failure_message: String,
144    /// Renders the content with the form's errors, pending state, and submit handle, like
145    /// lumen-react's function child. It wins over `children`.
146    pub render: Option<Callback<DialogFormState, Element>>,
147    /// Extra classes appended after the Lumen classes.
148    #[props(into)]
149    pub class: Option<String>,
150    /// Any other `<form>` or global attribute, such as `novalidate` to validate in Rust only.
151    #[props(extends = GlobalAttributes, extends = form)]
152    pub attributes: Vec<Attribute>,
153    /// [`DialogHeader`](super::DialogHeader), [`DialogBody`](super::DialogBody), and
154    /// [`DialogFooter`](super::DialogFooter), when `render` is not used.
155    pub children: Element,
156}
157
158/// The form-level error a failed request shows; a blank message falls back to the default.
159fn failure_errors(message: &str) -> FormErrors {
160    let message = message.trim();
161    let message = if message.is_empty() {
162        DEFAULT_FAILURE_MESSAGE
163    } else {
164        message
165    };
166
167    FormErrors {
168        fields: Vec::new(),
169        form: vec![message.to_string()],
170    }
171}
172
173/// The `data-status` value: `submitting`, `error`, or `idle`.
174fn form_status(pending: bool, errors: &FormErrors) -> &'static str {
175    if pending {
176        "submitting"
177    } else if errors.is_empty() {
178        "idle"
179    } else {
180        "error"
181    }
182}
183
184/// Moves focus to the first error's control, else to the registered `ErrorSummary`.
185async fn focus_first_error(control_ids: Vec<String>, summary: Option<Rc<MountedData>>) {
186    if !control_ids.is_empty() {
187        let eval = document::eval(FOCUS_ERROR_CONTROL);
188
189        if eval.send(control_ids).is_ok() && eval.join::<bool>().await.unwrap_or(false) {
190            return;
191        }
192    }
193
194    if let Some(summary) = summary {
195        let _ = summary.set_focus(true).await;
196    }
197}
198
199/// The form of a [`Dialog`](super::Dialog) or [`AlertDialog`](super::AlertDialog). Place
200/// [`DialogHeader`](super::DialogHeader), [`DialogBody`](super::DialogBody), and
201/// [`DialogFooter`](super::DialogFooter) inside it.
202///
203/// Submitting runs `submit`. While the request is pending, the dialog refuses Escape, outside
204/// clicks, and [`DialogClose`](super::DialogClose), the form sets `aria-busy="true"`, and
205/// `DialogClose` is disabled. Returned errors and failures keep the dialog open with every
206/// value, and focus moves to the first error's control or the
207/// [`ErrorSummary`](crate::ErrorSummary). Success closes the dialog and calls `on_success`;
208/// closing the dialog clears the errors.
209#[component]
210pub fn DialogForm(props: DialogFormProps) -> Element {
211    let handle = try_use_context::<DialogHandle>();
212    let mut errors = use_signal(FormErrors::default);
213    let mut pending = use_signal(|| false);
214    let context = use_context_provider(|| DialogFormContext {
215        pending,
216        summary: CopyValue::new(None),
217    });
218    // Whether this form holds the dialog's dismissal lock, so unmounting mid-request releases it.
219    let lock = use_hook(|| Rc::new(Cell::new(false)));
220
221    use_drop({
222        let lock = lock.clone();
223
224        move || {
225            if lock.get()
226                && let Some(handle) = handle
227            {
228                handle.release_lock();
229            }
230        }
231    });
232
233    // Escape, DialogClose, and success all close the dialog, so the next opening starts clean.
234    let open = handle.map(DialogHandle::is_open);
235    use_effect(use_reactive((&open,), move |(open,)| {
236        if open == Some(false) && !*pending.peek() && !errors.peek().is_empty() {
237            errors.set(FormErrors::default());
238        }
239    }));
240
241    let failure_message = props.failure_message.clone();
242    let (submit, on_success) = (props.submit, props.on_success);
243    let summary = context.summary;
244    let run = use_callback(move |values: DialogFormValues| {
245        if *pending.peek() {
246            return;
247        }
248
249        if !errors.peek().is_empty() {
250            errors.set(FormErrors::default());
251        }
252
253        // Without a request, submitting closes the dialog, like a native `method="dialog"` form.
254        let Some(submit) = submit else {
255            if let Some(handle) = handle {
256                handle.set_open(false);
257            }
258
259            return;
260        };
261
262        pending.set(true);
263        lock.set(true);
264
265        if let Some(handle) = handle {
266            handle.set_locked(true);
267        }
268
269        let request = submit.call(values);
270        let failure = failure_errors(&failure_message);
271        let lock = lock.clone();
272
273        spawn(async move {
274            let next = match request.await {
275                Ok(next) => next.normalized(),
276                Err(DialogFormFailure) => failure,
277            };
278
279            lock.set(false);
280
281            if let Some(handle) = handle {
282                handle.set_locked(false);
283            }
284
285            pending.set(false);
286
287            if next.is_empty() {
288                if let Some(handle) = handle {
289                    handle.set_open(false);
290                }
291
292                if let Some(on_success) = on_success {
293                    on_success.call(());
294                }
295
296                return;
297            }
298
299            let control_ids: Vec<String> = next
300                .fields
301                .iter()
302                .filter_map(|error| error.control_id.clone())
303                .collect();
304
305            errors.set(next);
306            // Let the summary and the re-enabled actions render before moving focus.
307            sleep(Duration::ZERO).await;
308            let target = Option::clone(&*summary.peek());
309            focus_first_error(control_ids, target).await;
310        });
311    });
312    let submit_now = use_callback(move |()| run.call(DialogFormValues::default()));
313
314    let is_pending = pending();
315    let current = errors();
316    let status = form_status(is_pending, &current);
317    let class = compose([Some("ui-form ui-dialog-form"), props.class.as_deref()]);
318    let has_dialog = handle.is_some();
319    let content = match props.render {
320        Some(render) => render.call(DialogFormState {
321            errors: current,
322            pending: is_pending,
323            submit: submit_now,
324        }),
325        None => props.children,
326    };
327
328    rsx! {
329        form {
330            aria_busy: is_pending.then_some("true"),
331            class,
332            "data-slot": "dialog-form",
333            "data-status": status,
334            "data-ui-dialog-form": "true",
335            "data-ui-owner": "dioxus",
336            method: "dialog",
337            onsubmit: move |event: FormEvent| {
338                // Outside a Lumen dialog and without a request, the browser submits natively.
339                if submit.is_none() && !has_dialog {
340                    return;
341                }
342
343                event.prevent_default();
344                run.call(DialogFormValues(event.values()));
345            },
346            ..props.attributes,
347            {content}
348        }
349    }
350}
351
352#[cfg(test)]
353mod tests {
354    use super::{DialogFormValues, FormErrors, failure_errors, form_status};
355    use dioxus::prelude::FormValue;
356
357    #[test]
358    fn values_read_the_first_text_entry() {
359        let values = DialogFormValues::from(vec![
360            ("avatar".to_string(), FormValue::File(None)),
361            ("name".to_string(), FormValue::Text("Ada".to_string())),
362            ("name".to_string(), FormValue::Text("Grace".to_string())),
363        ]);
364
365        assert_eq!(values.get("name"), Some("Ada"));
366        assert_eq!(values.get("avatar"), None);
367        assert_eq!(values.get("missing"), None);
368        assert_eq!(values.entries().len(), 3);
369        assert_eq!(DialogFormValues::default().get("name"), None);
370    }
371
372    #[test]
373    fn blank_failure_messages_fall_back_to_the_default() {
374        assert_eq!(
375            failure_errors("  Not saved.  ").form,
376            vec!["Not saved.".to_string()]
377        );
378        assert_eq!(
379            failure_errors(" \n ").form,
380            vec!["Something went wrong. Try again.".to_string()]
381        );
382        assert_eq!(failure_errors("x").fields, Vec::new());
383    }
384
385    #[test]
386    fn status_prefers_submitting_then_error() {
387        let errors = FormErrors::from(vec![("form", "Try again.")]);
388
389        assert_eq!(form_status(true, &errors), "submitting");
390        assert_eq!(form_status(false, &errors), "error");
391        assert_eq!(form_status(false, &FormErrors::default()), "idle");
392    }
393}