1use std::rc::Rc;
4
5use dioxus::core::AttributeValue;
6use dioxus::document;
7use dioxus::prelude::*;
8
9use super::number_field_host::{ValueMirror, caret_script, use_scripting, use_value_mirror};
10use super::number_field_locale::{is_js_whitespace, numeric_digit, utf16_len_capped};
11use crate::class::compose;
12
13const DEFAULT_LENGTH: usize = 6;
14const DEFAULT_PATTERN: &str = "[0-9]*";
15const NATIVE_SELECTOR: &str = "[data-ui-input-otp-native]";
16
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19#[non_exhaustive]
20pub enum InputOTPInputMode {
21 None,
23 Text,
25 Decimal,
27 #[default]
29 Numeric,
30 Tel,
32 Search,
34 Email,
36 Url,
38}
39
40impl InputOTPInputMode {
41 pub fn as_str(self) -> &'static str {
43 match self {
44 Self::None => "none",
45 Self::Text => "text",
46 Self::Decimal => "decimal",
47 Self::Numeric => "numeric",
48 Self::Tel => "tel",
49 Self::Search => "search",
50 Self::Email => "email",
51 Self::Url => "url",
52 }
53 }
54}
55
56pub fn input_otp_sanitize(
60 value: &str,
61 length: usize,
62 input_mode: InputOTPInputMode,
63 pattern: &str,
64) -> String {
65 let numeric = input_mode == InputOTPInputMode::Numeric || pattern == DEFAULT_PATTERN;
66
67 value
68 .chars()
69 .filter(|character| {
70 if numeric {
71 character.is_ascii_digit()
72 } else {
73 !is_js_whitespace(*character)
74 }
75 })
76 .take(length)
77 .collect()
78}
79
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82#[non_exhaustive]
83pub enum InputOTPLengthError {
84 OutOfRange,
86}
87
88impl std::fmt::Display for InputOTPLengthError {
89 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90 formatter.write_str("OTP length must be between 1 and 12.")
91 }
92}
93
94impl std::error::Error for InputOTPLengthError {}
95
96pub fn input_otp_normalize_numeric(
105 proposal: &str,
106 length: usize,
107) -> Result<Option<String>, InputOTPLengthError> {
108 if !(1..=12).contains(&length) {
109 return Err(InputOTPLengthError::OutOfRange);
110 }
111
112 if utf16_len_capped(proposal, 128) > 128 {
113 return Ok(None);
114 }
115
116 let mut result = String::new();
117
118 for character in proposal.chars() {
119 if let Some(digit) = numeric_digit(character) {
120 result.push(char::from(b'0' + digit));
121 } else if character != '-' && !is_js_whitespace(character) {
122 return Ok(None);
123 }
124
125 if result.len() > length {
126 return Ok(None);
127 }
128 }
129
130 Ok(Some(result))
131}
132
133const PASTE_SCRIPT: &str = r"
137if (!window.__lumenDioxusOtpPaste) {
138 window.__lumenDioxusOtpPaste = true;
139 document.addEventListener('paste', event => {
140 const input = event.target;
141 if (event.defaultPrevented || !(input instanceof HTMLInputElement) || !input.matches('[data-ui-input-otp-native]')) return;
142 const pasted = event.clipboardData ? event.clipboardData.getData('text') : '';
143 if (!pasted) return;
144 event.preventDefault();
145 const root = input.closest('[data-ui-input-otp]');
146 const length = Math.max(1, Number(root && root.getAttribute('data-ui-input-otp-length')) || 6);
147 const numeric = input.inputMode === 'numeric' || input.getAttribute('pattern') === '[0-9]*';
148 const next = (numeric ? pasted.replace(/\D/g, '') : pasted.replace(/\s/g, '')).slice(0, length);
149 input.value = next;
150 input.setSelectionRange(next.length, next.length);
151 input.dispatchEvent(new Event('input', { bubbles: true }));
152 }, true);
153}
154";
155
156fn caret_from_utf16(value: &str, offset: usize) -> usize {
158 let mut units = 0;
159
160 for (index, character) in value.chars().enumerate() {
161 if units >= offset {
162 return index;
163 }
164
165 units += character.len_utf16();
166 }
167
168 value.chars().count()
169}
170
171#[derive(Props, Clone, PartialEq)]
173pub struct InputOTPProps {
174 #[props(default = DEFAULT_LENGTH)]
176 pub length: usize,
177 pub max_length: Option<usize>,
179 #[props(into)]
181 pub value: Option<String>,
182 #[props(into)]
184 pub default_value: Option<String>,
185 pub on_value_change: Option<EventHandler<String>>,
187 #[props(default)]
189 pub disabled: bool,
190 #[props(default)]
192 pub input_mode: InputOTPInputMode,
193 #[props(default = DEFAULT_PATTERN.to_string(), into)]
195 pub pattern: String,
196 #[props(into)]
198 pub input_class: Option<String>,
199 #[props(into)]
201 pub class: Option<String>,
202 #[props(extends = GlobalAttributes, extends = input)]
205 pub attributes: Vec<Attribute>,
206}
207
208fn aria_invalid(attributes: &[Attribute]) -> bool {
210 attributes.iter().any(|attribute| {
211 attribute.name == "aria-invalid"
212 && match &attribute.value {
213 AttributeValue::Bool(value) => *value,
214 AttributeValue::Text(value) => value == "true",
215 _ => false,
216 }
217 })
218}
219
220#[component]
231pub fn InputOTP(props: InputOTPProps) -> Element {
232 let length = if props.length == 0 {
233 DEFAULT_LENGTH
234 } else {
235 props.length
236 };
237 let input_mode = props.input_mode;
238 let pattern = props.pattern.clone();
239 let sanitize = {
240 let pattern = pattern.clone();
241 move |value: &str| input_otp_sanitize(value, length, input_mode, &pattern)
242 };
243 let mut internal = use_signal(|| sanitize(props.default_value.as_deref().unwrap_or_default()));
244 let controlled = props.value.clone();
245 let value = sanitize(
246 &controlled
247 .clone()
248 .unwrap_or_else(|| internal.read().clone()),
249 );
250 let mut focused = use_signal(|| false);
251 let mut caret = use_signal(|| value.chars().count());
252 let mut input_node = use_signal(|| None::<Rc<MountedData>>);
253 let mirror: ValueMirror = use_value_mirror();
254 let scripting = use_scripting();
255 let enhanced = scripting != Some(false);
256 let invalid = aria_invalid(&props.attributes);
257 let disabled = props.disabled;
258 let on_value_change = props.on_value_change;
259 let is_controlled = controlled.is_some();
260 let value_length = value.chars().count();
261 let active_index = (*caret.read()).min(value_length).min(length - 1);
262 let rendered_value = mirror.attribute(&value);
263 let mut latest_value = use_hook(|| CopyValue::new(String::new()));
264
265 latest_value.set(value.clone());
266
267 use_hook(move || {
268 if scripting != Some(false) {
269 spawn(async move {
270 let _ = document::eval(PASTE_SCRIPT).await;
271 });
272 }
273 });
274
275 let mut set_selection = move |index: usize| {
276 let current = latest_value.peek().clone();
277 let position = index.min(current.chars().count());
278
279 caret.set(position);
280
281 let node = input_node.peek().clone();
282 let script =
283 (scripting == Some(true)).then(|| caret_script(NATIVE_SELECTOR, ¤t, position));
284
285 spawn(async move {
286 if let Some(node) = node {
287 let _ = node.set_focus(true).await;
288 }
289
290 if let Some(script) = script {
291 let _ = document::eval(&script).await;
292 }
293 });
294 };
295
296 let sync_caret_from_dom = move || {
297 if scripting != Some(true) {
298 return;
299 }
300
301 spawn(async move {
302 let script = format!(
303 "const el = document.activeElement; return el && el.matches('{NATIVE_SELECTOR}') ? [el.value, el.selectionStart ?? el.value.length] : null;"
304 );
305
306 if let Ok(Some((dom_value, offset))) = document::eval(&script)
307 .join::<Option<(String, usize)>>()
308 .await
309 {
310 caret.set(caret_from_utf16(&dom_value, offset));
311 }
312 });
313 };
314
315 let root_class = compose([Some("ui-input-otp-field"), props.class.as_deref()]);
316 let input_class = compose([
317 Some("ui-input-otp ui-input-otp__native"),
318 props.input_class.as_deref(),
319 ]);
320 let has_autocomplete = props
321 .attributes
322 .iter()
323 .any(|attribute| attribute.name == "autocomplete");
324 let max_length = props.max_length.unwrap_or(length);
325 let chars: Vec<char> = value.chars().collect();
326 let is_focused = *focused.read();
327
328 rsx! {
329 div {
330 class: root_class,
331 "data-disabled": if disabled { "true" } else { "false" },
332 "data-invalid": if invalid { "true" } else { "false" },
333 "data-ui-input-otp": "true",
334 "data-ui-input-otp-length": "{length}",
335 "data-ui-owner": "dioxus",
336 input {
337 autocomplete: (!has_autocomplete).then_some("one-time-code"),
338 class: input_class,
339 "data-ui-enhanced": enhanced.then_some("true"),
340 "data-ui-input-otp-native": "true",
341 disabled,
342 inputmode: input_mode.as_str(),
343 maxlength: "{max_length}",
344 pattern: pattern.clone(),
345 r#type: "text",
346 value: rendered_value,
347 onmounted: move |event| input_node.set(Some(event.data())),
348 onfocus: move |_| {
349 focused.set(true);
350 sync_caret_from_dom();
351 },
352 onblur: move |_| focused.set(false),
353 onclick: move |_| sync_caret_from_dom(),
354 onkeyup: move |_| sync_caret_from_dom(),
355 onkeydown: move |event| {
356 if !*focused.peek() {
357 focused.set(true);
358 }
359
360 let current = *caret.peek();
361 let next = match event.key() {
362 Key::ArrowLeft => current.saturating_sub(1),
363 Key::ArrowRight => (current + 1).min(value_length),
364 Key::Home => 0,
365 Key::End => value_length,
366 _ => return,
367 };
368
369 caret.set(next);
370 },
371 oninput: move |event| {
372 let raw = event.value();
373 let next = sanitize(&raw);
374 let previous_length = value_length;
375 let next_length = next.chars().count();
376 let current = *caret.peek();
377
378 let moved = if next_length >= previous_length {
380 current + (next_length - previous_length)
381 } else {
382 current.saturating_sub(previous_length - next_length)
383 };
384
385 if !*focused.peek() {
386 focused.set(true);
387 }
388
389 caret.set(moved.min(next_length));
390
391 if !is_controlled {
392 internal.set(next.clone());
393 }
394
395 if is_controlled || raw != next {
398 mirror.record(raw, || {});
399 }
400
401 if let Some(handler) = on_value_change {
402 handler.call(next);
403 }
404 },
405 ..props.attributes,
406 }
407 div {
408 class: "ui-input-otp__segments",
409 "data-ui-input-otp-segments": "true",
410 hidden: !enhanced,
411 for index in 0..length {
412 button {
413 key: "{index}",
414 aria_hidden: "true",
415 class: "ui-input-otp__segment",
416 "data-active": if is_focused && index == active_index { "true" } else { "false" },
417 "data-index": "{index}",
418 "data-ui-input-otp-segment": "true",
419 disabled,
420 tabindex: "-1",
421 r#type: "button",
422 onclick: move |event| {
423 event.prevent_default();
424 focused.set(true);
425 set_selection(index);
426 },
427 span {
428 "data-ui-input-otp-char": "true",
429 {chars.get(index).map_or_else(|| "\u{a0}".to_string(), char::to_string)}
430 }
431 }
432 }
433 }
434 }
435 }
436}
437
438#[cfg(test)]
439mod tests {
440 use dioxus::prelude::*;
441
442 use super::{InputOTP, caret_from_utf16};
443 use crate::inputs::number_field_host::set_scripting_for_tests;
444
445 #[test]
446 fn utf16_offsets_map_to_character_indexes() {
447 assert_eq!(caret_from_utf16("12", 1), 1);
448 assert_eq!(caret_from_utf16("\u{1f600}1", 2), 1);
449 assert_eq!(caret_from_utf16("12", 9), 2);
450 }
451
452 #[test]
453 fn native_renders_the_visible_input_fallback() {
454 set_scripting_for_tests(Some(false));
455 let html = dioxus_ssr::render_element(
456 rsx! { InputOTP { aria_label: "Code", length: 4, default_value: "12" } },
457 );
458 set_scripting_for_tests(None);
459
460 assert!(!html.contains("data-ui-enhanced"), "{html}");
461 assert!(
462 html.contains("data-ui-input-otp-segments=\"true\" hidden"),
463 "{html}"
464 );
465 assert!(html.contains("value=\"12\""), "{html}");
466 }
467}