Skip to main content

lumen_dioxus/inputs/
amount_field.rs

1//! `AmountField`: a localized money amount input that submits an exact ASCII decimal.
2
3// cspell:words onpaste oncompositionstart oncompositionend
4
5use dioxus::prelude::*;
6
7use super::amount_field_format::{
8    AmountEditor, AmountFieldChange, AmountFieldOptions, AmountInputKind, AmountMessages,
9    amount_field_value, infer_edit,
10};
11use super::number_field_host::{
12    caret_script, has_flag, run_scripts, use_scripting, use_value_mirror, validity_script,
13};
14use crate::class::compose;
15
16const INPUT_SELECTOR: &str = "[data-ui-amount-input]";
17
18/// Props for [`AmountField`].
19#[derive(Props, Clone, PartialEq)]
20pub struct AmountFieldProps {
21    /// Controlled ASCII draft, such as `"1234.50"`. Leave unset to let the field manage itself.
22    #[props(into)]
23    pub value: Option<String>,
24    /// Initial ASCII draft when uncontrolled. Defaults to empty.
25    #[props(default, into)]
26    pub default_value: String,
27    /// BCP 47 locale of the displayed separators and digits. Defaults to `en-US`.
28    #[props(default = "en-US".to_string(), into)]
29    pub locale: String,
30    /// Allowed fraction digits, from 0 to 20. Defaults to 2; larger values count as 20.
31    #[props(default = 2)]
32    pub fraction_digits: u8,
33    /// Accepts negative amounts.
34    #[props(default)]
35    pub allow_negative: bool,
36    /// Inclusive lower bound as a complete ASCII decimal string such as `"1000.50"`.
37    #[props(into)]
38    pub min: Option<String>,
39    /// Inclusive upper bound as a complete ASCII decimal string.
40    #[props(into)]
41    pub max: Option<String>,
42    /// Message for an incomplete or invalid amount.
43    #[props(into)]
44    pub invalid_message: Option<String>,
45    /// Underflow message; `{min}` is replaced with the formatted bound.
46    #[props(into)]
47    pub range_underflow_message: Option<String>,
48    /// Overflow message; `{max}` is replaced with the formatted bound.
49    #[props(into)]
50    pub range_overflow_message: Option<String>,
51    /// Called after every accepted edit with the draft and its complete value.
52    pub on_value_change: Option<EventHandler<AmountFieldChange>>,
53    /// Form field name of the hidden input that submits the ASCII value.
54    #[props(into)]
55    pub name: Option<String>,
56    /// Id of the form both inputs belong to.
57    #[props(into)]
58    pub form: Option<String>,
59    /// Disables the field; a disabled amount is not submitted.
60    #[props(default)]
61    pub disabled: bool,
62    /// Extra classes for the visible input, appended after the Lumen classes.
63    #[props(into)]
64    pub class: Option<String>,
65    /// Any other `<input>` or global attribute for the visible input, such as `aria_label`, `id`,
66    /// `readonly` (which also ignores edits), or `required` (which the hidden input mirrors).
67    #[props(extends = GlobalAttributes, extends = input)]
68    pub attributes: Vec<Attribute>,
69}
70
71/// Which key started the next edit; Dioxus form events carry no `inputType`.
72#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
73enum PendingEdit {
74    #[default]
75    None,
76    Backspace,
77    Delete,
78    Paste,
79}
80
81/// A localized amount input, ported from lumen-react's `AmountField`.
82///
83/// The visible input shows the amount with the locale's grouping, decimal separator, and digits
84/// (`1.234,50` in `es-CO`); a hidden input submits the exact ASCII decimal (`1234.50`) under
85/// `name`. Edits that do not parse are reverted, deleting a group separator removes the adjacent
86/// digit, and the caret follows the typed digit. Values are never converted to floating point,
87/// and nothing is rounded.
88///
89/// Formatting uses a built-in table of common locale separators, digits, and grouping patterns
90/// that matches `Intl.NumberFormat`; unknown regions use their language's entry, and unknown or
91/// malformed locales use `en-US`.
92#[component]
93pub fn AmountField(props: AmountFieldProps) -> Element {
94    let options = AmountFieldOptions {
95        locale: props.locale.clone(),
96        fraction_digits: props.fraction_digits.min(20),
97        allow_negative: props.allow_negative,
98    };
99    let editor = AmountEditor {
100        options,
101        messages: AmountMessages {
102            min: props.min.clone(),
103            max: props.max.clone(),
104            invalid: props.invalid_message.clone(),
105            underflow: props.range_underflow_message.clone(),
106            overflow: props.range_overflow_message.clone(),
107        },
108    };
109    let internal = use_signal(|| props.default_value.clone());
110    let controlled = props.value.clone();
111    let draft = controlled
112        .clone()
113        .unwrap_or_else(|| internal.read().clone());
114    let display = editor.display(&draft);
115    let mirror = use_value_mirror();
116    let scripting = use_scripting();
117    let rendered = mirror.attribute(&display);
118    let mut composing = use_signal(|| false);
119    let mut composed = use_signal(String::new);
120    let mut pending = use_signal(PendingEdit::default);
121    // Render-time state read by the event handlers, so the handlers stay `Copy`.
122    let mut latest = use_hook(|| {
123        CopyValue::new(Latest {
124            editor: editor.clone(),
125            controlled: None,
126            shown: String::new(),
127            validity: String::new(),
128        })
129    });
130
131    latest.set(Latest {
132        validity: editor.validity(&draft),
133        editor,
134        controlled: controlled.clone(),
135        shown: rendered.clone(),
136    });
137
138    let required = has_flag(&props.attributes, "required");
139    let blocked = props.disabled || has_flag(&props.attributes, "readonly");
140    let on_value_change = props.on_value_change;
141    let submitted = amount_field_value(&draft).unwrap_or_default().to_string();
142    let input_class = compose([Some("ui-input ui-amount-field"), props.class.as_deref()]);
143
144    let handle_input = move |raw: String| {
145        if blocked {
146            return;
147        }
148
149        let Latest {
150            editor,
151            controlled,
152            shown: previous,
153            ..
154        } = latest.peek().clone();
155        let (_, inserted) = infer_edit(&previous, &raw);
156        let mut pending = pending;
157        let kind = match pending.replace(PendingEdit::None) {
158            PendingEdit::Paste => AmountInputKind::Paste,
159            PendingEdit::Backspace => AmountInputKind::DeleteBackward,
160            PendingEdit::Delete => AmountInputKind::DeleteForward,
161            // Dioxus Native reports no paste events; several characters at once are a paste.
162            PendingEdit::None if scripting == Some(false) && inserted.chars().count() > 1 => {
163                AmountInputKind::Paste
164            }
165            PendingEdit::None
166                if inserted.is_empty() && raw.chars().count() < previous.chars().count() =>
167            {
168                AmountInputKind::DeleteBackward
169            }
170            PendingEdit::None => AmountInputKind::Insert,
171        };
172        let is_controlled = controlled.is_some();
173        let current = controlled.unwrap_or_else(|| internal.peek().clone());
174        let edit = editor.edit(&current, &previous, &raw, kind);
175        let scripts = (scripting == Some(true)).then(|| {
176            vec![
177                caret_script(INPUT_SELECTOR, &edit.display, edit.caret),
178                validity_script(INPUT_SELECTOR, &edit.validity),
179            ]
180        });
181
182        mirror.record(raw, move || {
183            if let Some(scripts) = scripts {
184                run_scripts(scripts);
185            }
186        });
187
188        if !edit.accepted {
189            return;
190        }
191
192        if !is_controlled {
193            let mut internal = internal;
194            internal.set(edit.draft.clone());
195        }
196
197        if let Some(handler) = on_value_change {
198            handler.call(AmountFieldChange::new(edit.draft));
199        }
200    };
201
202    rsx! {
203        span {
204            "allow-negative": props.allow_negative.then_some(""),
205            "data-ui-amount-field": "true",
206            "default-value": props.default_value.clone(),
207            "fraction-digits": "{props.fraction_digits}",
208            "invalid-message": props.invalid_message.clone(),
209            "locale": props.locale.clone(),
210            "max": props.max.clone(),
211            "min": props.min.clone(),
212            "range-overflow-message": props.range_overflow_message.clone(),
213            "range-underflow-message": props.range_underflow_message.clone(),
214            "value": draft.clone(),
215            input {
216                class: input_class,
217                "data-ui-amount-input": "true",
218                disabled: props.disabled,
219                form: props.form.clone(),
220                inputmode: "decimal",
221                r#type: "text",
222                value: rendered,
223                onkeydown: move |event| {
224                    pending.set(match event.key() {
225                        Key::Backspace => PendingEdit::Backspace,
226                        Key::Delete => PendingEdit::Delete,
227                        _ => PendingEdit::None,
228                    });
229                },
230                onpaste: move |_| pending.set(PendingEdit::Paste),
231                oncompositionstart: move |_| composing.set(true),
232                oncompositionend: move |_| {
233                    composing.set(false);
234                    handle_input(composed.peek().clone());
235                },
236                onfocus: move |_| {
237                    if scripting == Some(true) {
238                        let message = latest.peek().validity.clone();
239                        run_scripts(vec![validity_script(INPUT_SELECTOR, &message)]);
240                    }
241                },
242                oninput: move |event| {
243                    let raw = event.value();
244
245                    if *composing.peek() {
246                        composed.set(raw);
247                        return;
248                    }
249
250                    handle_input(raw);
251                },
252                ..props.attributes,
253            }
254            input {
255                "data-ui-amount-value": "true",
256                disabled: props.disabled,
257                form: props.form.clone(),
258                max: props.max.clone(),
259                min: props.min.clone(),
260                name: props.name.clone(),
261                required,
262                r#type: "hidden",
263                value: submitted,
264            }
265        }
266    }
267}
268
269/// Render-time values the event handlers read.
270#[derive(Clone)]
271struct Latest {
272    editor: AmountEditor,
273    controlled: Option<String>,
274    /// The text the visible input shows.
275    shown: String,
276    validity: String,
277}