lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! `InputOTP`: a one-time code field with one real text input and visual segments.

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]";

/// The `inputmode` of an [`InputOTP`], which picks the on-screen keyboard.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum InputOTPInputMode {
    /// No virtual keyboard.
    None,
    /// Standard text keyboard.
    Text,
    /// Digits and a decimal separator.
    Decimal,
    /// Digits only. With this mode, codes keep ASCII digits only.
    #[default]
    Numeric,
    /// A telephone keypad.
    Tel,
    /// A search keyboard.
    Search,
    /// An email keyboard.
    Email,
    /// A URL keyboard.
    Url,
}

impl InputOTPInputMode {
    /// The DOM attribute value.
    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",
        }
    }
}

/// Normalizes a proposed code like lumen-react's `useInputOTP`: numeric codes (numeric input mode
/// or the default `[0-9]*` pattern) keep ASCII digits only, other codes drop white space, and the
/// result is cut to `length` characters.
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()
}

/// Why [`input_otp_normalize_numeric`] rejected its configuration.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum InputOTPLengthError {
    /// The length is outside `1..=12`.
    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 {}

/// Strict numeric code normalization for a single editor, like lumen-core's
/// `normalizeLumenNumericOTP`: decimal digits of any script become ASCII, `-` and white space
/// separators are dropped, and anything else (or more than `length` digits, or input longer than
/// 128 UTF-16 code units) returns `Ok(None)`.
///
/// # Errors
///
/// [`InputOTPLengthError::OutOfRange`] when `length` is not between 1 and 12.
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))
}

/// Paste handling for web and desktop renderers, installed once per document: like lumen-react,
/// a paste replaces the whole code with its sanitized text (so `maxlength` cannot truncate the
/// clipboard first) and dispatches an `input` event that the Rust handler processes.
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);
}
";

/// Converts a UTF-16 caret offset from the DOM into a character index of `value`.
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()
}

/// Props for [`InputOTP`].
#[derive(Props, Clone, PartialEq)]
pub struct InputOTPProps {
    /// Number of code characters and segments. Defaults to 6; 0 also means 6.
    #[props(default = DEFAULT_LENGTH)]
    pub length: usize,
    /// The `maxlength` of the real input. Defaults to `length`.
    pub max_length: Option<usize>,
    /// Controlled code. Leave unset to let the field manage itself.
    #[props(into)]
    pub value: Option<String>,
    /// Initial code when uncontrolled.
    #[props(into)]
    pub default_value: Option<String>,
    /// Called with the sanitized code after every edit or paste.
    pub on_value_change: Option<EventHandler<String>>,
    /// Disables the input and the segments.
    #[props(default)]
    pub disabled: bool,
    /// The virtual keyboard. Defaults to numeric, which also keeps codes to ASCII digits.
    #[props(default)]
    pub input_mode: InputOTPInputMode,
    /// The input's `pattern`. Defaults to `[0-9]*`, which also keeps codes to ASCII digits.
    #[props(default = DEFAULT_PATTERN.to_string(), into)]
    pub pattern: String,
    /// Extra classes for the real `<input>`.
    #[props(into)]
    pub input_class: Option<String>,
    /// Extra classes for the root element, appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<input>` or global attribute for the real input, such as `name`, `aria_label`,
    /// or `aria_invalid: "true"` (which also marks the segments invalid).
    #[props(extends = GlobalAttributes, extends = input)]
    pub attributes: Vec<Attribute>,
}

/// Whether the attributes set `aria-invalid` to `true`, like lumen-react's check.
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,
            }
    })
}

/// A one-time code field, ported from lumen-react's `InputOTP` and `useInputOTP`.
///
/// One real `<input>` holds the code, so autofill (`autocomplete="one-time-code"`), form
/// submission, and screen readers see a single field; the segment buttons only show the
/// characters and move the caret. Typing, Backspace, arrow keys, Home, and End work in the real
/// input, and a paste replaces the whole code with its sanitized text.
///
/// On Dioxus Native, which runs no JavaScript and cannot move focus or the caret from Rust, the
/// field renders Lumen's no-JavaScript fallback instead: the real input stays visible and the
/// segments are hidden. Typing and paste are sanitized the same way.
#[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, &current, 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();

                    // Model the caret like the DOM: insertions move it forward, deletions back.
                    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());
                    }

                    // Rewrite the control when sanitizing changed the text, or when a controlled
                    // value may stay the same while the control shows the edit.
                    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}");
    }
}