1use std::rc::Rc;
4
5use gpui::{
6 AnyElement, App, AppContext as _, Context, ElementId, Entity, EventEmitter, FocusHandle,
7 Focusable as _, InteractiveElement as _, IntoElement, MouseButton, ParentElement as _,
8 RenderOnce, Role, SharedString, StyleRefinement, Styled, Subscription, Window, div,
9};
10
11use crate::{
12 Input, InputBase, TestSupportExt as _,
13 input::{InputAccessibility, InputEvent, InputState},
14};
15
16#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct InputOtpEvent {
20 pub value: SharedString,
21 pub complete: bool,
22}
23
24pub struct InputOtpState {
31 input: Entity<InputState>,
32 length: usize,
33 _subscriptions: Vec<Subscription>,
34}
35
36impl InputOtpState {
37 pub fn new(length: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
39 assert!(length > 0, "InputOtp needs at least one digit");
40 let input = cx.new(|cx| {
41 InputState::new(window, cx)
42 .validate(move |value, _| {
43 value.len() <= length && value.bytes().all(|byte| byte.is_ascii_digit())
44 })
45 .placeholder("")
46 });
47 let subscriptions = vec![
48 cx.observe(&input, |_, _, cx| cx.notify()),
49 cx.subscribe(&input, |state, input, event: &InputEvent, cx| {
50 if matches!(event, InputEvent::Change) {
51 let value = input.read(cx).value();
52 cx.emit(InputOtpEvent {
53 complete: value.len() == state.length,
54 value,
55 });
56 }
57 }),
58 ];
59 Self {
60 input,
61 length,
62 _subscriptions: subscriptions,
63 }
64 }
65
66 pub fn length(&self) -> usize {
67 self.length
68 }
69
70 pub fn value(&self, cx: &App) -> SharedString {
71 self.input.read(cx).value()
72 }
73
74 pub fn is_complete(&self, cx: &App) -> bool {
75 self.value(cx).len() == self.length
76 }
77
78 pub fn focus_handle(&self, cx: &App) -> FocusHandle {
79 self.input.focus_handle(cx)
80 }
81
82 pub fn input(&self) -> &Entity<InputState> {
86 &self.input
87 }
88
89 pub fn set_value(
92 &mut self,
93 value: impl Into<SharedString>,
94 window: &mut Window,
95 cx: &mut Context<Self>,
96 ) -> bool {
97 let value = value.into();
98 if value.len() > self.length || !value.bytes().all(|byte| byte.is_ascii_digit()) {
99 return false;
100 }
101 self.input
102 .update(cx, |input, cx| input.set_value(value, window, cx));
103 cx.notify();
104 true
105 }
106
107 pub fn set_disabled(&mut self, disabled: bool, cx: &mut Context<Self>) {
108 self.input
109 .update(cx, |input, cx| input.set_disabled(disabled, cx));
110 }
111
112 pub fn set_readonly(&mut self, readonly: bool, cx: &mut Context<Self>) {
113 self.input
114 .update(cx, |input, cx| input.set_readonly(readonly, cx));
115 }
116}
117
118impl EventEmitter<InputOtpEvent> for InputOtpState {}
119
120#[derive(Clone, Copy, Debug)]
123pub struct InputOtpSlot {
124 pub index: usize,
125 pub character: Option<char>,
126 pub active: bool,
127 pub selected: bool,
128 pub disabled: bool,
129 pub readonly: bool,
130}
131
132type SlotRenderer = Rc<dyn Fn(InputOtpSlot, &mut Window, &mut App) -> AnyElement>;
133
134#[derive(IntoElement)]
142pub struct InputOtp {
143 id: ElementId,
144 base: InputBase,
145 state: Entity<InputOtpState>,
146 label: Option<SharedString>,
147 description: Option<SharedString>,
148 slot: SlotRenderer,
149}
150
151impl InputOtp {
152 pub fn new(id: impl Into<ElementId>, state: &Entity<InputOtpState>) -> Self {
153 let id = id.into();
154 Self {
155 base: InputBase::new(id.clone()).role(None::<Role>),
156 id,
157 state: state.clone(),
158 label: None,
159 description: None,
160 slot: Rc::new(|slot, _, _| {
161 div()
162 .child(slot.character.unwrap_or('_').to_string())
163 .into_any_element()
164 }),
165 }
166 }
167
168 pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
169 self.label = Some(label.into());
170 self
171 }
172
173 pub fn accessibility_description(mut self, description: impl Into<SharedString>) -> Self {
174 self.description = Some(description.into());
175 self
176 }
177
178 pub fn slot<R: IntoElement>(
179 mut self,
180 render: impl Fn(InputOtpSlot, &mut Window, &mut App) -> R + 'static,
181 ) -> Self {
182 self.slot = Rc::new(move |slot, window, cx| render(slot, window, cx).into_any_element());
183 self
184 }
185}
186
187impl Styled for InputOtp {
188 fn style(&mut self) -> &mut StyleRefinement {
189 self.base.style()
190 }
191}
192
193impl RenderOnce for InputOtp {
194 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
195 let model = self.state.read(cx);
196 let length = model.length;
197 let input = model.input.clone();
198 let value = input.read(cx).value();
199 let selection = input.read(cx).selected_range();
200 let cursor = input.read(cx).cursor();
201 let presentation = input.read(cx).presentation();
202 let disabled = presentation.is_disabled();
203 let readonly = presentation.is_readonly();
204 let focus = input.focus_handle(cx);
205 let focused = focus.is_focused(window);
206 input.update(cx, |input, _| {
207 let mut accessibility = input
208 .accessibility()
209 .cloned()
210 .unwrap_or_else(|| InputAccessibility::new(Some(Role::TextInput)));
211 if let Some(label) = self.label {
212 accessibility = accessibility.with_label(Some(label));
213 }
214 if let Some(description) = self.description {
215 accessibility = accessibility.with_description(Some(description));
216 }
217 input.set_accessibility(accessibility);
218 });
219 let slots = (0..length).map(|index| {
220 let input = input.clone();
221 let slot = InputOtpSlot {
222 index,
223 character: value.as_bytes().get(index).map(|byte| char::from(*byte)),
224 active: focused && cursor.min(length - 1) == index,
225 selected: focused && selection.contains(&index),
226 disabled,
227 readonly,
228 };
229 div()
230 .id((self.id.clone(), index.to_string()))
231 .test_support()
232 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
233 cx.stop_propagation();
234 input.update(cx, |input, cx| {
235 if !input.presentation().is_disabled() {
236 input.focus(window, cx);
237 let length = input.value().len();
238 let start = index.min(length);
239 input.set_selected_range(start..(start + 1).min(length), cx);
240 }
241 });
242 })
243 .child((self.slot)(slot, window, cx))
244 });
245 self.base
246 .semantic_owner::<Input>(input.entity_id())
247 .focused(focused)
248 .disabled(disabled)
249 .relative()
250 .flex()
251 .child(
252 div()
253 .absolute()
254 .inset_0()
255 .size_full()
256 .opacity(0.)
257 .child(Input::new(&input)),
258 )
259 .children(slots)
260 }
261}
262
263#[cfg(test)]
264mod tests {
265 use gpui::{ClipboardItem, Modifiers, Render, TestAppContext, px};
266
267 use super::*;
268
269 struct Harness {
270 state: Entity<InputOtpState>,
271 after: FocusHandle,
272 _subscription: Subscription,
273 }
274
275 impl Render for Harness {
276 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
277 div()
278 .size_full()
279 .child(
280 InputOtp::new("otp", &self.state)
281 .accessibility_label("Verification code")
282 .slot(|slot, _, _| {
283 div()
284 .debug_selector(move || format!("otp-slot-{}", slot.index))
285 .w(px(36.))
286 .h(px(40.))
287 .child(slot.character.unwrap_or('_').to_string())
288 }),
289 )
290 .child(
291 crate::Button::new("after")
292 .track_focus(&self.after)
293 .child("After"),
294 )
295 }
296 }
297
298 #[gpui::test]
299 fn one_editor_owns_paste_selection_deletion_and_slot_focus(cx: &mut TestAppContext) {
300 cx.update(crate::init);
301 let (root, cx) = cx.add_window_view(|window, cx| {
302 let view = cx.new(|cx| {
303 let state = cx.new(|cx| InputOtpState::new(6, window, cx));
304 Harness {
305 _subscription: cx.observe(&state, |_, _, cx| cx.notify()),
306 state,
307 after: cx.focus_handle(),
308 }
309 });
310 crate::Root::new(view, window, cx)
311 });
312 let view = root
313 .read_with(cx, |root, _| root.view().clone())
314 .downcast::<Harness>()
315 .unwrap();
316 cx.update(|window, cx| {
317 window.activate_window();
318 view.read(cx)
319 .state
320 .read(cx)
321 .focus_handle(cx)
322 .focus(window, cx);
323 window.draw(cx).clear(cx);
324 cx.write_to_clipboard(ClipboardItem::new_string("123456".into()));
325 });
326 cx.simulate_keystrokes(if cfg!(target_os = "macos") {
327 "cmd-v"
328 } else {
329 "ctrl-v"
330 });
331 cx.simulate_input("7");
332 cx.simulate_input("x");
333 cx.update(|_, cx| assert_eq!(view.read(cx).state.read(cx).value(cx), "123456"));
334 cx.simulate_keystrokes("left backspace");
335 cx.update(|_, cx| assert_eq!(view.read(cx).state.read(cx).value(cx), "12346"));
336 cx.simulate_input("9");
337 cx.update(|window, cx| {
338 assert_eq!(view.read(cx).state.read(cx).value(cx), "123496");
339 assert!(view.read(cx).state.read(cx).is_complete(cx));
340 window.draw(cx).clear(cx);
341 });
342 let slot = cx.debug_bounds("otp-slot-1").unwrap().center();
343 cx.simulate_click(slot, Modifiers::default());
344 cx.simulate_input("8");
345 cx.update(|_, cx| assert_eq!(view.read(cx).state.read(cx).value(cx), "183496"));
346 cx.simulate_keystrokes("tab");
347 cx.update(|window, cx| {
348 assert!(
349 view.read(cx).after.is_focused(window),
350 "slots add no Tab stops"
351 );
352 let state = view.read(cx).state.clone();
353 state.update(cx, |state, cx| state.set_disabled(true, cx));
354 window.draw(cx).clear(cx);
355 });
356 cx.simulate_click(slot, Modifiers::default());
357 cx.update(|window, cx| assert!(view.read(cx).after.is_focused(window)));
358 }
359}