lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `DialogForm`: the form of a [`Dialog`](super::Dialog) or [`AlertDialog`](super::AlertDialog)
//! that runs a request, locks dismissal while it is pending, and shows the errors it returns.
//!
//! lumen-react's `DialogForm` validates the native controls and calls `submit` with the
//! `FormData`. lumen-dioxus leaves native validation to the browser, passes the submitted values to
//! an `async` request, and keeps the same pending lock, error focus, and close-on-success flow on
//! every renderer.

use std::cell::Cell;
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::time::Duration;

use dioxus::prelude::*;

use super::dialog::DialogHandle;
use crate::FormErrors;
use crate::class::compose;
use crate::time::sleep;

/// The message a failed request shows by default, like lumen-core's
/// `lumenDialogFormFailureMessage`.
const DEFAULT_FAILURE_MESSAGE: &str = "Something went wrong. Try again.";

/// Web, desktop, and mobile: focuses the first control among the ids that exists inside a dialog
/// form and is enabled, like lumen-core's `resolveLumenFormErrorFocusTarget`. The ids arrive
/// through `dioxus.recv`, so they are never interpolated into the script.
const FOCUS_ERROR_CONTROL: &str = r"
const ids = await dioxus.recv();
if (!Array.isArray(ids)) return false;
for (const id of ids) {
  if (typeof id !== 'string') continue;
  const control = document.getElementById(id);
  if (!(control instanceof HTMLElement) || control.matches(':disabled')) continue;
  const owner = control.closest('[data-ui-dialog-form]') ?? control.form;
  if (!(owner instanceof HTMLElement) || !owner.matches('[data-ui-dialog-form]')) continue;
  control.focus();
  if (document.activeElement === control) return true;
}
return false;
";

/// The values a [`DialogForm`] submitted, like the `FormData` lumen-react passes to `submit`.
///
/// They come from the form's named controls when it submits. [`DialogFormState::submit`] runs a
/// submission without a submit event, as Dioxus Native needs, and passes no values: read
/// controlled values from your own signals there.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DialogFormValues(Vec<(String, FormValue)>);

impl DialogFormValues {
    /// Every submitted entry, in form order, files included.
    pub fn entries(&self) -> &[(String, FormValue)] {
        &self.0
    }

    /// The first text value submitted under `name`.
    pub fn get(&self, name: &str) -> Option<&str> {
        self.0.iter().find_map(|(key, value)| match value {
            FormValue::Text(text) if key == name => Some(text.as_str()),
            _ => None,
        })
    }
}

impl From<Vec<(String, FormValue)>> for DialogFormValues {
    fn from(entries: Vec<(String, FormValue)>) -> Self {
        Self(entries)
    }
}

/// A failed [`DialogForm`] request, like a rejected `submit` promise in lumen-react. The dialog
/// stays open, keeps every value, and shows its `failure_message`.
///
/// Any [`std::error::Error`] converts into it, so `?` works inside a request.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DialogFormFailure;

impl<E: std::error::Error> From<E> for DialogFormFailure {
    fn from(_: E) -> Self {
        Self
    }
}

/// What a [`DialogForm`] request resolves to: field and form errors keep the dialog open and show
/// them, no errors close it, and a [`DialogFormFailure`] shows the failure message.
pub type DialogFormResult = Result<FormErrors, DialogFormFailure>;

/// The request a [`DialogForm`]'s `submit` callback starts. Return `Box::pin(async move { ... })`
/// from a closure annotated `-> DialogFormFuture`.
pub type DialogFormFuture = Pin<Box<dyn Future<Output = DialogFormResult>>>;

/// What a [`DialogForm`] hands its `render` function, like the state lumen-react passes to a
/// function child.
#[derive(Clone, Debug, PartialEq)]
pub struct DialogFormState {
    /// The errors the last request returned, or the failure message. Pass them to an
    /// [`ErrorSummary`](crate::ErrorSummary).
    pub errors: FormErrors,
    /// True while the request runs; the dialog can't be dismissed meanwhile. Pass it to the
    /// submit [`Button`](crate::Button)'s `loading`.
    pub pending: bool,
    /// Submits the form without a submit event and without values. Dioxus Native reports no
    /// submit events, so call it from the submit button's `onclick` after `prevent_default()`.
    pub submit: Callback<()>,
}

/// Shared with the parts inside a [`DialogForm`]: [`DialogClose`](super::DialogClose) disables
/// itself while the request is pending, and an [`ErrorSummary`](crate::ErrorSummary) registers
/// itself so the form can focus it.
#[derive(Clone, Copy)]
pub(crate) struct DialogFormContext {
    pending: Signal<bool>,
    summary: CopyValue<Option<Rc<MountedData>>>,
}

impl DialogFormContext {
    /// Whether the request is pending. Reading it subscribes the component.
    pub(crate) fn is_pending(self) -> bool {
        *self.pending.read()
    }

    /// Remembers the mounted `ErrorSummary` that error focus falls back to.
    pub(crate) fn set_summary(self, summary: Rc<MountedData>) {
        let mut stored = self.summary;
        stored.set(Some(summary));
    }
}

/// Props for [`DialogForm`].
#[derive(Props, Clone, PartialEq)]
pub struct DialogFormProps {
    /// Receives the submitted values and starts the request. It resolves to field or form errors
    /// to keep the dialog open and show them, to no errors to close the dialog, or to a failure.
    /// Without it, submitting closes the dialog.
    pub submit: Option<Callback<DialogFormValues, DialogFormFuture>>,
    /// Called after a request resolves without errors, once the dialog starts closing.
    pub on_success: Option<EventHandler<()>>,
    /// Shown as a form error when the request fails; entered values stay. Defaults to
    /// `Something went wrong. Try again.`
    #[props(default = DEFAULT_FAILURE_MESSAGE.to_string(), into)]
    pub failure_message: String,
    /// Renders the content with the form's errors, pending state, and submit handle, like
    /// lumen-react's function child. It wins over `children`.
    pub render: Option<Callback<DialogFormState, Element>>,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<form>` or global attribute, such as `novalidate` to validate in Rust only.
    #[props(extends = GlobalAttributes, extends = form)]
    pub attributes: Vec<Attribute>,
    /// [`DialogHeader`](super::DialogHeader), [`DialogBody`](super::DialogBody), and
    /// [`DialogFooter`](super::DialogFooter), when `render` is not used.
    pub children: Element,
}

/// The form-level error a failed request shows; a blank message falls back to the default.
fn failure_errors(message: &str) -> FormErrors {
    let message = message.trim();
    let message = if message.is_empty() {
        DEFAULT_FAILURE_MESSAGE
    } else {
        message
    };

    FormErrors {
        fields: Vec::new(),
        form: vec![message.to_string()],
    }
}

/// The `data-status` value: `submitting`, `error`, or `idle`.
fn form_status(pending: bool, errors: &FormErrors) -> &'static str {
    if pending {
        "submitting"
    } else if errors.is_empty() {
        "idle"
    } else {
        "error"
    }
}

/// Moves focus to the first error's control, else to the registered `ErrorSummary`.
async fn focus_first_error(control_ids: Vec<String>, summary: Option<Rc<MountedData>>) {
    if !control_ids.is_empty() {
        let eval = document::eval(FOCUS_ERROR_CONTROL);

        if eval.send(control_ids).is_ok() && eval.join::<bool>().await.unwrap_or(false) {
            return;
        }
    }

    if let Some(summary) = summary {
        let _ = summary.set_focus(true).await;
    }
}

/// The form of a [`Dialog`](super::Dialog) or [`AlertDialog`](super::AlertDialog). Place
/// [`DialogHeader`](super::DialogHeader), [`DialogBody`](super::DialogBody), and
/// [`DialogFooter`](super::DialogFooter) inside it.
///
/// Submitting runs `submit`. While the request is pending, the dialog refuses Escape, outside
/// clicks, and [`DialogClose`](super::DialogClose), the form sets `aria-busy="true"`, and
/// `DialogClose` is disabled. Returned errors and failures keep the dialog open with every
/// value, and focus moves to the first error's control or the
/// [`ErrorSummary`](crate::ErrorSummary). Success closes the dialog and calls `on_success`;
/// closing the dialog clears the errors.
#[component]
pub fn DialogForm(props: DialogFormProps) -> Element {
    let handle = try_use_context::<DialogHandle>();
    let mut errors = use_signal(FormErrors::default);
    let mut pending = use_signal(|| false);
    let context = use_context_provider(|| DialogFormContext {
        pending,
        summary: CopyValue::new(None),
    });
    // Whether this form holds the dialog's dismissal lock, so unmounting mid-request releases it.
    let lock = use_hook(|| Rc::new(Cell::new(false)));

    use_drop({
        let lock = lock.clone();

        move || {
            if lock.get()
                && let Some(handle) = handle
            {
                handle.release_lock();
            }
        }
    });

    // Escape, DialogClose, and success all close the dialog, so the next opening starts clean.
    let open = handle.map(DialogHandle::is_open);
    use_effect(use_reactive((&open,), move |(open,)| {
        if open == Some(false) && !*pending.peek() && !errors.peek().is_empty() {
            errors.set(FormErrors::default());
        }
    }));

    let failure_message = props.failure_message.clone();
    let (submit, on_success) = (props.submit, props.on_success);
    let summary = context.summary;
    let run = use_callback(move |values: DialogFormValues| {
        if *pending.peek() {
            return;
        }

        if !errors.peek().is_empty() {
            errors.set(FormErrors::default());
        }

        // Without a request, submitting closes the dialog, like a native `method="dialog"` form.
        let Some(submit) = submit else {
            if let Some(handle) = handle {
                handle.set_open(false);
            }

            return;
        };

        pending.set(true);
        lock.set(true);

        if let Some(handle) = handle {
            handle.set_locked(true);
        }

        let request = submit.call(values);
        let failure = failure_errors(&failure_message);
        let lock = lock.clone();

        spawn(async move {
            let next = match request.await {
                Ok(next) => next.normalized(),
                Err(DialogFormFailure) => failure,
            };

            lock.set(false);

            if let Some(handle) = handle {
                handle.set_locked(false);
            }

            pending.set(false);

            if next.is_empty() {
                if let Some(handle) = handle {
                    handle.set_open(false);
                }

                if let Some(on_success) = on_success {
                    on_success.call(());
                }

                return;
            }

            let control_ids: Vec<String> = next
                .fields
                .iter()
                .filter_map(|error| error.control_id.clone())
                .collect();

            errors.set(next);
            // Let the summary and the re-enabled actions render before moving focus.
            sleep(Duration::ZERO).await;
            let target = Option::clone(&*summary.peek());
            focus_first_error(control_ids, target).await;
        });
    });
    let submit_now = use_callback(move |()| run.call(DialogFormValues::default()));

    let is_pending = pending();
    let current = errors();
    let status = form_status(is_pending, &current);
    let class = compose([Some("ui-form ui-dialog-form"), props.class.as_deref()]);
    let has_dialog = handle.is_some();
    let content = match props.render {
        Some(render) => render.call(DialogFormState {
            errors: current,
            pending: is_pending,
            submit: submit_now,
        }),
        None => props.children,
    };

    rsx! {
        form {
            aria_busy: is_pending.then_some("true"),
            class,
            "data-slot": "dialog-form",
            "data-status": status,
            "data-ui-dialog-form": "true",
            "data-ui-owner": "dioxus",
            method: "dialog",
            onsubmit: move |event: FormEvent| {
                // Outside a Lumen dialog and without a request, the browser submits natively.
                if submit.is_none() && !has_dialog {
                    return;
                }

                event.prevent_default();
                run.call(DialogFormValues(event.values()));
            },
            ..props.attributes,
            {content}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{DialogFormValues, FormErrors, failure_errors, form_status};
    use dioxus::prelude::FormValue;

    #[test]
    fn values_read_the_first_text_entry() {
        let values = DialogFormValues::from(vec![
            ("avatar".to_string(), FormValue::File(None)),
            ("name".to_string(), FormValue::Text("Ada".to_string())),
            ("name".to_string(), FormValue::Text("Grace".to_string())),
        ]);

        assert_eq!(values.get("name"), Some("Ada"));
        assert_eq!(values.get("avatar"), None);
        assert_eq!(values.get("missing"), None);
        assert_eq!(values.entries().len(), 3);
        assert_eq!(DialogFormValues::default().get("name"), None);
    }

    #[test]
    fn blank_failure_messages_fall_back_to_the_default() {
        assert_eq!(
            failure_errors("  Not saved.  ").form,
            vec!["Not saved.".to_string()]
        );
        assert_eq!(
            failure_errors(" \n ").form,
            vec!["Something went wrong. Try again.".to_string()]
        );
        assert_eq!(failure_errors("x").fields, Vec::new());
    }

    #[test]
    fn status_prefers_submitting_then_error() {
        let errors = FormErrors::from(vec![("form", "Try again.")]);

        assert_eq!(form_status(true, &errors), "submitting");
        assert_eq!(form_status(false, &errors), "error");
        assert_eq!(form_status(false, &FormErrors::default()), "idle");
    }
}