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