Skip to main content

fc_ui/capabilities/controls/
otp_input.rs

1use crate::capabilities::foundation::theme::use_theme;
2use gpui::{prelude::FluentBuilder as _, *};
3use std::rc::Rc;
4
5actions!(
6    otp_input,
7    [
8        OTPBackspace,
9        OTPDelete,
10        OTPLeft,
11        OTPRight,
12        OTPHome,
13        OTPEnd,
14        OTPPaste,
15        OTPEscape,
16    ]
17);
18
19pub fn init(cx: &mut App) {
20    if !crate::capabilities::foundation::initialization::begin(cx, "otp-input") {
21        return;
22    }
23    cx.bind_keys([
24        KeyBinding::new("backspace", OTPBackspace, Some("OTPInput")),
25        KeyBinding::new("delete", OTPDelete, Some("OTPInput")),
26        KeyBinding::new("left", OTPLeft, Some("OTPInput")),
27        KeyBinding::new("right", OTPRight, Some("OTPInput")),
28        KeyBinding::new("home", OTPHome, Some("OTPInput")),
29        KeyBinding::new("end", OTPEnd, Some("OTPInput")),
30        #[cfg(target_os = "macos")]
31        KeyBinding::new("cmd-v", OTPPaste, Some("OTPInput")),
32        #[cfg(not(target_os = "macos"))]
33        KeyBinding::new("ctrl-v", OTPPaste, Some("OTPInput")),
34        KeyBinding::new("escape", OTPEscape, Some("OTPInput")),
35    ]);
36}
37
38#[derive(Clone, Debug)]
39pub enum OTPInputEvent {
40    Change(String),
41    Complete(String),
42    Focus,
43    Blur,
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum OTPInputSize {
48    Sm,
49    Md,
50    Lg,
51}
52
53impl Default for OTPInputSize {
54    fn default() -> Self {
55        Self::Md
56    }
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum OTPInputState {
61    Default,
62    Error,
63    Success,
64}
65
66impl Default for OTPInputState {
67    fn default() -> Self {
68        Self::Default
69    }
70}
71
72pub struct OTPState {
73    focus_handles: Vec<FocusHandle>,
74    digits: Vec<Option<char>>,
75    focused_index: usize,
76    digit_count: usize,
77    masked: bool,
78    disabled: bool,
79    state: OTPInputState,
80    event_subscription: Option<Subscription>,
81}
82
83impl EventEmitter<OTPInputEvent> for OTPState {}
84
85impl OTPState {
86    pub fn new(cx: &mut Context<Self>, digit_count: usize) -> Self {
87        let digit_count = digit_count.clamp(4, 8);
88        let focus_handles: Vec<FocusHandle> = (0..digit_count).map(|_| cx.focus_handle()).collect();
89
90        Self {
91            focus_handles,
92            digits: vec![None; digit_count],
93            focused_index: 0,
94            digit_count,
95            masked: false,
96            disabled: false,
97            state: OTPInputState::Default,
98            event_subscription: None,
99        }
100    }
101
102    fn replace_event_subscription(&mut self, subscription: Option<Subscription>) {
103        self.event_subscription = subscription;
104    }
105
106    /// Set the digit count within the focus capacity created at construction.
107    ///
108    /// Prefer passing the final count to [`OTPState::new`]. Counts larger than
109    /// the construction capacity are clamped to that capacity so the builder
110    /// cannot create a state the renderer cannot focus safely.
111    #[deprecated(note = "pass digit_count to OTPState::new(cx, count) instead")]
112    pub fn digit_count(mut self, count: usize) -> Self {
113        let count = count.clamp(4, 8).min(self.focus_handles.len());
114        self.digit_count = count;
115        self.digits.resize(count, None);
116        self.focused_index = self.focused_index.min(count.saturating_sub(1));
117        self
118    }
119
120    pub fn masked(mut self, masked: bool) -> Self {
121        self.masked = masked;
122        self
123    }
124
125    pub fn value(&self) -> String {
126        self.digits.iter().filter_map(|d| *d).collect()
127    }
128
129    pub fn is_complete(&self) -> bool {
130        self.digits.iter().all(|d| d.is_some())
131    }
132
133    pub fn set_value(&mut self, value: &str, cx: &mut Context<Self>) {
134        self.digits.fill(None);
135
136        for (i, ch) in value.chars().take(self.digit_count).enumerate() {
137            if ch.is_ascii_digit() {
138                self.digits[i] = Some(ch);
139            }
140        }
141
142        cx.emit(OTPInputEvent::Change(self.value()));
143
144        if self.is_complete() {
145            cx.emit(OTPInputEvent::Complete(self.value()));
146        }
147
148        cx.notify();
149    }
150
151    pub fn clear(&mut self, cx: &mut Context<Self>) {
152        self.digits.fill(None);
153        self.focused_index = 0;
154        cx.emit(OTPInputEvent::Change(String::new()));
155        cx.notify();
156    }
157
158    pub fn set_state(&mut self, state: OTPInputState, cx: &mut Context<Self>) {
159        self.state = state;
160        cx.notify();
161    }
162
163    pub fn set_error(&mut self, cx: &mut Context<Self>) {
164        self.state = OTPInputState::Error;
165        cx.notify();
166    }
167
168    pub fn set_success(&mut self, cx: &mut Context<Self>) {
169        self.state = OTPInputState::Success;
170        cx.notify();
171    }
172
173    pub fn focus_first(&mut self, window: &mut Window, cx: &mut Context<Self>) {
174        self.focused_index = 0;
175        if let Some(handle) = self.focus_handles.first() {
176            window.focus(handle);
177        }
178        cx.notify();
179    }
180
181    fn set_digit(
182        &mut self,
183        index: usize,
184        digit: char,
185        window: &mut Window,
186        cx: &mut Context<Self>,
187    ) {
188        if index >= self.digit_count || !digit.is_ascii_digit() {
189            return;
190        }
191
192        self.digits[index] = Some(digit);
193        cx.emit(OTPInputEvent::Change(self.value()));
194
195        if self.is_complete() {
196            cx.emit(OTPInputEvent::Complete(self.value()));
197        } else if index + 1 < self.digit_count {
198            self.focused_index = index + 1;
199            window.focus(&self.focus_handles[index + 1]);
200        }
201
202        cx.notify();
203    }
204
205    fn clear_digit(&mut self, index: usize, cx: &mut Context<Self>) {
206        if index >= self.digit_count {
207            return;
208        }
209
210        self.digits[index] = None;
211        cx.emit(OTPInputEvent::Change(self.value()));
212        cx.notify();
213    }
214
215    fn move_left(&mut self, window: &mut Window, cx: &mut Context<Self>) {
216        if self.focused_index > 0 {
217            self.focused_index -= 1;
218            window.focus(&self.focus_handles[self.focused_index]);
219            cx.notify();
220        }
221    }
222
223    fn move_right(&mut self, window: &mut Window, cx: &mut Context<Self>) {
224        if self.focused_index + 1 < self.digit_count {
225            self.focused_index += 1;
226            window.focus(&self.focus_handles[self.focused_index]);
227            cx.notify();
228        }
229    }
230
231    fn move_home(&mut self, window: &mut Window, cx: &mut Context<Self>) {
232        self.focused_index = 0;
233        window.focus(&self.focus_handles[0]);
234        cx.notify();
235    }
236
237    fn move_end(&mut self, window: &mut Window, cx: &mut Context<Self>) {
238        self.focused_index = self.digit_count - 1;
239        window.focus(&self.focus_handles[self.focused_index]);
240        cx.notify();
241    }
242
243    pub fn backspace(&mut self, _: &OTPBackspace, window: &mut Window, cx: &mut Context<Self>) {
244        if self.disabled {
245            return;
246        }
247
248        if self.digits[self.focused_index].is_some() {
249            self.clear_digit(self.focused_index, cx);
250        } else if self.focused_index > 0 {
251            self.focused_index -= 1;
252            self.clear_digit(self.focused_index, cx);
253            window.focus(&self.focus_handles[self.focused_index]);
254        }
255    }
256
257    pub fn delete(&mut self, _: &OTPDelete, _window: &mut Window, cx: &mut Context<Self>) {
258        if self.disabled {
259            return;
260        }
261
262        self.clear_digit(self.focused_index, cx);
263    }
264
265    pub fn left(&mut self, _: &OTPLeft, window: &mut Window, cx: &mut Context<Self>) {
266        self.move_left(window, cx);
267    }
268
269    pub fn right(&mut self, _: &OTPRight, window: &mut Window, cx: &mut Context<Self>) {
270        self.move_right(window, cx);
271    }
272
273    pub fn home(&mut self, _: &OTPHome, window: &mut Window, cx: &mut Context<Self>) {
274        self.move_home(window, cx);
275    }
276
277    pub fn end(&mut self, _: &OTPEnd, window: &mut Window, cx: &mut Context<Self>) {
278        self.move_end(window, cx);
279    }
280
281    pub fn paste(&mut self, _: &OTPPaste, _window: &mut Window, cx: &mut Context<Self>) {
282        if self.disabled {
283            return;
284        }
285
286        if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) {
287            let digits: String = text.chars().filter(|c| c.is_ascii_digit()).collect();
288            self.set_value(&digits, cx);
289        }
290    }
291
292    pub fn escape(&mut self, _: &OTPEscape, window: &mut Window, cx: &mut Context<Self>) {
293        window.blur(cx);
294        cx.emit(OTPInputEvent::Blur);
295        cx.notify();
296    }
297
298    pub fn focus_handle(&self, index: usize, _: &App) -> Option<FocusHandle> {
299        self.focus_handles.get(index).cloned()
300    }
301}
302
303impl Focusable for OTPState {
304    fn focus_handle(&self, _: &App) -> FocusHandle {
305        self.focus_handles
306            .first()
307            .cloned()
308            .expect("OTPState must have at least one focus handle")
309    }
310}
311
312impl Render for OTPState {
313    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
314        div()
315    }
316}
317
318#[derive(IntoElement)]
319pub struct OTPInput {
320    state: Entity<OTPState>,
321    size: OTPInputSize,
322    disabled: bool,
323    masked: bool,
324    separator: Option<SharedString>,
325    separator_position: Option<usize>,
326    on_change: Option<Rc<dyn Fn(String, &mut App)>>,
327    on_complete: Option<Rc<dyn Fn(String, &mut App)>>,
328    style: StyleRefinement,
329}
330
331impl OTPInput {
332    pub fn new(state: &Entity<OTPState>) -> Self {
333        Self {
334            state: state.clone(),
335            size: OTPInputSize::default(),
336            disabled: false,
337            masked: false,
338            separator: None,
339            separator_position: None,
340            on_change: None,
341            on_complete: None,
342            style: StyleRefinement::default(),
343        }
344    }
345
346    pub fn size(mut self, size: OTPInputSize) -> Self {
347        self.size = size;
348        self
349    }
350
351    pub fn disabled(mut self, disabled: bool) -> Self {
352        self.disabled = disabled;
353        self
354    }
355
356    pub fn masked(mut self, masked: bool) -> Self {
357        self.masked = masked;
358        self
359    }
360
361    pub fn separator(mut self, separator: impl Into<SharedString>) -> Self {
362        self.separator = Some(separator.into());
363        self
364    }
365
366    pub fn separator_position(mut self, position: usize) -> Self {
367        self.separator_position = Some(position);
368        self
369    }
370
371    pub fn on_change<F>(mut self, callback: F) -> Self
372    where
373        F: Fn(String, &mut App) + 'static,
374    {
375        self.on_change = Some(Rc::new(callback));
376        self
377    }
378
379    pub fn on_complete<F>(mut self, callback: F) -> Self
380    where
381        F: Fn(String, &mut App) + 'static,
382    {
383        self.on_complete = Some(Rc::new(callback));
384        self
385    }
386
387    fn install_event_subscription(&self, cx: &mut App) {
388        let on_change = self.on_change.clone();
389        let on_complete = self.on_complete.clone();
390        let has_callbacks = on_change.is_some() || on_complete.is_some();
391
392        let subscription = has_callbacks.then(|| {
393            cx.subscribe(
394                &self.state,
395                move |_, event: &OTPInputEvent, cx| match event {
396                    OTPInputEvent::Change(value) => {
397                        if let Some(callback) = on_change.as_ref() {
398                            callback(value.clone(), cx);
399                        }
400                    }
401                    OTPInputEvent::Complete(value) => {
402                        if let Some(callback) = on_complete.as_ref() {
403                            callback(value.clone(), cx);
404                        }
405                    }
406                    OTPInputEvent::Focus | OTPInputEvent::Blur => {}
407                },
408            )
409        });
410
411        self.state.update(cx, |state, _| {
412            state.replace_event_subscription(subscription);
413        });
414    }
415
416    fn box_size(&self) -> Pixels {
417        match self.size {
418            OTPInputSize::Sm => px(36.0),
419            OTPInputSize::Md => px(44.0),
420            OTPInputSize::Lg => px(52.0),
421        }
422    }
423
424    fn font_size(&self) -> Pixels {
425        match self.size {
426            OTPInputSize::Sm => px(16.0),
427            OTPInputSize::Md => px(20.0),
428            OTPInputSize::Lg => px(24.0),
429        }
430    }
431
432    fn input_gap(&self) -> Pixels {
433        match self.size {
434            OTPInputSize::Sm => px(6.0),
435            OTPInputSize::Md => px(8.0),
436            OTPInputSize::Lg => px(10.0),
437        }
438    }
439}
440
441impl Styled for OTPInput {
442    fn style(&mut self) -> &mut StyleRefinement {
443        &mut self.style
444    }
445}
446
447impl RenderOnce for OTPInput {
448    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
449        let theme = use_theme(cx);
450        let box_size = self.box_size();
451        let font_size = self.font_size();
452        let input_gap = self.input_gap();
453
454        let otp_state = self.state.read(cx);
455        // Iterate based on the smaller of `digit_count` / `focus_handles.len()` /
456        // `digits.len()` to guarantee we never index out of bounds even if the
457        // fields ever desync.
458        let digit_count = otp_state
459            .digit_count
460            .min(otp_state.focus_handles.len())
461            .min(otp_state.digits.len());
462        let digits = otp_state.digits.clone();
463        let _focused_index = otp_state.focused_index;
464        let state = otp_state.state;
465        let masked = self.masked || otp_state.masked;
466        let disabled = self.disabled || otp_state.disabled;
467        let focus_handles = otp_state.focus_handles.to_vec();
468
469        self.state.update(cx, |state, _| {
470            state.disabled = disabled;
471            state.masked = masked;
472        });
473
474        self.install_event_subscription(cx);
475
476        let (border_color, focus_border_color) = match state {
477            OTPInputState::Default => (theme.tokens.border, theme.tokens.ring),
478            OTPInputState::Error => (theme.tokens.destructive, theme.tokens.destructive),
479            OTPInputState::Success => (theme.tokens.primary, theme.tokens.primary),
480        };
481
482        let user_style = self.style;
483        let separator = self.separator.clone();
484        let separator_position = self.separator_position.unwrap_or(digit_count / 2);
485
486        div()
487            .id(("otp-input", self.state.entity_id()))
488            .key_context("OTPInput")
489            .flex()
490            .items_center()
491            .gap(input_gap)
492            .when(!disabled, |this| {
493                this.on_action(window.listener_for(&self.state, OTPState::backspace))
494                    .on_action(window.listener_for(&self.state, OTPState::delete))
495                    .on_action(window.listener_for(&self.state, OTPState::left))
496                    .on_action(window.listener_for(&self.state, OTPState::right))
497                    .on_action(window.listener_for(&self.state, OTPState::home))
498                    .on_action(window.listener_for(&self.state, OTPState::end))
499                    .on_action(window.listener_for(&self.state, OTPState::paste))
500                    .on_action(window.listener_for(&self.state, OTPState::escape))
501            })
502            .children((0..digit_count).flat_map(|i| {
503                let state_clone = self.state.clone();
504                let focus_handle = focus_handles[i].clone();
505                let focus_handle_for_track = focus_handle.clone();
506                let focus_handle_for_click = focus_handle.clone();
507                let is_focused = focus_handle.is_focused(window);
508                let digit = digits[i];
509
510                let display_char = if let Some(d) = digit {
511                    if masked {
512                        SharedString::from("●")
513                    } else {
514                        SharedString::from(d.to_string())
515                    }
516                } else {
517                    SharedString::from("")
518                };
519
520                let digit_box = div()
521                    .id(ElementId::NamedInteger("otp-digit".into(), i as u64))
522                    .track_focus(&focus_handle_for_track.tab_index(0).tab_stop(true))
523                    .size(box_size)
524                    .flex()
525                    .items_center()
526                    .justify_center()
527                    .bg(if disabled {
528                        theme.tokens.muted.opacity(0.5)
529                    } else {
530                        theme.tokens.background
531                    })
532                    .border_1()
533                    .border_color(if is_focused && !disabled {
534                        focus_border_color
535                    } else {
536                        border_color
537                    })
538                    .rounded(theme.tokens.radius_md)
539                    .text_size(font_size)
540                    .font_weight(FontWeight::SEMIBOLD)
541                    .font_family(theme.tokens.font_mono.clone())
542                    .text_color(if disabled {
543                        theme.tokens.muted_foreground
544                    } else {
545                        theme.tokens.foreground
546                    })
547                    .when(is_focused && !disabled, |this| {
548                        this.shadow(smallvec::smallvec![theme.tokens.focus_ring_light()])
549                    })
550                    .when(!disabled, |this| {
551                        this.cursor(CursorStyle::IBeam)
552                            .hover(|style| style.border_color(focus_border_color))
553                    })
554                    .on_mouse_down(MouseButton::Left, {
555                        let state = state_clone.clone();
556                        move |_, window, cx| {
557                            window.focus(&focus_handle_for_click);
558                            state.update(cx, |s, cx| {
559                                s.focused_index = i;
560                                cx.notify();
561                            });
562                        }
563                    })
564                    .on_key_down({
565                        let state = state_clone.clone();
566                        move |event, window, cx| {
567                            if disabled {
568                                return;
569                            }
570
571                            let key = &event.keystroke.key;
572                            if key.len() == 1 {
573                                if let Some(ch) = key.chars().next() {
574                                    if ch.is_ascii_digit() {
575                                        state.update(cx, |s, cx| {
576                                            s.set_digit(i, ch, window, cx);
577                                        });
578                                        cx.stop_propagation();
579                                    }
580                                }
581                            }
582                        }
583                    })
584                    .child(display_char)
585                    .into_any_element();
586
587                let should_show_separator = separator.is_some()
588                    && separator_position > 0
589                    && i == separator_position - 1
590                    && i + 1 < digit_count;
591
592                if should_show_separator {
593                    vec![
594                        digit_box,
595                        div()
596                            .text_size(font_size)
597                            .text_color(theme.tokens.muted_foreground)
598                            .child(separator.clone().unwrap())
599                            .into_any_element(),
600                    ]
601                } else {
602                    vec![digit_box]
603                }
604            }))
605            .map(|this| {
606                let mut container = this;
607                container.style().refine(&user_style);
608                container
609            })
610    }
611}
612
613#[cfg(test)]
614mod tests {
615    use super::*;
616    use crate::capabilities::foundation::theme::{install_theme, Theme};
617    use std::{cell::Cell, rc::Rc};
618
619    struct OtpRenderTestView {
620        state: Entity<OTPState>,
621        callback_calls: Option<Rc<Cell<usize>>>,
622    }
623
624    impl Render for OtpRenderTestView {
625        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
626            OTPInput::new(&self.state).when_some(self.callback_calls.clone(), |input, calls| {
627                input.on_change(move |_, _| calls.set(calls.get() + 1))
628            })
629        }
630    }
631
632    #[gpui::test]
633    fn repeated_render_replaces_otp_event_subscription() {
634        let mut app = TestApp::new();
635        app.update(|cx| install_theme(cx, Theme::light()));
636        let stale_calls = Rc::new(Cell::new(0));
637        let current_calls = Rc::new(Cell::new(0));
638        let mut window = app.open_window(|_, cx| OtpRenderTestView {
639            state: cx.new(|cx| OTPState::new(cx, 6)),
640            callback_calls: Some(stale_calls.clone()),
641        });
642
643        window.draw();
644        window.update(|view, _, cx| {
645            view.callback_calls = Some(current_calls.clone());
646            cx.notify();
647        });
648        window.draw();
649        window.update(|view, _, cx| {
650            view.state
651                .update(cx, |_, cx| cx.emit(OTPInputEvent::Change("1".to_string())));
652        });
653        assert_eq!(stale_calls.get(), 0);
654        assert_eq!(current_calls.get(), 1);
655
656        window.update(|view, _, cx| {
657            view.callback_calls = None;
658            cx.notify();
659        });
660        window.draw();
661        window.update(|view, _, cx| {
662            view.state
663                .update(cx, |_, cx| cx.emit(OTPInputEvent::Change("2".to_string())));
664        });
665        assert_eq!(current_calls.get(), 1);
666    }
667
668    #[gpui::test]
669    #[allow(deprecated)]
670    fn digit_count_builder_cannot_exceed_focus_capacity() {
671        let mut app = TestApp::new();
672        let state = app.update(|cx| cx.new(|cx| OTPState::new(cx, 4).digit_count(8)));
673
674        app.read(|cx| {
675            let state = state.read(cx);
676            assert_eq!(state.digit_count, 4);
677            assert_eq!(state.digits.len(), 4);
678            assert_eq!(state.focus_handles.len(), 4);
679        });
680    }
681
682    #[gpui::test]
683    #[allow(deprecated)]
684    fn digit_count_can_grow_again_within_focus_capacity() {
685        let mut app = TestApp::new();
686        let state =
687            app.update(|cx| cx.new(|cx| OTPState::new(cx, 8).digit_count(4).digit_count(8)));
688
689        app.update(|cx| {
690            state.update(cx, |state, cx| state.set_value("12345678", cx));
691        });
692
693        app.read(|cx| {
694            let state = state.read(cx);
695            assert_eq!(state.value(), "12345678");
696            assert_eq!(state.digit_count, 8);
697            assert_eq!(state.digits.len(), 8);
698            assert_eq!(state.focus_handles.len(), 8);
699        });
700    }
701
702    struct OtpSeparatorTestView {
703        state: Entity<OTPState>,
704    }
705
706    impl Render for OtpSeparatorTestView {
707        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
708            OTPInput::new(&self.state)
709                .separator("-")
710                .separator_position(0)
711        }
712    }
713
714    #[gpui::test]
715    fn separator_position_zero_renders_without_panic() {
716        let mut app = TestApp::new();
717        app.update(|cx| install_theme(cx, Theme::light()));
718        let mut window = app.open_window(|_, cx| OtpSeparatorTestView {
719            state: cx.new(|cx| OTPState::new(cx, 6)),
720        });
721        // 修复前:渲染时 separator_position - 1 在 0 处 usize 下溢 panic
722        window.draw();
723    }
724}