Skip to main content

lumen_dioxus/inputs/
number_field.rs

1//! `NumberField`: a native number input with Rust stepping where the renderer has none.
2
3use dioxus::prelude::*;
4
5use super::number_field_decimal::{
6    NumberFieldOptions, NumberFieldStepDirection, number_field_step_draft,
7};
8use super::number_field_host::{has_flag, use_scripting};
9use crate::class::compose;
10
11/// Props for [`NumberField`].
12#[derive(Props, Clone, PartialEq)]
13pub struct NumberFieldProps {
14    /// Controlled value. Leave unset to let the input manage itself.
15    #[props(into)]
16    pub value: Option<String>,
17    /// Initial value when uncontrolled.
18    #[props(into)]
19    pub default_value: Option<String>,
20    /// Inclusive lower bound, a complete ASCII decimal such as `"0"`.
21    #[props(into)]
22    pub min: Option<String>,
23    /// Inclusive upper bound.
24    #[props(into)]
25    pub max: Option<String>,
26    /// Step size for the arrow keys. Defaults to `1`.
27    #[props(into)]
28    pub step: Option<String>,
29    /// The native input type. Defaults to `number`.
30    #[props(default = "number".to_string(), into)]
31    pub r#type: String,
32    /// Called with the input's text after every edit or step.
33    pub on_value_change: Option<EventHandler<String>>,
34    /// Fires on every edit.
35    pub oninput: Option<EventHandler<FormEvent>>,
36    /// Fires when the value is committed.
37    pub onchange: Option<EventHandler<FormEvent>>,
38    /// Extra classes appended after the Lumen classes.
39    #[props(into)]
40    pub class: Option<String>,
41    /// Any other `<input>` or global attribute, such as `id`, `name`, or `aria_label`.
42    #[props(extends = GlobalAttributes, extends = input)]
43    pub attributes: Vec<Attribute>,
44}
45
46/// Whether a character can appear in a browser number input's text.
47fn number_character(character: char) -> bool {
48    character.is_ascii_digit() || matches!(character, '.' | '-' | '+' | 'e' | 'E')
49}
50
51/// A number input: `<input type="number" class="ui-input ui-number-field">`, like lumen-react.
52///
53/// Browsers step the value with `ArrowUp` and `ArrowDown` and filter what can be typed. Dioxus Native
54/// draws `type="number"` as a plain text field, so there the component adds both in Rust:
55/// `ArrowUp` and `ArrowDown` add or subtract `step` exactly (no floating point) and clamp to `min`
56/// and `max`, and keys that cannot appear in a number are ignored.
57#[component]
58pub fn NumberField(props: NumberFieldProps) -> Element {
59    let scripting = use_scripting();
60    let controlled = props.value.clone();
61    // The rendered `value` changes only through props or Rust stepping. User edits stay in the
62    // control, so a partial draft such as `-` is never overwritten.
63    let mut rendered = use_signal(|| props.default_value.clone());
64    let mut current = use_hook(|| CopyValue::new(props.default_value.clone().unwrap_or_default()));
65
66    if let Some(value) = &controlled
67        && *current.peek() != *value
68    {
69        current.set(value.clone());
70    }
71
72    let value = controlled.clone().or_else(|| rendered.read().clone());
73    let class = compose([Some("ui-input ui-number-field"), props.class.as_deref()]);
74    let options = NumberFieldOptions {
75        locale: None,
76        min: props.min.clone(),
77        max: props.max.clone(),
78        step: props.step.clone(),
79    };
80    let blocked =
81        has_flag(&props.attributes, "readonly") || has_flag(&props.attributes, "disabled");
82    let is_controlled = controlled.is_some();
83    let (on_value_change, oninput, onchange) =
84        (props.on_value_change, props.oninput, props.onchange);
85
86    rsx! {
87        input {
88            class,
89            max: props.max.clone(),
90            min: props.min.clone(),
91            step: props.step.clone(),
92            r#type: props.r#type.clone(),
93            value,
94            oninput: move |event| {
95                let text = event.value();
96
97                current.set(text.clone());
98
99                if let Some(handler) = on_value_change {
100                    handler.call(text);
101                }
102
103                if let Some(handler) = oninput {
104                    handler.call(event);
105                }
106            },
107            onchange: move |event| {
108                if let Some(handler) = onchange {
109                    handler.call(event);
110                }
111            },
112            onkeydown: move |event| {
113                // Browsers and desktop webviews provide native number behavior.
114                if scripting != Some(false) || blocked {
115                    return;
116                }
117
118                let modifiers = event.modifiers();
119
120                if modifiers.ctrl() || modifiers.meta() || modifiers.alt() {
121                    return;
122                }
123
124                let direction = match event.key() {
125                    Key::ArrowUp => NumberFieldStepDirection::Up,
126                    Key::ArrowDown => NumberFieldStepDirection::Down,
127                    Key::Character(text) => {
128                        if !text.chars().all(number_character) {
129                            event.prevent_default();
130                        }
131
132                        return;
133                    }
134                    _ => return,
135                };
136                let shown = current.peek().clone();
137                let Ok(Some(next)) = number_field_step_draft(&shown, direction, &options) else {
138                    return;
139                };
140
141                event.prevent_default();
142                current.set(next.clone());
143
144                if !is_controlled {
145                    // Render what the control shows first, so the stepped value always differs
146                    // from the previous render and reaches the control.
147                    rendered.set(Some(shown));
148
149                    let next = next.clone();
150
151                    spawn(async move { rendered.set(Some(next)) });
152                }
153
154                if let Some(handler) = on_value_change {
155                    handler.call(next);
156                }
157            },
158            ..props.attributes,
159        }
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::number_character;
166
167    #[test]
168    fn number_characters_match_browser_number_inputs() {
169        for character in "0123456789.-+eE".chars() {
170            assert!(number_character(character));
171        }
172
173        for character in "a,x \u{663}".chars() {
174            assert!(!number_character(character));
175        }
176    }
177}