Skip to main content

arc_ui/blocks/
otp_input.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: registry/components/otp-input/otp-input.tsx + module.css.
3//! GPUI 的基础 OtpState 仅支持末尾追加,故复用 InputState 实现逐槽编辑、IME 与粘贴。
4use super::child_id;
5use crate::inputs::field_message::render_field_message;
6use arc_motion::{
7    arc_spring, arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
8};
9use arc_tokens::{ActiveArcTheme as _, BlockTokens, Radii, Spacing, Typography, oklab_mix};
10use gpui_kit::base::ElementExt as _;
11use gpui_kit::component::input::{
12    Backspace, Input as KitInput, InputEvent, InputState, MoveLeft, MoveRight,
13};
14use gpui_kit::{
15    App, BorderStyle, Bounds, Context, Corners, Edges, ElementId, Entity, Focusable as _,
16    IntoElement, KeyDownEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Size, Styled,
17    Subscription, TestSupportExt as _, TextAlign, Window, bounds, canvas, div, point, prelude::*,
18    px, quad,
19};
20use std::{cell::RefCell, rc::Rc};
21
22#[derive(Default)]
23struct RingGeometry {
24    focused: Option<usize>,
25    target: Option<Bounds<Pixels>>,
26    row_size: Option<Size<Pixels>>,
27}
28type Change = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30pub enum OtpInputMode {
31    #[default]
32    Numeric,
33    Text,
34}
35pub fn sanitize_otp(raw: &str, mode: OtpInputMode, length: usize) -> String {
36    raw.chars()
37        .filter(|c| mode == OtpInputMode::Text || c.is_ascii_digit())
38        .take(length)
39        .collect()
40}
41struct State {
42    inputs: Vec<Entity<InputState>>,
43    slots: Vec<String>,
44    on_change: Option<Change>,
45    mode: OtpInputMode,
46    error_at: f64,
47    last_error: Option<SharedString>,
48    measured_slots: Rc<RefCell<Vec<Option<Bounds<Pixels>>>>>,
49    ring_geometry: Rc<RefCell<RingGeometry>>,
50    _subscriptions: Vec<Subscription>,
51}
52impl State {
53    fn new(length: usize, mode: OtpInputMode, window: &mut Window, cx: &mut Context<Self>) -> Self {
54        let inputs = (0..length)
55            .map(|_| cx.new(|cx| InputState::new(window, cx)))
56            .collect::<Vec<_>>();
57        let subscriptions = inputs
58            .iter()
59            .enumerate()
60            .map(|(index, input)| {
61                cx.subscribe_in(input, window, move |s, emitter, event, w, cx| {
62                    if !matches!(event, InputEvent::Change) {
63                        return;
64                    }
65                    let raw = emitter.read(cx).value().to_string();
66                    let clean = sanitize_otp(&raw, s.mode, s.inputs.len() - index);
67                    if clean.is_empty() {
68                        s.slots[index].clear();
69                    } else {
70                        for (offset, c) in clean.chars().enumerate() {
71                            s.slots[index + offset] = c.to_string();
72                        }
73                    }
74                    let count = clean.chars().count();
75                    for (slot, input) in s.inputs.iter().enumerate() {
76                        let text = s.slots[slot].clone();
77                        if input.read(cx).value().as_ref() != text {
78                            input.update(cx, |i, cx| i.set_value(text, w, cx));
79                        }
80                    }
81                    let next = (index + count).min(s.inputs.len() - 1);
82                    if count > 0 {
83                        s.inputs[next].update(cx, |i, cx| {
84                            i.focus(w, cx);
85                            i.select_all(w, cx);
86                        });
87                    }
88                    if let Some(cb) = &s.on_change {
89                        cb(&s.slots.concat().into(), w, cx)
90                    }
91                    cx.notify();
92                })
93            })
94            .collect();
95        Self {
96            slots: vec![String::new(); length],
97            inputs,
98            mode,
99            on_change: None,
100            error_at: f64::NEG_INFINITY,
101            last_error: None,
102            measured_slots: Rc::new(RefCell::new(vec![None; length])),
103            ring_geometry: Rc::default(),
104            _subscriptions: subscriptions,
105        }
106    }
107
108    fn navigate(&mut self, index: usize, step: i32, w: &mut Window, cx: &mut Context<Self>) {
109        let target =
110            (index as i64 + i64::from(step)).clamp(0, self.inputs.len() as i64 - 1) as usize;
111        self.inputs[target].update(cx, |i, cx| {
112            i.focus(w, cx);
113            i.select_all(w, cx);
114        });
115        cx.notify();
116    }
117
118    fn backspace(&mut self, index: usize, w: &mut Window, cx: &mut Context<Self>) {
119        let target = if self.slots[index].is_empty() {
120            index.saturating_sub(1)
121        } else {
122            index
123        };
124        self.slots[target].clear();
125        self.inputs[target].update(cx, |i, cx| {
126            i.set_value("", w, cx);
127            i.focus(w, cx);
128        });
129        if let Some(cb) = &self.on_change {
130            cb(&self.slots.concat().into(), w, cx);
131        }
132        cx.notify();
133    }
134
135    /// Delete 键只清当前槽,不回退到前一位(与上游 OTP 行为一致)。
136    fn delete_forward(&mut self, index: usize, w: &mut Window, cx: &mut Context<Self>) {
137        if self.slots[index].is_empty() {
138            return;
139        }
140        self.slots[index].clear();
141        self.inputs[index].update(cx, |i, cx| {
142            i.set_value("", w, cx);
143            i.focus(w, cx);
144        });
145        if let Some(cb) = &self.on_change {
146            cb(&self.slots.concat().into(), w, cx);
147        }
148        cx.notify();
149    }
150}
151#[derive(IntoElement)]
152pub struct OtpInput {
153    id: ElementId,
154    label: SharedString,
155    length: usize,
156    value: Option<SharedString>,
157    description: Option<SharedString>,
158    error: Option<SharedString>,
159    auto_focus: bool,
160    disabled: bool,
161    mode: OtpInputMode,
162    on_change: Option<Change>,
163}
164impl OtpInput {
165    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
166        Self {
167            id: id.into(),
168            label: label.into(),
169            length: 6,
170            value: None,
171            description: None,
172            error: None,
173            auto_focus: false,
174            disabled: false,
175            mode: OtpInputMode::Numeric,
176            on_change: None,
177        }
178    }
179    pub fn length(mut self, v: usize) -> Self {
180        self.length = v.max(1);
181        self
182    }
183    pub fn value(mut self, v: impl Into<SharedString>) -> Self {
184        self.value = Some(v.into());
185        self
186    }
187    pub fn description(mut self, v: impl Into<SharedString>) -> Self {
188        self.description = Some(v.into());
189        self
190    }
191    pub fn error(mut self, v: impl Into<SharedString>) -> Self {
192        self.error = Some(v.into());
193        self
194    }
195    pub fn auto_focus(mut self, v: bool) -> Self {
196        self.auto_focus = v;
197        self
198    }
199    pub fn disabled(mut self, v: bool) -> Self {
200        self.disabled = v;
201        self
202    }
203    pub fn input_mode(mut self, v: OtpInputMode) -> Self {
204        self.mode = v;
205        self
206    }
207    pub fn on_change(mut self, f: impl Fn(&SharedString, &mut Window, &mut App) + 'static) -> Self {
208        self.on_change = Some(Rc::new(f));
209        self
210    }
211}
212impl RenderOnce for OtpInput {
213    fn render(self, w: &mut Window, cx: &mut App) -> impl IntoElement {
214        let colors = cx.arc_theme().colors;
215        let motion = cx.arc_theme().motion;
216        let state = w.use_keyed_state(
217            child_id(&self.id, format!("state-{}", self.length)),
218            cx,
219            |w, cx| {
220                let s = State::new(self.length, self.mode, w, cx);
221                if self.auto_focus && !self.disabled {
222                    let input = s.inputs[0].clone();
223                    w.on_next_frame(move |w, cx| input.update(cx, |i, cx| i.focus(w, cx)));
224                }
225                s
226            },
227        );
228        state.update(cx, |s, _| {
229            s.on_change = self.on_change;
230            s.mode = self.mode;
231        });
232        if let Some(value) = self.value {
233            let next = sanitize_otp(&value, self.mode, self.length);
234            if state.read(cx).slots.concat() != next {
235                state.update(cx, |s, cx| {
236                    s.slots = next
237                        .chars()
238                        .map(|c| c.to_string())
239                        .chain(std::iter::repeat(String::new()))
240                        .take(self.length)
241                        .collect();
242                    for (i, input) in s.inputs.iter().enumerate() {
243                        input.update(cx, |input, cx| input.set_value(s.slots[i].clone(), w, cx));
244                    }
245                });
246            }
247        }
248        // 新的错误文案触发一次横向回弹,作为对提交动作的反馈。
249        if state.read(cx).last_error != self.error {
250            let now = motion_now(cx);
251            let next = self.error.clone();
252            state.update(cx, |s, _| {
253                s.last_error = next;
254                s.error_at = now;
255            });
256        }
257        let shake = if self.error.is_some() && !is_reduced_motion(cx) {
258            let elapsed = (motion_now(cx) - state.read(cx).error_at).max(0.0);
259            if elapsed < 0.36 {
260                w.request_animation_frame();
261                let p = (elapsed / 0.36) as f32;
262                (p * std::f32::consts::TAU * 3.0).sin() * 6.0 * (1.0 - p)
263            } else {
264                0.0
265            }
266        } else {
267            0.0
268        };
269        let inputs = state.read(cx).inputs.clone();
270        let measured_slots = state.read(cx).measured_slots.clone();
271        // 上游 .inputs:fit-content,窄容器下槽位等比收缩(flex: 0 1 42px)。
272        let row_width = BlockTokens::OTP_WIDTH * self.length as f32
273            + BlockTokens::OTP_GAP * self.length.saturating_sub(1) as f32;
274        let mut row = div()
275            .id(child_id(&self.id, "slots"))
276            .role(Role::Group)
277            .aria_label(self.label.clone())
278            .relative()
279            .flex()
280            .gap(BlockTokens::OTP_GAP)
281            .w(row_width)
282            .max_w_full()
283            .ml(px(shake));
284        let invalid = self.error.is_some();
285        for (index, input) in inputs.iter().enumerate() {
286            let filled = !input.read(cx).value().is_empty();
287            let click_input = input.clone();
288            let left_state = state.clone();
289            let right_state = state.clone();
290            let backspace_state = state.clone();
291            let delete_state = state.clone();
292            let disabled = self.disabled;
293            let measured = measured_slots.clone();
294            // 上游 .input 基础态:border + surface;hover:border-strong + surface-muted;
295            // 填充:accent 边框 + accent-subtle 背景;错误:danger 边框 + 7% danger 混色背景。
296            let mut slot = div()
297                .id(child_id(&self.id, format!("slot-{index}")))
298                .test_support()
299                .on_prepaint(move |bounds, _, _| {
300                    // on_prepaint 的绝对子 canvas 得到 padding box,补回槽位的 1px 边框。
301                    measured.borrow_mut()[index] = Some(bounds.extend(Edges::all(px(1.0))));
302                })
303                .relative()
304                .overflow_hidden()
305                .track_focus(&input.read(cx).focus_handle(cx))
306                .min_w(px(0.0))
307                .w(BlockTokens::OTP_WIDTH)
308                .h(BlockTokens::OTP_HEIGHT)
309                .flex_shrink(1.0)
310                .flex_grow(0.0)
311                .flex_basis(BlockTokens::OTP_WIDTH)
312                .rounded(Radii::CONTROL)
313                .border_1()
314                .border_color(if invalid {
315                    colors.danger
316                } else if filled {
317                    colors.accent
318                } else {
319                    colors.border
320                })
321                .bg(if invalid {
322                    oklab_mix(colors.danger, colors.surface, 0.07)
323                } else if filled {
324                    colors.accent_subtle
325                } else {
326                    colors.surface
327                })
328                .hover(move |s| {
329                    if !disabled && !filled && !invalid {
330                        s.border_color(colors.border_strong)
331                            .bg(colors.surface_muted)
332                    } else {
333                        s
334                    }
335                })
336                .text_size(Typography::TEXT_LG)
337                .when(disabled, |d| d.opacity(0.48).bg(colors.surface_muted))
338                .on_mouse_down(gpui_kit::MouseButton::Left, move |_, w, cx| {
339                    if !disabled {
340                        click_input.update(cx, |i, cx| {
341                            i.focus(w, cx);
342                            i.select_all(w, cx);
343                        });
344                    }
345                })
346                // 原生输入先解析键绑定;捕获 action,避免退格继续删除相邻槽的字符。
347                .capture_action(move |_: &MoveLeft, w, cx| {
348                    if !disabled {
349                        left_state.update(cx, |s, cx| s.navigate(index, -1, w, cx));
350                    }
351                    cx.stop_propagation();
352                })
353                .capture_action(move |_: &MoveRight, w, cx| {
354                    if !disabled {
355                        right_state.update(cx, |s, cx| s.navigate(index, 1, w, cx));
356                    }
357                    cx.stop_propagation();
358                })
359                .capture_action(move |_: &Backspace, w, cx| {
360                    if !disabled {
361                        backspace_state.update(cx, |s, cx| s.backspace(index, w, cx));
362                    }
363                    cx.stop_propagation();
364                })
365                // Delete 只清当前槽;先于内层输入捕获,避免原生删除二次消费。
366                .capture_key_down(move |event: &KeyDownEvent, w, cx| {
367                    if !disabled && event.keystroke.key == "delete" {
368                        delete_state.update(cx, |s, cx| s.delete_forward(index, w, cx));
369                        cx.stop_propagation();
370                    }
371                })
372                .child(
373                    KitInput::new(input)
374                        .appearance(false)
375                        .text_color(gpui_kit::Hsla::transparent_black())
376                        .text_align(TextAlign::Center)
377                        .text_size(Typography::TEXT_LG)
378                        .p(px(0.0))
379                        .min_w(px(0.0))
380                        .id(child_id(&self.id, format!("input-{index}")))
381                        .aria_label(format!(
382                            "{}, digit {} of {}",
383                            self.label,
384                            index + 1,
385                            self.length
386                        ))
387                        .disabled(disabled)
388                        .size_full(),
389                );
390            // 原生文本透明,独立字形层只绘制数字,不再用不透明矩形遮住槽位描边。
391            if !input.read(cx).value().is_empty() {
392                let ch = input.read(cx).value().to_string();
393                let rise = arc_spring_with_options(
394                    (
395                        child_id(&self.id, format!("glyph-{index}")),
396                        SharedString::from(ch.clone()),
397                    ),
398                    0.0,
399                    SpringOptions::new(motion.spring.snappy).with_initial_value(4.0),
400                    w,
401                    cx,
402                );
403                if !rise.settled {
404                    w.request_animation_frame();
405                }
406                let opacity = (1.0 - rise.value / 4.0).clamp(0.0, 1.0);
407                let click = input.clone();
408                slot = slot.child(
409                    div()
410                        .id(child_id(&self.id, format!("glyph-{index}")))
411                        .absolute()
412                        .inset_0()
413                        .flex()
414                        .items_center()
415                        .justify_center()
416                        .text_color(colors.foreground)
417                        .mt(px(rise.value))
418                        .opacity(opacity)
419                        .on_mouse_down(gpui_kit::MouseButton::Left, move |_, w, cx| {
420                            if !disabled {
421                                click.update(cx, |i, cx| {
422                                    i.focus(w, cx);
423                                    i.select_all(w, cx);
424                                });
425                            }
426                        })
427                        .child(ch),
428                );
429            }
430            row = row.child(slot);
431        }
432        // 所有槽 prepaint 后,按当帧实测边界绘制唯一焦点环;绝不按容器宽度均分。
433        let focused = if self.disabled {
434            None
435        } else {
436            inputs
437                .iter()
438                .position(|i| i.read(cx).focus_handle(cx).is_focused(w))
439        };
440        let ring_op = arc_spring(
441            (child_id(&self.id, "ring-show"), "opacity"),
442            if focused.is_some() { 1.0 } else { 0.0 },
443            motion.spring.snappy,
444            w,
445            cx,
446        )
447        .clamp(0.0, 1.0);
448        let geometry = state.read(cx).ring_geometry.clone();
449        let ring_id = child_id(&self.id, "ring-x");
450        row = row.child(
451            canvas(
452                |_, _, _| {},
453                move |rect, _, window, cx| {
454                    let mut geometry = geometry.borrow_mut();
455                    let resized = geometry.row_size != Some(rect.size);
456                    let entering = geometry.focused.is_none();
457                    let target = focused
458                        .and_then(|index| measured_slots.borrow()[index])
459                        .map(|slot| bounds(slot.origin - rect.origin, slot.size));
460                    // 外部进入或收缩布局直接对齐;只有组内换焦点才滑行。
461                    if let Some(target) = target {
462                        geometry.target = Some(target);
463                    }
464                    let Some(target) = geometry.target else {
465                        return;
466                    };
467                    let x = arc_spring_with_options(
468                        (ring_id.clone(), "x"),
469                        f32::from(target.origin.x),
470                        SpringOptions::new(motion.spring.snappy).with_travel(!entering && !resized),
471                        window,
472                        cx,
473                    )
474                    .value;
475                    geometry.focused = focused;
476                    geometry.row_size = Some(rect.size);
477                    if ring_op <= 0.01 {
478                        return;
479                    }
480                    let mut color = if invalid {
481                        colors.danger
482                    } else {
483                        colors.accent_strong
484                    };
485                    color.a *= ring_op;
486                    window.paint_quad(quad(
487                        bounds(rect.origin + point(px(x), target.origin.y), target.size),
488                        Corners::all(Radii::CONTROL),
489                        gpui_kit::Hsla::transparent_black(),
490                        Edges::all(px(1.0)),
491                        color,
492                        BorderStyle::Solid,
493                    ));
494                },
495            )
496            .absolute()
497            .inset_0(),
498        );
499        div()
500            .id(self.id.clone())
501            .w_full()
502            .flex()
503            .flex_col()
504            .gap(Spacing::S2)
505            .text_color(colors.foreground)
506            .child(self.label)
507            .child(row)
508            .child(render_field_message(
509                child_id(&self.id, "description"),
510                self.description,
511                false,
512                w,
513                cx,
514            ))
515            .child(render_field_message(
516                child_id(&self.id, "error"),
517                self.error,
518                true,
519                w,
520                cx,
521            ))
522    }
523}
524#[cfg(test)]
525mod tests {
526    use super::*;
527    #[test]
528    fn sanitize_is_unicode_safe() {
529        assert_eq!(
530            sanitize_otp("a1中23-4567", OtpInputMode::Numeric, 6),
531            "123456"
532        );
533        assert_eq!(sanitize_otp("你好a", OtpInputMode::Text, 2), "你好");
534    }
535}