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