Skip to main content

gpui_material_extras/specialized_inputs/
otp_input.rs

1use std::rc::Rc;
2
3use gpui::{
4    App, AppContext, Context, ElementId, Empty, Entity, EventEmitter, FocusHandle, Focusable, Hsla,
5    InteractiveElement, IntoElement, KeyDownEvent, MouseButton, ParentElement, Pixels, Render,
6    RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled, Subscription, Window, div,
7    prelude::FluentBuilder, px,
8};
9use gpui_base::{
10    OtpEvent as BaseOtpEvent, OtpInput as BaseOtpInput, OtpState as BaseOtpState, TestSupportExt,
11};
12use gpui_material_components::Text;
13use gpui_material_foundation::{color, current_material_theme};
14use gpui_material_theme::{ColorRole, CornerRole, Density, Direction, TypeRole};
15
16/// Events emitted by [`OtpInputState`].
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub enum OtpInputEvent {
19    /// The verification code changed.
20    Change(SharedString),
21    /// All verification code slots are filled.
22    Complete(SharedString),
23    /// The OTP input gained keyboard focus.
24    Focus,
25    /// The OTP input lost keyboard focus.
26    Blur,
27}
28
29/// Visual container treatment for [`OtpInput`] slots.
30#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
31pub enum OtpInputVariant {
32    /// Transparent/surface slots framed by an outline stroke (default).
33    #[default]
34    Outlined,
35    /// Filled `SurfaceContainerHighest` slots with an active bottom/perimeter accent.
36    Filled,
37}
38
39/// Per-instance color overrides for [`OtpInput`]. Omitted fields resolve from the window theme.
40#[derive(Clone, Copy, Debug, Default)]
41pub struct OtpInputColors {
42    /// Resting slot container color.
43    pub container: Option<Hsla>,
44    /// Container color for slots that contain a digit.
45    pub filled_container: Option<Hsla>,
46    /// Resting slot border color.
47    pub border: Option<Hsla>,
48    /// Border / focus ring color for the active slot while focused.
49    pub active_border: Option<Hsla>,
50    /// Border and message color when invalid and enabled.
51    pub error_border: Option<Hsla>,
52    /// Digit or mask-dot foreground color.
53    pub text: Option<Hsla>,
54    /// Caret bar color in an active empty slot.
55    pub caret: Option<Hsla>,
56    /// Slot container color when disabled.
57    pub disabled_container: Option<Hsla>,
58    /// Slot border color when disabled.
59    pub disabled_border: Option<Hsla>,
60    /// Digit foreground color when disabled.
61    pub disabled_text: Option<Hsla>,
62}
63
64/// Retained state for a Material 3 segmented [`OtpInput`].
65///
66/// Wraps the underlying base OTP focus/blinking state while adding slot-cursor
67/// navigation (`Left`, `Right`, `Home`, `End`), in-place slot replacement, `Delete`,
68/// and clipboard paste (`Ctrl/Cmd+V`).
69pub struct OtpInputState {
70    base: Entity<BaseOtpState>,
71    length: usize,
72    active_slot: usize,
73    _subscriptions: Vec<Subscription>,
74}
75
76impl OtpInputState {
77    /// Creates a new OTP state with `length` digit slots (minimum `1`).
78    pub fn new(length: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
79        let length = length.max(1);
80        let base = cx.new(|cx| BaseOtpState::new(length, window, cx));
81        let subscriptions = vec![
82            cx.observe(&base, |_, _, cx| cx.notify()),
83            cx.subscribe_in(
84                &base,
85                window,
86                |this, base, event: &BaseOtpEvent, _, cx| match event {
87                    BaseOtpEvent::Change => {
88                        let value = base.read(cx).value().clone();
89                        this.active_slot = value.chars().count().min(this.length - 1);
90                        cx.emit(OtpInputEvent::Change(value));
91                        cx.notify();
92                    }
93                    BaseOtpEvent::Complete => {
94                        let value = base.read(cx).value().clone();
95                        this.active_slot = this.length - 1;
96                        cx.emit(OtpInputEvent::Complete(value));
97                        cx.notify();
98                    }
99                    BaseOtpEvent::Focus => {
100                        let count = base.read(cx).value().chars().count();
101                        this.active_slot = count.min(this.length - 1);
102                        cx.emit(OtpInputEvent::Focus);
103                        cx.notify();
104                    }
105                    BaseOtpEvent::Blur => {
106                        cx.emit(OtpInputEvent::Blur);
107                        cx.notify();
108                    }
109                },
110            ),
111        ];
112        Self {
113            base,
114            length,
115            active_slot: 0,
116            _subscriptions: subscriptions,
117        }
118    }
119
120    /// Sets an initial digit value during construction (non-digits are stripped and truncated to `length`).
121    pub fn default_value(
122        mut self,
123        value: impl Into<SharedString>,
124        window: &mut Window,
125        cx: &mut Context<Self>,
126    ) -> Self {
127        let sanitized = sanitize_digits(value.into().as_str(), self.length);
128        self.active_slot = sanitized.chars().count().min(self.length - 1);
129        self.base
130            .update(cx, |base, cx| base.set_value(sanitized, window, cx));
131        self
132    }
133
134    /// Enables or disables masked bullet display during construction.
135    pub fn masked(self, masked: bool, window: &mut Window, cx: &mut Context<Self>) -> Self {
136        self.base
137            .update(cx, |base, cx| base.set_masked(masked, window, cx));
138        self
139    }
140
141    /// Returns the current entered digits.
142    pub fn value(&self, cx: &App) -> SharedString {
143        self.base.read(cx).value().clone()
144    }
145
146    /// Returns the total number of code slots.
147    pub fn length(&self) -> usize {
148        self.length
149    }
150
151    /// Returns whether no digits have been entered.
152    pub fn is_empty(&self, cx: &App) -> bool {
153        self.base.read(cx).is_empty()
154    }
155
156    /// Returns whether all slots contain a digit.
157    pub fn is_complete(&self, cx: &App) -> bool {
158        self.base.read(cx).value().chars().count() >= self.length
159    }
160
161    /// Returns whether digits are masked with bullets.
162    pub fn is_masked(&self, cx: &App) -> bool {
163        self.base.read(cx).is_masked()
164    }
165
166    /// Returns the currently targeted slot index (`0..length()`).
167    pub fn active_slot(&self) -> usize {
168        self.active_slot
169    }
170
171    /// Sets whether digits are masked with bullets.
172    pub fn set_masked(&mut self, masked: bool, window: &mut Window, cx: &mut Context<Self>) {
173        self.base
174            .update(cx, |base, cx| base.set_masked(masked, window, cx));
175        cx.notify();
176    }
177
178    /// Replaces the entered digits programmatically without emitting [`OtpInputEvent::Change`].
179    pub fn set_value(
180        &mut self,
181        value: impl Into<SharedString>,
182        window: &mut Window,
183        cx: &mut Context<Self>,
184    ) {
185        let sanitized = sanitize_digits(value.into().as_str(), self.length);
186        self.active_slot = sanitized.chars().count().min(self.length - 1);
187        self.base
188            .update(cx, |base, cx| base.set_value(sanitized, window, cx));
189        cx.notify();
190    }
191
192    /// Clears all entered digits without emitting [`OtpInputEvent::Change`].
193    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
194        self.set_value("", window, cx);
195    }
196
197    /// Moves the active slot index, clamped to the reachable slot range.
198    pub fn set_active_slot(&mut self, index: usize, cx: &mut Context<Self>) {
199        let filled = self.base.read(cx).value().chars().count();
200        let max_slot = filled.min(self.length - 1);
201        self.active_slot = index.min(max_slot);
202        cx.notify();
203    }
204
205    /// Pastes digits extracted from `text` starting at the active slot (or replacing
206    /// the whole code when `text` contains at least `length()` digits).
207    ///
208    /// Returns `true` if the value changed.
209    pub fn paste(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) -> bool {
210        let current = self.base.read(cx).value().clone();
211        let Some((next, next_slot)) =
212            apply_paste(current.as_str(), self.active_slot, text, self.length)
213        else {
214            return false;
215        };
216        if next == current.as_str() {
217            return false;
218        }
219        let shared: SharedString = next.into();
220        self.active_slot = next_slot;
221        self.base
222            .update(cx, |base, cx| base.set_value(shared.clone(), window, cx));
223        cx.emit(OtpInputEvent::Change(shared.clone()));
224        if shared.chars().count() == self.length {
225            cx.emit(OtpInputEvent::Complete(shared));
226        }
227        cx.notify();
228        true
229    }
230
231    /// Focuses the OTP input.
232    pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
233        self.base.update(cx, |base, cx| base.focus(window, cx));
234    }
235
236    fn handle_capture_key_down(
237        &mut self,
238        event: &KeyDownEvent,
239        window: &mut Window,
240        cx: &mut Context<Self>,
241    ) -> Option<(SharedString, bool)> {
242        let key = event.keystroke.key.as_str();
243        let modifiers = event.keystroke.modifiers;
244
245        if (modifiers.control || modifiers.platform) && key.eq_ignore_ascii_case("v") {
246            if let Some(item) = cx.read_from_clipboard()
247                && let Some(text) = item.text()
248            {
249                let changed = self.paste(&text, window, cx);
250                window.prevent_default();
251                cx.stop_propagation();
252                if changed {
253                    let val = self.value(cx);
254                    let complete = val.chars().count() == self.length;
255                    return Some((val, complete));
256                }
257            }
258            return None;
259        }
260
261        if modifiers.control || modifiers.platform || modifiers.alt {
262            return None;
263        }
264
265        let current = self.base.read(cx).value().clone();
266        let filled = current.chars().count();
267        let max_slot = filled.min(self.length - 1);
268
269        match key {
270            "left" => {
271                self.active_slot = self.active_slot.saturating_sub(1);
272                window.prevent_default();
273                cx.stop_propagation();
274                cx.notify();
275                return None;
276            }
277            "right" => {
278                self.active_slot = (self.active_slot + 1).min(max_slot);
279                window.prevent_default();
280                cx.stop_propagation();
281                cx.notify();
282                return None;
283            }
284            "home" => {
285                self.active_slot = 0;
286                window.prevent_default();
287                cx.stop_propagation();
288                cx.notify();
289                return None;
290            }
291            "end" => {
292                self.active_slot = max_slot;
293                window.prevent_default();
294                cx.stop_propagation();
295                cx.notify();
296                return None;
297            }
298            "delete" => {
299                if let Some((next, next_slot)) =
300                    delete_at(current.as_str(), self.active_slot, self.length)
301                {
302                    let shared: SharedString = next.into();
303                    self.active_slot = next_slot;
304                    self.base
305                        .update(cx, |base, cx| base.set_value(shared.clone(), window, cx));
306                    cx.emit(OtpInputEvent::Change(shared.clone()));
307                    window.prevent_default();
308                    cx.stop_propagation();
309                    cx.notify();
310                    return Some((shared, false));
311                }
312                window.prevent_default();
313                cx.stop_propagation();
314                return None;
315            }
316            "backspace" => {
317                if filled == 0 {
318                    window.prevent_default();
319                    cx.stop_propagation();
320                    return None;
321                }
322                let target = if self.active_slot < filled {
323                    self.active_slot
324                } else {
325                    filled - 1
326                };
327                if let Some((next, next_slot)) = delete_at(current.as_str(), target, self.length) {
328                    let shared: SharedString = next.into();
329                    self.active_slot = next_slot;
330                    self.base
331                        .update(cx, |base, cx| base.set_value(shared.clone(), window, cx));
332                    cx.emit(OtpInputEvent::Change(shared.clone()));
333                    window.prevent_default();
334                    cx.stop_propagation();
335                    cx.notify();
336                    return Some((shared, false));
337                }
338                return None;
339            }
340            _ => {}
341        }
342
343        // Handle digit entry synchronously so `active_slot` stays exact even across
344        // rapid multi-key input within a single frame.
345        if let Some(digit) = extract_single_digit(key, event.keystroke.key_char.as_deref()) {
346            if self.active_slot >= self.length {
347                return None;
348            }
349            let (next, next_slot) =
350                replace_at(current.as_str(), self.active_slot, digit, self.length);
351            let shared: SharedString = next.into();
352            let complete = shared.chars().count() == self.length;
353            self.active_slot = next_slot;
354            self.base
355                .update(cx, |base, cx| base.set_value(shared.clone(), window, cx));
356            cx.emit(OtpInputEvent::Change(shared.clone()));
357            if complete {
358                cx.emit(OtpInputEvent::Complete(shared.clone()));
359            }
360            window.prevent_default();
361            cx.stop_propagation();
362            cx.notify();
363            return Some((shared, complete));
364        }
365
366        None
367    }
368}
369
370impl Focusable for OtpInputState {
371    fn focus_handle(&self, cx: &App) -> FocusHandle {
372        self.base.read(cx).focus_handle(cx)
373    }
374}
375
376impl EventEmitter<OtpInputEvent> for OtpInputState {}
377
378impl Render for OtpInputState {
379    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
380        Empty
381    }
382}
383
384type OtpCallback = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
385
386/// Material 3 segmented one-time-password / verification code input.
387///
388/// Numeric slots always remain in left-to-right order per Material 3 and Unicode BiDi
389/// guidance, even inside right-to-left windows, while the label and supporting/error
390/// caption follow the window's logical direction.
391#[derive(IntoElement)]
392pub struct OtpInput {
393    id: ElementId,
394    label: SharedString,
395    state: Entity<OtpInputState>,
396    variant: OtpInputVariant,
397    masked_override: Option<bool>,
398    disabled: bool,
399    invalid: bool,
400    error: Option<SharedString>,
401    supporting: Option<SharedString>,
402    show_label: bool,
403    separator_after: Option<usize>,
404    slot_size: Option<(Pixels, Pixels)>,
405    gap: Pixels,
406    colors: OtpInputColors,
407    on_change: Option<OtpCallback>,
408    on_complete: Option<OtpCallback>,
409}
410
411impl OtpInput {
412    /// Creates an Outlined segmented OTP input bound to `state`.
413    pub fn new(
414        id: impl Into<ElementId>,
415        label: impl Into<SharedString>,
416        state: &Entity<OtpInputState>,
417    ) -> Self {
418        Self {
419            id: id.into(),
420            label: label.into(),
421            state: state.clone(),
422            variant: OtpInputVariant::Outlined,
423            masked_override: None,
424            disabled: false,
425            invalid: false,
426            error: None,
427            supporting: None,
428            show_label: true,
429            separator_after: None,
430            slot_size: None,
431            gap: px(8.),
432            colors: OtpInputColors::default(),
433            on_change: None,
434            on_complete: None,
435        }
436    }
437
438    /// Selects Outlined or Filled slot styling.
439    pub fn variant(mut self, variant: OtpInputVariant) -> Self {
440        self.variant = variant;
441        self
442    }
443
444    /// Overrides whether entered digits render as bullets (`•`).
445    pub fn masked(mut self, masked: bool) -> Self {
446        self.masked_override = Some(masked);
447        self
448    }
449
450    /// Disables keyboard and pointer interaction.
451    pub fn disabled(mut self, disabled: bool) -> Self {
452        self.disabled = disabled;
453        self
454    }
455
456    /// Marks the code invalid and displays an error message below the slots.
457    pub fn error(mut self, message: impl Into<SharedString>) -> Self {
458        self.error = Some(message.into());
459        self.invalid = true;
460        self
461    }
462
463    /// Marks the code invalid without replacing the supporting message.
464    pub fn invalid(mut self, invalid: bool) -> Self {
465        self.invalid = invalid;
466        self
467    }
468
469    /// Displays supporting helper text below the slots.
470    pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
471        self.supporting = Some(text.into());
472        self
473    }
474
475    /// Controls whether the visible label above the slots is shown. The constructor
476    /// label always remains the accessible group name.
477    pub fn show_label(mut self, show: bool) -> Self {
478        self.show_label = show;
479        self
480    }
481
482    /// Inserts a decorative dash separator after the `index`-th slot (1-based count,
483    /// e.g. `separator_after(3)` renders `1 2 3 - 4 5 6` for a 6-digit code).
484    pub fn separator_after(mut self, count: usize) -> Self {
485        self.separator_after = (count > 0).then_some(count);
486        self
487    }
488
489    /// Sets explicit slot width and height in logical pixels.
490    pub fn slot_size(mut self, width: Pixels, height: Pixels) -> Self {
491        if f32::from(width).is_finite()
492            && f32::from(height).is_finite()
493            && width > px(0.)
494            && height > px(0.)
495        {
496            self.slot_size = Some((width, height));
497        }
498        self
499    }
500
501    /// Sets horizontal spacing between slots in logical pixels (defaults to `8 px`).
502    pub fn gap(mut self, gap: Pixels) -> Self {
503        if f32::from(gap).is_finite() && gap >= px(0.) {
504            self.gap = gap;
505        }
506        self
507    }
508
509    /// Supplies per-instance color overrides.
510    pub fn colors(mut self, colors: OtpInputColors) -> Self {
511        self.colors = colors;
512        self
513    }
514
515    /// Invoked when user interaction changes the verification code.
516    pub fn on_change(
517        mut self,
518        handler: impl Fn(SharedString, &mut Window, &mut App) + 'static,
519    ) -> Self {
520        self.on_change = Some(Rc::new(handler));
521        self
522    }
523
524    /// Invoked when user interaction fills the final verification code slot.
525    pub fn on_complete(
526        mut self,
527        handler: impl Fn(SharedString, &mut Window, &mut App) + 'static,
528    ) -> Self {
529        self.on_complete = Some(Rc::new(handler));
530        self
531    }
532}
533
534impl RenderOnce for OtpInput {
535    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
536        let theme = current_material_theme(window, cx);
537        let rtl = theme.layout.direction == Direction::Rtl;
538        let reduce_motion = cx.reduce_motion();
539        let disabled = self.disabled;
540        let error_active = self.invalid && !disabled;
541
542        let (slot_w, slot_h) = self.slot_size.unwrap_or(match theme.layout.density {
543            Density::Compact => (px(44.), px(48.)),
544            Density::Standard => (px(48.), px(56.)),
545            Density::Comfortable => (px(52.), px(60.)),
546        });
547        let radius = px(CornerRole::Medium.shape().radii(
548            f32::from(slot_w),
549            f32::from(slot_h),
550            Direction::Ltr,
551        )[0]);
552
553        let base_entity = self.state.read(cx).base.clone();
554        let focus_handle = self.state.read(cx).focus_handle(cx);
555        let focused = !disabled && focus_handle.is_focused(window);
556        let length = self.state.read(cx).length();
557        let value = self.state.read(cx).value(cx);
558        let chars: Vec<char> = value.chars().collect();
559        let active_slot = self.state.read(cx).active_slot().min(length - 1);
560        let masked = self
561            .masked_override
562            .unwrap_or_else(|| self.state.read(cx).is_masked(cx));
563        let cursor_visible = focused && (reduce_motion || base_entity.read(cx).cursor_visible(cx));
564
565        let surface_highest = color(theme.colors.color(ColorRole::SurfaceContainerHighest));
566        let surface_container = color(theme.colors.color(ColorRole::SurfaceContainerLow));
567        let outline = color(theme.colors.color(ColorRole::Outline));
568        let primary = color(theme.colors.color(ColorRole::Primary));
569        let error_color = color(theme.colors.color(ColorRole::Error));
570        let on_surface = color(theme.colors.color(ColorRole::OnSurface));
571        let on_surface_variant = color(theme.colors.color(ColorRole::OnSurfaceVariant));
572
573        let resting_bg = self.colors.container.unwrap_or(match self.variant {
574            OtpInputVariant::Outlined => gpui::transparent_black(),
575            OtpInputVariant::Filled => surface_highest,
576        });
577        let filled_bg = self.colors.filled_container.unwrap_or(match self.variant {
578            OtpInputVariant::Outlined => surface_container,
579            OtpInputVariant::Filled => surface_highest,
580        });
581        let resting_border = self.colors.border.unwrap_or(outline);
582        let active_border = self.colors.active_border.unwrap_or(primary);
583        let err_border = self.colors.error_border.unwrap_or(error_color);
584        let digit_color = self.colors.text.unwrap_or(on_surface);
585        let caret_color = self.colors.caret.unwrap_or(primary);
586        let disabled_bg = self
587            .colors
588            .disabled_container
589            .unwrap_or(on_surface.opacity(0.04));
590        let disabled_border = self
591            .colors
592            .disabled_border
593            .unwrap_or(on_surface.opacity(0.12));
594        let disabled_text = self
595            .colors
596            .disabled_text
597            .unwrap_or(on_surface.opacity(0.38));
598
599        let on_change_cb = self.on_change.clone();
600        let on_complete_cb = self.on_complete.clone();
601        let state_for_capture = self.state.clone();
602        let state_for_bubble = self.state.clone();
603        let value_before_key = value.clone();
604
605        let mut slot_elements =
606            Vec::with_capacity(length + usize::from(self.separator_after.is_some()));
607        for index in 0..length {
608            if self.separator_after == Some(index) && index < length {
609                slot_elements.push(
610                    div()
611                        .w(px(12.))
612                        .h(px(2.))
613                        .rounded_full()
614                        .bg(if disabled {
615                            disabled_border
616                        } else {
617                            on_surface_variant
618                        })
619                        .into_any_element(),
620                );
621            }
622
623            let digit = chars.get(index).copied();
624            let is_active = focused && index == active_slot;
625            let bg = if disabled {
626                disabled_bg
627            } else if digit.is_some() {
628                filled_bg
629            } else {
630                resting_bg
631            };
632            let border = if disabled {
633                disabled_border
634            } else if error_active {
635                err_border
636            } else if is_active {
637                active_border
638            } else {
639                resting_border
640            };
641            let border_width = if is_active || error_active {
642                px(2.)
643            } else {
644                px(1.)
645            };
646            let show_caret = is_active && digit.is_none() && cursor_visible;
647            let slot_state = self.state.clone();
648
649            let slot = div()
650                .id((self.id.clone(), format!("slot-{index}")))
651                .test_support()
652                .w(slot_w)
653                .h(slot_h)
654                .rounded(radius)
655                .bg(bg)
656                .border(border_width)
657                .border_color(border)
658                .flex()
659                .items_center()
660                .justify_center()
661                .when(!disabled, |this| {
662                    this.cursor_text()
663                        .on_mouse_down(MouseButton::Left, move |_, window, cx| {
664                            slot_state.update(cx, |state, cx| {
665                                state.set_active_slot(index, cx);
666                                state.focus(window, cx);
667                            });
668                            window.prevent_default();
669                            cx.stop_propagation();
670                        })
671                })
672                .when_some(digit, |this, ch| {
673                    let display = if masked {
674                        SharedString::new_static("•")
675                    } else {
676                        ch.to_string().into()
677                    };
678                    this.child(
679                        Text::new(display)
680                            .role(TypeRole::HeadlineSmall)
681                            .color_override(if disabled { disabled_text } else { digit_color }),
682                    )
683                })
684                .when(show_caret, |this| {
685                    this.child(div().w(px(2.)).h(px(22.)).rounded_full().bg(caret_color))
686                });
687
688            slot_elements.push(slot.into_any_element());
689        }
690
691        let base_otp = BaseOtpInput::new(&base_entity)
692            .disabled(disabled)
693            .flex()
694            .flex_row()
695            .items_center()
696            .gap(self.gap)
697            .children(slot_elements);
698
699        let caption = if error_active {
700            self.error.or(self.supporting)
701        } else {
702            self.supporting
703        };
704
705        let on_change_after = on_change_cb.clone();
706        let on_complete_after = on_complete_cb.clone();
707
708        div()
709            .id(self.id.clone())
710            .test_support()
711            .role(Role::Group)
712            .aria_label(self.label.clone())
713            .flex()
714            .flex_col()
715            .gap_1p5()
716            .when(rtl, Styled::items_end)
717            .when(!disabled, |this| {
718                this.capture_key_down(move |event, window, cx| {
719                    let handled = state_for_capture.update(cx, |state, cx| {
720                        state.handle_capture_key_down(event, window, cx)
721                    });
722                    if let Some((next_value, complete)) = handled {
723                        if let Some(cb) = on_change_cb.as_ref() {
724                            cb(next_value.clone(), window, cx);
725                        }
726                        if complete && let Some(cb) = on_complete_cb.as_ref() {
727                            cb(next_value, window, cx);
728                        }
729                    }
730                })
731                .on_key_down(move |_, window, cx| {
732                    let after = state_for_bubble.read(cx).value(cx);
733                    if after != value_before_key {
734                        if let Some(cb) = on_change_after.as_ref() {
735                            cb(after.clone(), window, cx);
736                        }
737                        if after.chars().count() == length
738                            && let Some(cb) = on_complete_after.as_ref()
739                        {
740                            cb(after, window, cx);
741                        }
742                    }
743                })
744            })
745            .when(self.show_label, |this| {
746                this.child(
747                    Text::new(self.label.clone())
748                        .role(TypeRole::LabelLarge)
749                        .color_override(if disabled {
750                            disabled_text
751                        } else if error_active {
752                            err_border
753                        } else {
754                            on_surface_variant
755                        }),
756                )
757            })
758            .child(base_otp)
759            .when_some(caption, |this, text| {
760                this.child(
761                    div()
762                        .id((self.id.clone(), "supporting"))
763                        .test_support()
764                        .role(if error_active {
765                            Role::Alert
766                        } else {
767                            Role::Status
768                        })
769                        .aria_label(text.clone())
770                        .child(Text::new(text).role(TypeRole::BodySmall).color_override(
771                            if disabled {
772                                disabled_text
773                            } else if error_active {
774                                err_border
775                            } else {
776                                on_surface_variant
777                            },
778                        )),
779                )
780            })
781    }
782}
783
784fn to_digit_char(ch: char) -> Option<char> {
785    if ch.is_ascii_digit() {
786        Some(ch)
787    } else {
788        let digit = (ch as u32).checked_sub('0' as u32)?;
789        char::from_digit(digit, 10)
790    }
791}
792
793fn extract_single_digit(key: &str, key_char: Option<&str>) -> Option<char> {
794    let from_key = if key.chars().count() == 1 {
795        key.chars().next().and_then(to_digit_char)
796    } else {
797        None
798    };
799    from_key.or_else(|| {
800        let kc = key_char?;
801        if kc.chars().count() == 1 {
802            kc.chars().next().and_then(to_digit_char)
803        } else {
804            None
805        }
806    })
807}
808
809fn sanitize_digits(input: &str, max_len: usize) -> String {
810    input
811        .chars()
812        .filter_map(to_digit_char)
813        .take(max_len)
814        .collect()
815}
816
817fn replace_at(current: &str, slot: usize, digit: char, length: usize) -> (String, usize) {
818    let mut chars: Vec<char> = current.chars().take(length).collect();
819    if slot < chars.len() {
820        chars[slot] = digit;
821    } else if chars.len() < length {
822        chars.push(digit);
823    }
824    let next_slot = (slot + 1).min(length - 1);
825    (chars.into_iter().collect(), next_slot)
826}
827
828fn delete_at(current: &str, slot: usize, length: usize) -> Option<(String, usize)> {
829    let mut chars: Vec<char> = current.chars().take(length).collect();
830    if slot >= chars.len() {
831        return None;
832    }
833    chars.remove(slot);
834    let next_slot = slot.min(chars.len()).min(length - 1);
835    Some((chars.into_iter().collect(), next_slot))
836}
837
838fn apply_paste(current: &str, slot: usize, pasted: &str, length: usize) -> Option<(String, usize)> {
839    let digits: Vec<char> = pasted.chars().filter_map(to_digit_char).collect();
840    if digits.is_empty() {
841        return None;
842    }
843    if digits.len() >= length {
844        let next: String = digits.into_iter().take(length).collect();
845        return Some((next, length - 1));
846    }
847    let mut chars: Vec<char> = current.chars().take(length).collect();
848    let mut cursor = slot.min(chars.len()).min(length - 1);
849    for digit in digits {
850        if cursor < chars.len() {
851            chars[cursor] = digit;
852        } else if chars.len() < length {
853            chars.push(digit);
854        }
855        if cursor + 1 < length {
856            cursor += 1;
857        }
858    }
859    let next_slot = cursor.min(chars.len()).min(length - 1);
860    Some((chars.into_iter().collect(), next_slot))
861}
862
863#[cfg(test)]
864mod tests {
865    use super::*;
866
867    #[test]
868    fn sanitize_and_paste_handle_ascii_fullwidth_and_noise() {
869        assert_eq!(sanitize_digits("12-34 5678", 6), "123456");
870        assert_eq!(apply_paste("12", 1, "98", 4), Some(("198".to_owned(), 3)));
871        assert_eq!(
872            apply_paste("1234", 2, "654321", 4),
873            Some(("6543".to_owned(), 3))
874        );
875        assert_eq!(apply_paste("12", 0, "abc", 4), None);
876    }
877
878    #[test]
879    fn slot_replace_and_delete_preserve_cursor_bounds() {
880        assert_eq!(replace_at("1234", 1, '9', 4), ("1934".to_owned(), 2));
881        assert_eq!(replace_at("1234", 3, '0', 4), ("1230".to_owned(), 3));
882        assert_eq!(delete_at("1234", 1, 4), Some(("134".to_owned(), 1)));
883        assert_eq!(delete_at("1", 0, 4), Some((String::new(), 0)));
884        assert_eq!(delete_at("12", 2, 4), None);
885    }
886}