lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `Form`: a form with Lumen's spacing and a submission status.

// cspell:words onreset

use dioxus::prelude::*;

use crate::class::compose;

/// Where a [`Form`] is in its submission, also its `data-status` value.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FormStatus {
    /// Nothing is happening.
    #[default]
    Idle,
    /// The values are being checked.
    Validating,
    /// The values are being sent. The form sets `aria-busy="true"`.
    Submitting,
    /// The submission succeeded. Password fields in the form hide their text again.
    Success,
    /// The submission failed.
    Error,
}

impl FormStatus {
    /// The `data-status` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Idle => "idle",
            Self::Validating => "validating",
            Self::Submitting => "submitting",
            Self::Success => "success",
            Self::Error => "error",
        }
    }
}

/// Events a [`Form`] shares with the controls inside it: how many times the status became
/// `Success` and how many times the form was reset. A [`PasswordField`](crate::PasswordField)
/// hides its text when either changes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct FormSignals {
    pub(crate) successes: u64,
    pub(crate) resets: u64,
}

/// The counters of the enclosing [`Form`], read reactively, or `None` outside a form.
pub(crate) fn use_form_signals() -> Option<FormSignals> {
    try_use_context::<Signal<FormSignals>>().map(|signals| *signals.read())
}

/// Props for [`Form`].
#[derive(Props, Clone, PartialEq)]
pub struct FormProps {
    /// Submission status, exposed as `data-status`. `Submitting` also sets `aria-busy="true"`.
    #[props(default)]
    pub status: FormStatus,
    /// Adds `data-ui-form`, which opts the form into Lumen's web runtime enhancements.
    #[props(default)]
    pub enhance: bool,
    /// Overrides the `aria-busy` value that `status` implies.
    pub aria_busy: Option<bool>,
    /// Fires when the form is submitted. Call `prevent_default` to handle it in the app.
    pub onsubmit: Option<EventHandler<FormEvent>>,
    /// Fires when the form is reset.
    pub onreset: Option<EventHandler<FormEvent>>,
    /// Fires on every edit inside the form.
    pub oninput: Option<EventHandler<FormEvent>>,
    /// Fires when a control inside the form commits a change.
    pub onchange: Option<EventHandler<FormEvent>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<form>` or global attribute, such as `action`, `method`, or `novalidate`.
    #[props(extends = GlobalAttributes, extends = form)]
    pub attributes: Vec<Attribute>,
    /// Fields and actions.
    pub children: Element,
}

/// A form with Lumen's vertical rhythm and a `data-status` hook for submission states.
#[component]
pub fn Form(props: FormProps) -> Element {
    let mut signals = use_context_provider(|| Signal::new(FormSignals::default()));
    let mut last_status = use_hook(|| CopyValue::new(props.status));

    // Count transitions into `Success` (not a form that mounts as successful), like lumen-react's
    // observer on `data-status`.
    use_effect(use_reactive((&props.status,), move |(status,)| {
        if *last_status.peek() == status {
            return;
        }

        last_status.set(status);

        if status == FormStatus::Success {
            signals.write().successes += 1;
        }
    }));

    let class = compose([Some("ui-form"), props.class.as_deref()]);
    let aria_busy = props
        .aria_busy
        .or((props.status == FormStatus::Submitting).then_some(true))
        .map(|busy| if busy { "true" } else { "false" });
    let (onsubmit, onreset, oninput, onchange) =
        (props.onsubmit, props.onreset, props.oninput, props.onchange);

    rsx! {
        form {
            aria_busy,
            class,
            "data-status": props.status.as_str(),
            "data-ui-form": props.enhance.then_some("true"),
            onsubmit: move |event| {
                if let Some(handler) = onsubmit {
                    handler.call(event);
                }
            },
            onreset: move |event| {
                signals.write().resets += 1;

                if let Some(handler) = onreset {
                    handler.call(event);
                }
            },
            oninput: move |event| {
                if let Some(handler) = oninput {
                    handler.call(event);
                }
            },
            onchange: move |event| {
                if let Some(handler) = onchange {
                    handler.call(event);
                }
            },
            ..props.attributes,
            {props.children}
        }
    }
}