use std::rc::Rc;
use dioxus::core::AttributeValue;
use dioxus::document;
use dioxus::prelude::*;
use super::number_field_host::{ValueMirror, caret_script, use_scripting, use_value_mirror};
use super::number_field_locale::{is_js_whitespace, numeric_digit, utf16_len_capped};
use crate::class::compose;
const DEFAULT_LENGTH: usize = 6;
const DEFAULT_PATTERN: &str = "[0-9]*";
const NATIVE_SELECTOR: &str = "[data-ui-input-otp-native]";
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum InputOTPInputMode {
None,
Text,
Decimal,
#[default]
Numeric,
Tel,
Search,
Email,
Url,
}
impl InputOTPInputMode {
pub fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Text => "text",
Self::Decimal => "decimal",
Self::Numeric => "numeric",
Self::Tel => "tel",
Self::Search => "search",
Self::Email => "email",
Self::Url => "url",
}
}
}
pub fn input_otp_sanitize(
value: &str,
length: usize,
input_mode: InputOTPInputMode,
pattern: &str,
) -> String {
let numeric = input_mode == InputOTPInputMode::Numeric || pattern == DEFAULT_PATTERN;
value
.chars()
.filter(|character| {
if numeric {
character.is_ascii_digit()
} else {
!is_js_whitespace(*character)
}
})
.take(length)
.collect()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum InputOTPLengthError {
OutOfRange,
}
impl std::fmt::Display for InputOTPLengthError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("OTP length must be between 1 and 12.")
}
}
impl std::error::Error for InputOTPLengthError {}
pub fn input_otp_normalize_numeric(
proposal: &str,
length: usize,
) -> Result<Option<String>, InputOTPLengthError> {
if !(1..=12).contains(&length) {
return Err(InputOTPLengthError::OutOfRange);
}
if utf16_len_capped(proposal, 128) > 128 {
return Ok(None);
}
let mut result = String::new();
for character in proposal.chars() {
if let Some(digit) = numeric_digit(character) {
result.push(char::from(b'0' + digit));
} else if character != '-' && !is_js_whitespace(character) {
return Ok(None);
}
if result.len() > length {
return Ok(None);
}
}
Ok(Some(result))
}
const PASTE_SCRIPT: &str = r"
if (!window.__lumenDioxusOtpPaste) {
window.__lumenDioxusOtpPaste = true;
document.addEventListener('paste', event => {
const input = event.target;
if (event.defaultPrevented || !(input instanceof HTMLInputElement) || !input.matches('[data-ui-input-otp-native]')) return;
const pasted = event.clipboardData ? event.clipboardData.getData('text') : '';
if (!pasted) return;
event.preventDefault();
const root = input.closest('[data-ui-input-otp]');
const length = Math.max(1, Number(root && root.getAttribute('data-ui-input-otp-length')) || 6);
const numeric = input.inputMode === 'numeric' || input.getAttribute('pattern') === '[0-9]*';
const next = (numeric ? pasted.replace(/\D/g, '') : pasted.replace(/\s/g, '')).slice(0, length);
input.value = next;
input.setSelectionRange(next.length, next.length);
input.dispatchEvent(new Event('input', { bubbles: true }));
}, true);
}
";
fn caret_from_utf16(value: &str, offset: usize) -> usize {
let mut units = 0;
for (index, character) in value.chars().enumerate() {
if units >= offset {
return index;
}
units += character.len_utf16();
}
value.chars().count()
}
#[derive(Props, Clone, PartialEq)]
pub struct InputOTPProps {
#[props(default = DEFAULT_LENGTH)]
pub length: usize,
pub max_length: Option<usize>,
#[props(into)]
pub value: Option<String>,
#[props(into)]
pub default_value: Option<String>,
pub on_value_change: Option<EventHandler<String>>,
#[props(default)]
pub disabled: bool,
#[props(default)]
pub input_mode: InputOTPInputMode,
#[props(default = DEFAULT_PATTERN.to_string(), into)]
pub pattern: String,
#[props(into)]
pub input_class: Option<String>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = input)]
pub attributes: Vec<Attribute>,
}
fn aria_invalid(attributes: &[Attribute]) -> bool {
attributes.iter().any(|attribute| {
attribute.name == "aria-invalid"
&& match &attribute.value {
AttributeValue::Bool(value) => *value,
AttributeValue::Text(value) => value == "true",
_ => false,
}
})
}
#[component]
pub fn InputOTP(props: InputOTPProps) -> Element {
let length = if props.length == 0 {
DEFAULT_LENGTH
} else {
props.length
};
let input_mode = props.input_mode;
let pattern = props.pattern.clone();
let sanitize = {
let pattern = pattern.clone();
move |value: &str| input_otp_sanitize(value, length, input_mode, &pattern)
};
let mut internal = use_signal(|| sanitize(props.default_value.as_deref().unwrap_or_default()));
let controlled = props.value.clone();
let value = sanitize(
&controlled
.clone()
.unwrap_or_else(|| internal.read().clone()),
);
let mut focused = use_signal(|| false);
let mut caret = use_signal(|| value.chars().count());
let mut input_node = use_signal(|| None::<Rc<MountedData>>);
let mirror: ValueMirror = use_value_mirror();
let scripting = use_scripting();
let enhanced = scripting != Some(false);
let invalid = aria_invalid(&props.attributes);
let disabled = props.disabled;
let on_value_change = props.on_value_change;
let is_controlled = controlled.is_some();
let value_length = value.chars().count();
let active_index = (*caret.read()).min(value_length).min(length - 1);
let rendered_value = mirror.attribute(&value);
let mut latest_value = use_hook(|| CopyValue::new(String::new()));
latest_value.set(value.clone());
use_hook(move || {
if scripting != Some(false) {
spawn(async move {
let _ = document::eval(PASTE_SCRIPT).await;
});
}
});
let mut set_selection = move |index: usize| {
let current = latest_value.peek().clone();
let position = index.min(current.chars().count());
caret.set(position);
let node = input_node.peek().clone();
let script =
(scripting == Some(true)).then(|| caret_script(NATIVE_SELECTOR, ¤t, position));
spawn(async move {
if let Some(node) = node {
let _ = node.set_focus(true).await;
}
if let Some(script) = script {
let _ = document::eval(&script).await;
}
});
};
let sync_caret_from_dom = move || {
if scripting != Some(true) {
return;
}
spawn(async move {
let script = format!(
"const el = document.activeElement; return el && el.matches('{NATIVE_SELECTOR}') ? [el.value, el.selectionStart ?? el.value.length] : null;"
);
if let Ok(Some((dom_value, offset))) = document::eval(&script)
.join::<Option<(String, usize)>>()
.await
{
caret.set(caret_from_utf16(&dom_value, offset));
}
});
};
let root_class = compose([Some("ui-input-otp-field"), props.class.as_deref()]);
let input_class = compose([
Some("ui-input-otp ui-input-otp__native"),
props.input_class.as_deref(),
]);
let has_autocomplete = props
.attributes
.iter()
.any(|attribute| attribute.name == "autocomplete");
let max_length = props.max_length.unwrap_or(length);
let chars: Vec<char> = value.chars().collect();
let is_focused = *focused.read();
rsx! {
div {
class: root_class,
"data-disabled": if disabled { "true" } else { "false" },
"data-invalid": if invalid { "true" } else { "false" },
"data-ui-input-otp": "true",
"data-ui-input-otp-length": "{length}",
"data-ui-owner": "dioxus",
input {
autocomplete: (!has_autocomplete).then_some("one-time-code"),
class: input_class,
"data-ui-enhanced": enhanced.then_some("true"),
"data-ui-input-otp-native": "true",
disabled,
inputmode: input_mode.as_str(),
maxlength: "{max_length}",
pattern: pattern.clone(),
r#type: "text",
value: rendered_value,
onmounted: move |event| input_node.set(Some(event.data())),
onfocus: move |_| {
focused.set(true);
sync_caret_from_dom();
},
onblur: move |_| focused.set(false),
onclick: move |_| sync_caret_from_dom(),
onkeyup: move |_| sync_caret_from_dom(),
onkeydown: move |event| {
if !*focused.peek() {
focused.set(true);
}
let current = *caret.peek();
let next = match event.key() {
Key::ArrowLeft => current.saturating_sub(1),
Key::ArrowRight => (current + 1).min(value_length),
Key::Home => 0,
Key::End => value_length,
_ => return,
};
caret.set(next);
},
oninput: move |event| {
let raw = event.value();
let next = sanitize(&raw);
let previous_length = value_length;
let next_length = next.chars().count();
let current = *caret.peek();
let moved = if next_length >= previous_length {
current + (next_length - previous_length)
} else {
current.saturating_sub(previous_length - next_length)
};
if !*focused.peek() {
focused.set(true);
}
caret.set(moved.min(next_length));
if !is_controlled {
internal.set(next.clone());
}
if is_controlled || raw != next {
mirror.record(raw, || {});
}
if let Some(handler) = on_value_change {
handler.call(next);
}
},
..props.attributes,
}
div {
class: "ui-input-otp__segments",
"data-ui-input-otp-segments": "true",
hidden: !enhanced,
for index in 0..length {
button {
key: "{index}",
aria_hidden: "true",
class: "ui-input-otp__segment",
"data-active": if is_focused && index == active_index { "true" } else { "false" },
"data-index": "{index}",
"data-ui-input-otp-segment": "true",
disabled,
tabindex: "-1",
r#type: "button",
onclick: move |event| {
event.prevent_default();
focused.set(true);
set_selection(index);
},
span {
"data-ui-input-otp-char": "true",
{chars.get(index).map_or_else(|| "\u{a0}".to_string(), char::to_string)}
}
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use dioxus::prelude::*;
use super::{InputOTP, caret_from_utf16};
use crate::inputs::number_field_host::set_scripting_for_tests;
#[test]
fn utf16_offsets_map_to_character_indexes() {
assert_eq!(caret_from_utf16("12", 1), 1);
assert_eq!(caret_from_utf16("\u{1f600}1", 2), 1);
assert_eq!(caret_from_utf16("12", 9), 2);
}
#[test]
fn native_renders_the_visible_input_fallback() {
set_scripting_for_tests(Some(false));
let html = dioxus_ssr::render_element(
rsx! { InputOTP { aria_label: "Code", length: 4, default_value: "12" } },
);
set_scripting_for_tests(None);
assert!(!html.contains("data-ui-enhanced"), "{html}");
assert!(
html.contains("data-ui-input-otp-segments=\"true\" hidden"),
"{html}"
);
assert!(html.contains("value=\"12\""), "{html}");
}
}