arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: registry/components/otp-input/otp-input.tsx + module.css.
//! GPUI 的基础 OtpState 仅支持末尾追加,故复用 InputState 实现逐槽编辑、IME 与粘贴。
use super::child_id;
use crate::inputs::field_message::render_field_message;
use arc_motion::{
    arc_spring, arc_spring_with_options, is_reduced_motion, motion_now, spring::SpringOptions,
};
use arc_tokens::{ActiveArcTheme as _, BlockTokens, Radii, Spacing, Typography, oklab_mix};
use gpui_kit::base::ElementExt as _;
use gpui_kit::component::input::{
    Backspace, Input as KitInput, InputEvent, InputState, MoveLeft, MoveRight,
};
use gpui_kit::{
    App, BorderStyle, Bounds, Context, Corners, Edges, ElementId, Entity, Focusable as _,
    IntoElement, KeyDownEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Size, Styled,
    Subscription, TestSupportExt as _, TextAlign, Window, bounds, canvas, div, point, prelude::*,
    px, quad,
};
use std::{cell::RefCell, rc::Rc};

#[derive(Default)]
struct RingGeometry {
    focused: Option<usize>,
    target: Option<Bounds<Pixels>>,
    row_size: Option<Size<Pixels>>,
}
type Change = Rc<dyn Fn(&SharedString, &mut Window, &mut App)>;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OtpInputMode {
    #[default]
    Numeric,
    Text,
}
pub fn sanitize_otp(raw: &str, mode: OtpInputMode, length: usize) -> String {
    raw.chars()
        .filter(|c| mode == OtpInputMode::Text || c.is_ascii_digit())
        .take(length)
        .collect()
}
struct State {
    inputs: Vec<Entity<InputState>>,
    slots: Vec<String>,
    on_change: Option<Change>,
    mode: OtpInputMode,
    error_at: f64,
    last_error: Option<SharedString>,
    measured_slots: Rc<RefCell<Vec<Option<Bounds<Pixels>>>>>,
    ring_geometry: Rc<RefCell<RingGeometry>>,
    _subscriptions: Vec<Subscription>,
}
impl State {
    fn new(length: usize, mode: OtpInputMode, window: &mut Window, cx: &mut Context<Self>) -> Self {
        let inputs = (0..length)
            .map(|_| cx.new(|cx| InputState::new(window, cx)))
            .collect::<Vec<_>>();
        let subscriptions = inputs
            .iter()
            .enumerate()
            .map(|(index, input)| {
                cx.subscribe_in(input, window, move |s, emitter, event, w, cx| {
                    if !matches!(event, InputEvent::Change) {
                        return;
                    }
                    let raw = emitter.read(cx).value().to_string();
                    let clean = sanitize_otp(&raw, s.mode, s.inputs.len() - index);
                    if clean.is_empty() {
                        s.slots[index].clear();
                    } else {
                        for (offset, c) in clean.chars().enumerate() {
                            s.slots[index + offset] = c.to_string();
                        }
                    }
                    let count = clean.chars().count();
                    for (slot, input) in s.inputs.iter().enumerate() {
                        let text = s.slots[slot].clone();
                        if input.read(cx).value().as_ref() != text {
                            input.update(cx, |i, cx| i.set_value(text, w, cx));
                        }
                    }
                    let next = (index + count).min(s.inputs.len() - 1);
                    if count > 0 {
                        s.inputs[next].update(cx, |i, cx| {
                            i.focus(w, cx);
                            i.select_all(w, cx);
                        });
                    }
                    if let Some(cb) = &s.on_change {
                        cb(&s.slots.concat().into(), w, cx)
                    }
                    cx.notify();
                })
            })
            .collect();
        Self {
            slots: vec![String::new(); length],
            inputs,
            mode,
            on_change: None,
            error_at: f64::NEG_INFINITY,
            last_error: None,
            measured_slots: Rc::new(RefCell::new(vec![None; length])),
            ring_geometry: Rc::default(),
            _subscriptions: subscriptions,
        }
    }

    fn navigate(&mut self, index: usize, step: i32, w: &mut Window, cx: &mut Context<Self>) {
        let target =
            (index as i64 + i64::from(step)).clamp(0, self.inputs.len() as i64 - 1) as usize;
        self.inputs[target].update(cx, |i, cx| {
            i.focus(w, cx);
            i.select_all(w, cx);
        });
        cx.notify();
    }

    fn backspace(&mut self, index: usize, w: &mut Window, cx: &mut Context<Self>) {
        let target = if self.slots[index].is_empty() {
            index.saturating_sub(1)
        } else {
            index
        };
        self.slots[target].clear();
        self.inputs[target].update(cx, |i, cx| {
            i.set_value("", w, cx);
            i.focus(w, cx);
        });
        if let Some(cb) = &self.on_change {
            cb(&self.slots.concat().into(), w, cx);
        }
        cx.notify();
    }

    /// Delete 键只清当前槽,不回退到前一位(与上游 OTP 行为一致)。
    fn delete_forward(&mut self, index: usize, w: &mut Window, cx: &mut Context<Self>) {
        if self.slots[index].is_empty() {
            return;
        }
        self.slots[index].clear();
        self.inputs[index].update(cx, |i, cx| {
            i.set_value("", w, cx);
            i.focus(w, cx);
        });
        if let Some(cb) = &self.on_change {
            cb(&self.slots.concat().into(), w, cx);
        }
        cx.notify();
    }
}
#[derive(IntoElement)]
pub struct OtpInput {
    id: ElementId,
    label: SharedString,
    length: usize,
    value: Option<SharedString>,
    description: Option<SharedString>,
    error: Option<SharedString>,
    auto_focus: bool,
    disabled: bool,
    mode: OtpInputMode,
    on_change: Option<Change>,
}
impl OtpInput {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            length: 6,
            value: None,
            description: None,
            error: None,
            auto_focus: false,
            disabled: false,
            mode: OtpInputMode::Numeric,
            on_change: None,
        }
    }
    pub fn length(mut self, v: usize) -> Self {
        self.length = v.max(1);
        self
    }
    pub fn value(mut self, v: impl Into<SharedString>) -> Self {
        self.value = Some(v.into());
        self
    }
    pub fn description(mut self, v: impl Into<SharedString>) -> Self {
        self.description = Some(v.into());
        self
    }
    pub fn error(mut self, v: impl Into<SharedString>) -> Self {
        self.error = Some(v.into());
        self
    }
    pub fn auto_focus(mut self, v: bool) -> Self {
        self.auto_focus = v;
        self
    }
    pub fn disabled(mut self, v: bool) -> Self {
        self.disabled = v;
        self
    }
    pub fn input_mode(mut self, v: OtpInputMode) -> Self {
        self.mode = v;
        self
    }
    pub fn on_change(mut self, f: impl Fn(&SharedString, &mut Window, &mut App) + 'static) -> Self {
        self.on_change = Some(Rc::new(f));
        self
    }
}
impl RenderOnce for OtpInput {
    fn render(self, w: &mut Window, cx: &mut App) -> impl IntoElement {
        let colors = cx.arc_theme().colors;
        let motion = cx.arc_theme().motion;
        let state = w.use_keyed_state(
            child_id(&self.id, format!("state-{}", self.length)),
            cx,
            |w, cx| {
                let s = State::new(self.length, self.mode, w, cx);
                if self.auto_focus && !self.disabled {
                    let input = s.inputs[0].clone();
                    w.on_next_frame(move |w, cx| input.update(cx, |i, cx| i.focus(w, cx)));
                }
                s
            },
        );
        state.update(cx, |s, _| {
            s.on_change = self.on_change;
            s.mode = self.mode;
        });
        if let Some(value) = self.value {
            let next = sanitize_otp(&value, self.mode, self.length);
            if state.read(cx).slots.concat() != next {
                state.update(cx, |s, cx| {
                    s.slots = next
                        .chars()
                        .map(|c| c.to_string())
                        .chain(std::iter::repeat(String::new()))
                        .take(self.length)
                        .collect();
                    for (i, input) in s.inputs.iter().enumerate() {
                        input.update(cx, |input, cx| input.set_value(s.slots[i].clone(), w, cx));
                    }
                });
            }
        }
        // 新的错误文案触发一次横向回弹,作为对提交动作的反馈。
        if state.read(cx).last_error != self.error {
            let now = motion_now(cx);
            let next = self.error.clone();
            state.update(cx, |s, _| {
                s.last_error = next;
                s.error_at = now;
            });
        }
        let shake = if self.error.is_some() && !is_reduced_motion(cx) {
            let elapsed = (motion_now(cx) - state.read(cx).error_at).max(0.0);
            if elapsed < 0.36 {
                w.request_animation_frame();
                let p = (elapsed / 0.36) as f32;
                (p * std::f32::consts::TAU * 3.0).sin() * 6.0 * (1.0 - p)
            } else {
                0.0
            }
        } else {
            0.0
        };
        let inputs = state.read(cx).inputs.clone();
        let measured_slots = state.read(cx).measured_slots.clone();
        // 上游 .inputs:fit-content,窄容器下槽位等比收缩(flex: 0 1 42px)。
        let row_width = BlockTokens::OTP_WIDTH * self.length as f32
            + BlockTokens::OTP_GAP * self.length.saturating_sub(1) as f32;
        let mut row = div()
            .id(child_id(&self.id, "slots"))
            .role(Role::Group)
            .aria_label(self.label.clone())
            .relative()
            .flex()
            .gap(BlockTokens::OTP_GAP)
            .w(row_width)
            .max_w_full()
            .ml(px(shake));
        let invalid = self.error.is_some();
        for (index, input) in inputs.iter().enumerate() {
            let filled = !input.read(cx).value().is_empty();
            let click_input = input.clone();
            let left_state = state.clone();
            let right_state = state.clone();
            let backspace_state = state.clone();
            let delete_state = state.clone();
            let disabled = self.disabled;
            let measured = measured_slots.clone();
            // 上游 .input 基础态:border + surface;hover:border-strong + surface-muted;
            // 填充:accent 边框 + accent-subtle 背景;错误:danger 边框 + 7% danger 混色背景。
            let mut slot = div()
                .id(child_id(&self.id, format!("slot-{index}")))
                .test_support()
                .on_prepaint(move |bounds, _, _| {
                    // on_prepaint 的绝对子 canvas 得到 padding box,补回槽位的 1px 边框。
                    measured.borrow_mut()[index] = Some(bounds.extend(Edges::all(px(1.0))));
                })
                .relative()
                .overflow_hidden()
                .track_focus(&input.read(cx).focus_handle(cx))
                .min_w(px(0.0))
                .w(BlockTokens::OTP_WIDTH)
                .h(BlockTokens::OTP_HEIGHT)
                .flex_shrink(1.0)
                .flex_grow(0.0)
                .flex_basis(BlockTokens::OTP_WIDTH)
                .rounded(Radii::CONTROL)
                .border_1()
                .border_color(if invalid {
                    colors.danger
                } else if filled {
                    colors.accent
                } else {
                    colors.border
                })
                .bg(if invalid {
                    oklab_mix(colors.danger, colors.surface, 0.07)
                } else if filled {
                    colors.accent_subtle
                } else {
                    colors.surface
                })
                .hover(move |s| {
                    if !disabled && !filled && !invalid {
                        s.border_color(colors.border_strong)
                            .bg(colors.surface_muted)
                    } else {
                        s
                    }
                })
                .text_size(Typography::TEXT_LG)
                .when(disabled, |d| d.opacity(0.48).bg(colors.surface_muted))
                .on_mouse_down(gpui_kit::MouseButton::Left, move |_, w, cx| {
                    if !disabled {
                        click_input.update(cx, |i, cx| {
                            i.focus(w, cx);
                            i.select_all(w, cx);
                        });
                    }
                })
                // 原生输入先解析键绑定;捕获 action,避免退格继续删除相邻槽的字符。
                .capture_action(move |_: &MoveLeft, w, cx| {
                    if !disabled {
                        left_state.update(cx, |s, cx| s.navigate(index, -1, w, cx));
                    }
                    cx.stop_propagation();
                })
                .capture_action(move |_: &MoveRight, w, cx| {
                    if !disabled {
                        right_state.update(cx, |s, cx| s.navigate(index, 1, w, cx));
                    }
                    cx.stop_propagation();
                })
                .capture_action(move |_: &Backspace, w, cx| {
                    if !disabled {
                        backspace_state.update(cx, |s, cx| s.backspace(index, w, cx));
                    }
                    cx.stop_propagation();
                })
                // Delete 只清当前槽;先于内层输入捕获,避免原生删除二次消费。
                .capture_key_down(move |event: &KeyDownEvent, w, cx| {
                    if !disabled && event.keystroke.key == "delete" {
                        delete_state.update(cx, |s, cx| s.delete_forward(index, w, cx));
                        cx.stop_propagation();
                    }
                })
                .child(
                    KitInput::new(input)
                        .appearance(false)
                        .text_color(gpui_kit::Hsla::transparent_black())
                        .text_align(TextAlign::Center)
                        .text_size(Typography::TEXT_LG)
                        .p(px(0.0))
                        .min_w(px(0.0))
                        .id(child_id(&self.id, format!("input-{index}")))
                        .aria_label(format!(
                            "{}, digit {} of {}",
                            self.label,
                            index + 1,
                            self.length
                        ))
                        .disabled(disabled)
                        .size_full(),
                );
            // 原生文本透明,独立字形层只绘制数字,不再用不透明矩形遮住槽位描边。
            if !input.read(cx).value().is_empty() {
                let ch = input.read(cx).value().to_string();
                let rise = arc_spring_with_options(
                    (
                        child_id(&self.id, format!("glyph-{index}")),
                        SharedString::from(ch.clone()),
                    ),
                    0.0,
                    SpringOptions::new(motion.spring.snappy).with_initial_value(4.0),
                    w,
                    cx,
                );
                if !rise.settled {
                    w.request_animation_frame();
                }
                let opacity = (1.0 - rise.value / 4.0).clamp(0.0, 1.0);
                let click = input.clone();
                slot = slot.child(
                    div()
                        .id(child_id(&self.id, format!("glyph-{index}")))
                        .absolute()
                        .inset_0()
                        .flex()
                        .items_center()
                        .justify_center()
                        .text_color(colors.foreground)
                        .mt(px(rise.value))
                        .opacity(opacity)
                        .on_mouse_down(gpui_kit::MouseButton::Left, move |_, w, cx| {
                            if !disabled {
                                click.update(cx, |i, cx| {
                                    i.focus(w, cx);
                                    i.select_all(w, cx);
                                });
                            }
                        })
                        .child(ch),
                );
            }
            row = row.child(slot);
        }
        // 所有槽 prepaint 后,按当帧实测边界绘制唯一焦点环;绝不按容器宽度均分。
        let focused = if self.disabled {
            None
        } else {
            inputs
                .iter()
                .position(|i| i.read(cx).focus_handle(cx).is_focused(w))
        };
        let ring_op = arc_spring(
            (child_id(&self.id, "ring-show"), "opacity"),
            if focused.is_some() { 1.0 } else { 0.0 },
            motion.spring.snappy,
            w,
            cx,
        )
        .clamp(0.0, 1.0);
        let geometry = state.read(cx).ring_geometry.clone();
        let ring_id = child_id(&self.id, "ring-x");
        row = row.child(
            canvas(
                |_, _, _| {},
                move |rect, _, window, cx| {
                    let mut geometry = geometry.borrow_mut();
                    let resized = geometry.row_size != Some(rect.size);
                    let entering = geometry.focused.is_none();
                    let target = focused
                        .and_then(|index| measured_slots.borrow()[index])
                        .map(|slot| bounds(slot.origin - rect.origin, slot.size));
                    // 外部进入或收缩布局直接对齐;只有组内换焦点才滑行。
                    if let Some(target) = target {
                        geometry.target = Some(target);
                    }
                    let Some(target) = geometry.target else {
                        return;
                    };
                    let x = arc_spring_with_options(
                        (ring_id.clone(), "x"),
                        f32::from(target.origin.x),
                        SpringOptions::new(motion.spring.snappy).with_travel(!entering && !resized),
                        window,
                        cx,
                    )
                    .value;
                    geometry.focused = focused;
                    geometry.row_size = Some(rect.size);
                    if ring_op <= 0.01 {
                        return;
                    }
                    let mut color = if invalid {
                        colors.danger
                    } else {
                        colors.accent_strong
                    };
                    color.a *= ring_op;
                    window.paint_quad(quad(
                        bounds(rect.origin + point(px(x), target.origin.y), target.size),
                        Corners::all(Radii::CONTROL),
                        gpui_kit::Hsla::transparent_black(),
                        Edges::all(px(1.0)),
                        color,
                        BorderStyle::Solid,
                    ));
                },
            )
            .absolute()
            .inset_0(),
        );
        div()
            .id(self.id.clone())
            .w_full()
            .flex()
            .flex_col()
            .gap(Spacing::S2)
            .text_color(colors.foreground)
            .child(self.label)
            .child(row)
            .child(render_field_message(
                child_id(&self.id, "description"),
                self.description,
                false,
                w,
                cx,
            ))
            .child(render_field_message(
                child_id(&self.id, "error"),
                self.error,
                true,
                w,
                cx,
            ))
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn sanitize_is_unicode_safe() {
        assert_eq!(
            sanitize_otp("a1中23-4567", OtpInputMode::Numeric, 6),
            "123456"
        );
        assert_eq!(sanitize_otp("你好a", OtpInputMode::Text, 2), "你好");
    }
}