lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `AmountField`: a localized money amount input that submits an exact ASCII decimal.

// cspell:words onpaste oncompositionstart oncompositionend

use dioxus::prelude::*;

use super::amount_field_format::{
    AmountEditor, AmountFieldChange, AmountFieldOptions, AmountInputKind, AmountMessages,
    amount_field_value, infer_edit,
};
use super::number_field_host::{
    caret_script, has_flag, run_scripts, use_scripting, use_value_mirror, validity_script,
};
use crate::class::compose;

const INPUT_SELECTOR: &str = "[data-ui-amount-input]";

/// Props for [`AmountField`].
#[derive(Props, Clone, PartialEq)]
pub struct AmountFieldProps {
    /// Controlled ASCII draft, such as `"1234.50"`. Leave unset to let the field manage itself.
    #[props(into)]
    pub value: Option<String>,
    /// Initial ASCII draft when uncontrolled. Defaults to empty.
    #[props(default, into)]
    pub default_value: String,
    /// BCP 47 locale of the displayed separators and digits. Defaults to `en-US`.
    #[props(default = "en-US".to_string(), into)]
    pub locale: String,
    /// Allowed fraction digits, from 0 to 20. Defaults to 2; larger values count as 20.
    #[props(default = 2)]
    pub fraction_digits: u8,
    /// Accepts negative amounts.
    #[props(default)]
    pub allow_negative: bool,
    /// Inclusive lower bound as a complete ASCII decimal string such as `"1000.50"`.
    #[props(into)]
    pub min: Option<String>,
    /// Inclusive upper bound as a complete ASCII decimal string.
    #[props(into)]
    pub max: Option<String>,
    /// Message for an incomplete or invalid amount.
    #[props(into)]
    pub invalid_message: Option<String>,
    /// Underflow message; `{min}` is replaced with the formatted bound.
    #[props(into)]
    pub range_underflow_message: Option<String>,
    /// Overflow message; `{max}` is replaced with the formatted bound.
    #[props(into)]
    pub range_overflow_message: Option<String>,
    /// Called after every accepted edit with the draft and its complete value.
    pub on_value_change: Option<EventHandler<AmountFieldChange>>,
    /// Form field name of the hidden input that submits the ASCII value.
    #[props(into)]
    pub name: Option<String>,
    /// Id of the form both inputs belong to.
    #[props(into)]
    pub form: Option<String>,
    /// Disables the field; a disabled amount is not submitted.
    #[props(default)]
    pub disabled: bool,
    /// Extra classes for the visible input, appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<input>` or global attribute for the visible input, such as `aria_label`, `id`,
    /// `readonly` (which also ignores edits), or `required` (which the hidden input mirrors).
    #[props(extends = GlobalAttributes, extends = input)]
    pub attributes: Vec<Attribute>,
}

/// Which key started the next edit; Dioxus form events carry no `inputType`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum PendingEdit {
    #[default]
    None,
    Backspace,
    Delete,
    Paste,
}

/// A localized amount input, ported from lumen-react's `AmountField`.
///
/// The visible input shows the amount with the locale's grouping, decimal separator, and digits
/// (`1.234,50` in `es-CO`); a hidden input submits the exact ASCII decimal (`1234.50`) under
/// `name`. Edits that do not parse are reverted, deleting a group separator removes the adjacent
/// digit, and the caret follows the typed digit. Values are never converted to floating point,
/// and nothing is rounded.
///
/// Formatting uses a built-in table of common locale separators, digits, and grouping patterns
/// that matches `Intl.NumberFormat`; unknown regions use their language's entry, and unknown or
/// malformed locales use `en-US`.
#[component]
pub fn AmountField(props: AmountFieldProps) -> Element {
    let options = AmountFieldOptions {
        locale: props.locale.clone(),
        fraction_digits: props.fraction_digits.min(20),
        allow_negative: props.allow_negative,
    };
    let editor = AmountEditor {
        options,
        messages: AmountMessages {
            min: props.min.clone(),
            max: props.max.clone(),
            invalid: props.invalid_message.clone(),
            underflow: props.range_underflow_message.clone(),
            overflow: props.range_overflow_message.clone(),
        },
    };
    let internal = use_signal(|| props.default_value.clone());
    let controlled = props.value.clone();
    let draft = controlled
        .clone()
        .unwrap_or_else(|| internal.read().clone());
    let display = editor.display(&draft);
    let mirror = use_value_mirror();
    let scripting = use_scripting();
    let rendered = mirror.attribute(&display);
    let mut composing = use_signal(|| false);
    let mut composed = use_signal(String::new);
    let mut pending = use_signal(PendingEdit::default);
    // Render-time state read by the event handlers, so the handlers stay `Copy`.
    let mut latest = use_hook(|| {
        CopyValue::new(Latest {
            editor: editor.clone(),
            controlled: None,
            shown: String::new(),
            validity: String::new(),
        })
    });

    latest.set(Latest {
        validity: editor.validity(&draft),
        editor,
        controlled: controlled.clone(),
        shown: rendered.clone(),
    });

    let required = has_flag(&props.attributes, "required");
    let blocked = props.disabled || has_flag(&props.attributes, "readonly");
    let on_value_change = props.on_value_change;
    let submitted = amount_field_value(&draft).unwrap_or_default().to_string();
    let input_class = compose([Some("ui-input ui-amount-field"), props.class.as_deref()]);

    let handle_input = move |raw: String| {
        if blocked {
            return;
        }

        let Latest {
            editor,
            controlled,
            shown: previous,
            ..
        } = latest.peek().clone();
        let (_, inserted) = infer_edit(&previous, &raw);
        let mut pending = pending;
        let kind = match pending.replace(PendingEdit::None) {
            PendingEdit::Paste => AmountInputKind::Paste,
            PendingEdit::Backspace => AmountInputKind::DeleteBackward,
            PendingEdit::Delete => AmountInputKind::DeleteForward,
            // Dioxus Native reports no paste events; several characters at once are a paste.
            PendingEdit::None if scripting == Some(false) && inserted.chars().count() > 1 => {
                AmountInputKind::Paste
            }
            PendingEdit::None
                if inserted.is_empty() && raw.chars().count() < previous.chars().count() =>
            {
                AmountInputKind::DeleteBackward
            }
            PendingEdit::None => AmountInputKind::Insert,
        };
        let is_controlled = controlled.is_some();
        let current = controlled.unwrap_or_else(|| internal.peek().clone());
        let edit = editor.edit(&current, &previous, &raw, kind);
        let scripts = (scripting == Some(true)).then(|| {
            vec![
                caret_script(INPUT_SELECTOR, &edit.display, edit.caret),
                validity_script(INPUT_SELECTOR, &edit.validity),
            ]
        });

        mirror.record(raw, move || {
            if let Some(scripts) = scripts {
                run_scripts(scripts);
            }
        });

        if !edit.accepted {
            return;
        }

        if !is_controlled {
            let mut internal = internal;
            internal.set(edit.draft.clone());
        }

        if let Some(handler) = on_value_change {
            handler.call(AmountFieldChange::new(edit.draft));
        }
    };

    rsx! {
        span {
            "allow-negative": props.allow_negative.then_some(""),
            "data-ui-amount-field": "true",
            "default-value": props.default_value.clone(),
            "fraction-digits": "{props.fraction_digits}",
            "invalid-message": props.invalid_message.clone(),
            "locale": props.locale.clone(),
            "max": props.max.clone(),
            "min": props.min.clone(),
            "range-overflow-message": props.range_overflow_message.clone(),
            "range-underflow-message": props.range_underflow_message.clone(),
            "value": draft.clone(),
            input {
                class: input_class,
                "data-ui-amount-input": "true",
                disabled: props.disabled,
                form: props.form.clone(),
                inputmode: "decimal",
                r#type: "text",
                value: rendered,
                onkeydown: move |event| {
                    pending.set(match event.key() {
                        Key::Backspace => PendingEdit::Backspace,
                        Key::Delete => PendingEdit::Delete,
                        _ => PendingEdit::None,
                    });
                },
                onpaste: move |_| pending.set(PendingEdit::Paste),
                oncompositionstart: move |_| composing.set(true),
                oncompositionend: move |_| {
                    composing.set(false);
                    handle_input(composed.peek().clone());
                },
                onfocus: move |_| {
                    if scripting == Some(true) {
                        let message = latest.peek().validity.clone();
                        run_scripts(vec![validity_script(INPUT_SELECTOR, &message)]);
                    }
                },
                oninput: move |event| {
                    let raw = event.value();

                    if *composing.peek() {
                        composed.set(raw);
                        return;
                    }

                    handle_input(raw);
                },
                ..props.attributes,
            }
            input {
                "data-ui-amount-value": "true",
                disabled: props.disabled,
                form: props.form.clone(),
                max: props.max.clone(),
                min: props.min.clone(),
                name: props.name.clone(),
                required,
                r#type: "hidden",
                value: submitted,
            }
        }
    }
}

/// Render-time values the event handlers read.
#[derive(Clone)]
struct Latest {
    editor: AmountEditor,
    controlled: Option<String>,
    /// The text the visible input shows.
    shown: String,
    validity: String,
}