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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//! React Bits `SpringCheck` 的 GPUI 原生移植。
//!
//! 源组件:https://reactbits.dev 文本勾选行:方框 + 标签文字,勾选时填充
//! 从中心「膨胀」弹出(可过冲回弹)、对勾按 `pathLength` 描边画出、文字
//! 透明度降到 `done_opacity`、划线按 `strike_lag → 0.84` 区间擦入。
//!
//! 与 Web 版差异:
//! - 弹簧 `visualDuration: 0.2s` + `bounce` 映射为 `SpringSpec::visual(0.2,
//!   1 - zetaOf(bounce))`(本库 bounce 语义与 Motion 一致:bounce = 1 - ζ)。
//! - tick 描边消除由 canvas 采样弹簧进度逐帧裁剪折线长度,替代
//!   stroke-dashoffset。
//! - 划线 `transform-origin` 无对应 API:直接按 origin 决定线段起点,
//!   canvas 全宽绘制。

use std::rc::Rc;

use arc_motion::{arc_spring, is_reduced_motion};
use arc_tokens::{ActiveArcTheme as _, SpringSpec};
use gpui_kit::{
    App, ElementId, Hsla, IntoElement, MouseButton, ParentElement, RenderOnce, Role, SharedString,
    Styled, TestSupportExt as _, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
    relative,
};
// TestSupportExt 由主代码的 .test_support() 调用引入。

/// 划线擦入终点(占勾选弹簧进度比例,源码 `RULE_END`)。
pub const RULE_END: f32 = 0.84;
/// 划线静置垂直位置(行内容高度的 46%,源码 46%)。
const RULE_TOP_RATIO: f32 = 0.46;
/// 勾选完成后 box 反向膨胀比例(源码 `SWELL`)。
const BOX_SWELL: f32 = 0.35;
/// 对勾 SVG 视口边长(源码 24×24 viewBox)。
const TICK_VIEW: f32 = 24.0;
/// 对勾描边宽(viewBox 单位,源码 stroke-width: 2.6)。
const TICK_STROKE: f32 = 2.6;
/// 对勾路径关键点(Tick02Icon 折线近似,viewBox 24)。
const TICK_P0: (f32, f32) = (5.0, 12.5);
const TICK_P1: (f32, f32) = (10.0, 17.5);
const TICK_P2: (f32, f32) = (19.0, 6.5);

/// 划线擦入方向。
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StrikeOrigin {
    /// 从左侧擦入(默认)。
    #[default]
    Left,
    /// 从中心向两侧展开。
    Center,
    /// 从右侧擦入。
    Right,
    /// 不绘制划线。
    None,
}

impl StrikeOrigin {
    /// 从 CSS `transform-origin` 字符串解析。
    pub fn parse(value: &str) -> Self {
        match value {
            "center" => Self::Center,
            "right" => Self::Right,
            "none" => Self::None,
            _ => Self::Left,
        }
    }
}

/// `bounce`(React 语义 0..0.5,0 无过冲)→ 弹簧阻尼比 ζ。
/// 源码 `zetaOf`:`ζ = -ln(bounce) / √(π² + ln²(bounce))`。
fn zeta_of(bounce: f32) -> f32 {
    if bounce <= 0.0 {
        return 1.0;
    }
    let l = f64::from(bounce).ln();
    (-l / (std::f64::consts::PI.powi(2) + l * l).sqrt()) as f32
}

/// 组件完整配置。
#[derive(Clone, Debug)]
pub struct SpringCheckConfig {
    /// 标签墨色(划线同色);alpha=0 使用主题前景色。
    pub color: Hsla,
    /// 填充色(从中心膨胀)。
    pub fill_color: Hsla,
    /// 对勾描边色(画在填充之上)。
    pub check_color: Hsla,
    /// 方框边长 px。
    pub box_size: f32,
    /// 方框圆角 px(一半边长即圆形)。
    pub box_radius: f32,
    /// 标签字号 px。
    pub font_size: f32,
    /// 膨胀过冲量(0 直达,0.5 回弹两次;React bounce 语义)。
    pub bounce: f32,
    /// 划线起始点(0 与填充同步,0.4 等对勾)。
    pub strike_lag: f32,
    /// 勾选完成后文字保留的透明度。
    pub done_opacity: f32,
    /// 划线方向。
    pub strike: StrikeOrigin,
    /// 禁用:整行降透明度并忽略输入。
    pub disabled: bool,
}

impl Default for SpringCheckConfig {
    fn default() -> Self {
        Self {
            color: Hsla::default(),
            fill_color: Hsla::default(),
            check_color: Hsla::default(),
            box_size: 28.0,
            box_radius: 9.0,
            font_size: 18.0,
            bounce: 0.2,
            strike_lag: 0.12,
            done_opacity: 0.42,
            strike: StrikeOrigin::Left,
            disabled: false,
        }
    }
}

impl SpringCheckConfig {
    fn resolve_theme(mut self, colors: arc_tokens::ArcColors) -> Self {
        if self.color.a == 0.0 {
            self.color = colors.foreground;
        }
        if self.fill_color.a == 0.0 {
            self.fill_color = colors.accent;
        }
        if self.check_color.a == 0.0 {
            self.check_color = colors.accent_foreground;
        }
        self
    }

    /// 钳制非法输入。
    pub fn normalized(mut self) -> Self {
        self.box_size = self.box_size.clamp(14.0, 80.0).max(1.0);
        self.box_radius = self.box_radius.clamp(0.0, self.box_size / 2.0);
        self.font_size = self.font_size.clamp(10.0, 40.0);
        self.bounce = self.bounce.clamp(0.0, 0.5);
        self.strike_lag = self.strike_lag.clamp(0.0, 0.6);
        self.done_opacity = self.done_opacity.clamp(0.0, 1.0);
        self
    }
}

/// 内部帧间状态。
#[derive(Clone, Copy)]
struct SpringCheckInternal {
    uncontrolled: bool,
    hovered: bool,
    pressed: bool,
}

/// `onChange` 载荷:`(checked)`。
pub type SpringCheckChange = bool;
type ChangeHandler = Rc<dyn Fn(&SpringCheckChange, &mut Window, &mut App)>;

/// React Bits `SpringCheck`:弹簧勾选行。
///
/// - 非受控:内部状态 + `on_change` 回调;
/// - 受控:传入 `checked`,外部状态变化同样走弹簧动画。
#[derive(IntoElement)]
pub struct SpringCheck {
    /// 元素 id(键控通道由此派生)。
    id: ElementId,
    /// 标签文字。
    label: SharedString,
    /// 无障碍名称(覆盖 label)。
    aria_label: Option<SharedString>,
    /// 受控勾选态。
    checked: Option<bool>,
    /// 非受控初始态。
    default_checked: bool,
    /// 配置。
    config: SpringCheckConfig,
    /// 切换回调。
    on_change: Option<ChangeHandler>,
}

impl SpringCheck {
    /// 创建勾选行。
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            label: "Ship the build".into(),
            aria_label: None,
            checked: None,
            default_checked: false,
            config: SpringCheckConfig::default(),
            on_change: None,
        }
    }

    /// 设置标签。
    pub fn label(mut self, v: impl Into<SharedString>) -> Self {
        self.label = v.into();
        self
    }

    /// 设置无障碍名称。
    pub fn aria_label(mut self, v: impl Into<SharedString>) -> Self {
        self.aria_label = Some(v.into());
        self
    }

    /// 受控勾选态。
    pub fn checked(mut self, v: bool) -> Self {
        self.checked = Some(v);
        self
    }

    /// 非受控初始态。
    pub fn default_checked(mut self, v: bool) -> Self {
        self.default_checked = v;
        self
    }

    /// 覆盖配置。
    pub fn config(mut self, v: SpringCheckConfig) -> Self {
        self.config = v;
        self
    }

    /// 切换回调。
    pub fn on_change(mut self, f: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
        self.on_change = Some(Rc::new(f));
        self
    }
}

/// 划线水平缩放:由勾选弹簧进度 `t` 推导。
/// `t < strike_lag` 为 0;`t = RULE_END` 到 1,此后保持。
fn rule_scale(t: f32, strike_lag: f32) -> f32 {
    if strike_lag >= RULE_END {
        return 0.0;
    }
    ((t - strike_lag) / (RULE_END - strike_lag)).clamp(0.0, 1.0)
}

/// 对勾折线总长(viewBox 单位)。
fn tick_total_len() -> f32 {
    let seg1 = ((TICK_P1.0 - TICK_P0.0).powi(2) + (TICK_P1.1 - TICK_P0.1).powi(2)).sqrt();
    let seg2 = ((TICK_P2.0 - TICK_P1.0).powi(2) + (TICK_P2.1 - TICK_P1.1).powi(2)).sqrt();
    seg1 + seg2
}

/// 按 `drawn` 长度(0..total)裁剪折线并返回绘制点。
fn tick_points_to(drawn: f32) -> Vec<(f32, f32)> {
    let seg1 = ((TICK_P1.0 - TICK_P0.0).powi(2) + (TICK_P1.1 - TICK_P0.1).powi(2)).sqrt();
    let seg2 = ((TICK_P2.0 - TICK_P1.0).powi(2) + (TICK_P2.1 - TICK_P1.1).powi(2)).sqrt();
    let mut pts = vec![TICK_P0];
    if drawn >= seg1 {
        pts.push(TICK_P1);
        if drawn >= seg1 + seg2 {
            pts.push(TICK_P2);
        } else {
            let f = (drawn - seg1) / seg2;
            pts.push((
                TICK_P1.0 + (TICK_P2.0 - TICK_P1.0) * f,
                TICK_P1.1 + (TICK_P2.1 - TICK_P1.1) * f,
            ));
        }
    } else {
        let f = drawn / seg1;
        pts.push((
            TICK_P0.0 + (TICK_P1.0 - TICK_P0.0) * f,
            TICK_P0.1 + (TICK_P1.1 - TICK_P0.1) * f,
        ));
    }
    pts
}

/// 划线段起止(比例坐标 0..1),按 origin 裁剪。
fn rule_segment(scale: f32, origin: StrikeOrigin) -> Option<(f32, f32)> {
    match origin {
        StrikeOrigin::None => None,
        StrikeOrigin::Left => Some((0.0, scale)),
        StrikeOrigin::Center => {
            let half = scale / 2.0;
            Some((0.5 - half, 0.5 + half))
        }
        StrikeOrigin::Right => Some((1.0 - scale, 1.0)),
    }
}

/// 填充 + 对勾 canvas 绘制入口。
#[derive(Clone, Copy)]
struct FillCanvas {
    ox: f32,
    oy: f32,
    scale: f32,
}

impl RenderOnce for SpringCheck {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let reduced = is_reduced_motion(cx);
        let cfg = self
            .config
            .normalized()
            .resolve_theme(cx.arc_theme().colors);

        let state_id = ElementId::NamedChild(self.id.clone().into(), "__spring-check-state".into());
        let internal = window.use_keyed_state(state_id, cx, |_, _| SpringCheckInternal {
            uncontrolled: self.default_checked,
            hovered: false,
            pressed: false,
        });
        let snap = *internal.read(cx);

        let is_controlled = self.checked.is_some();
        let is_on = self.checked.unwrap_or(snap.uncontrolled);

        // —— 弹簧通道:勾选进度 0..1 —— //
        let spec = SpringSpec::visual(0.2, 1.0 - zeta_of(cfg.bounce));
        let t = if reduced {
            if is_on { 1.0 } else { 0.0 }
        } else {
            arc_spring(
                (self.id.clone(), "check-t"),
                if is_on { 1.0 } else { 0.0 },
                spec,
                window,
                cx,
            )
        };
        let press_scale = if reduced {
            1.0
        } else {
            arc_spring(
                (self.id.clone(), "press-scale"),
                if !cfg.disabled && snap.pressed {
                    0.95
                } else {
                    1.0
                },
                SpringSpec::visual(0.16, 0.0),
                window,
                cx,
            )
        };

        // —— 派生读数(源码 readings) —— //
        let fill_scale = t.max(0.0);
        let tick_alpha = t.clamp(0.0, 1.0);
        let word_opacity = 1.0 - (1.0 - cfg.done_opacity) * t.clamp(0.0, 1.0);
        let rule = if cfg.strike == StrikeOrigin::None {
            0.0
        } else {
            rule_scale(t, cfg.strike_lag)
        };
        let box_growth = BOX_SWELL * (t - 1.0).max(0.0); // 过冲期外扩
        let ring_opacity = if !cfg.disabled && snap.hovered {
            0.5
        } else {
            0.28
        };

        // —— 几何 —— //
        let ring_w = if cfg.box_size >= 24.0 { 2.0 } else { 1.5 };
        let gap = (cfg.box_size * 0.43).round().clamp(8.0, 16.0);
        let rule_h = ((cfg.font_size / 6.0).round() / 2.0).max(1.5);
        let row_h = (cfg.box_size + 16.0).max(44.0);
        let box_px = px(cfg.box_size);
        let box_size_now = px(cfg.box_size * (1.0 + box_growth));

        // —— 填充 canvas(含圆角矩形 + 对勾描边) —— //
        let fill_id = ElementId::NamedChild(self.id.clone().into(), "fill-canvas".into());
        let fill_color = cfg.fill_color;
        let check_color = cfg.check_color;
        let radius = cfg.box_radius;
        let total_len = tick_total_len();
        let drawn_len = total_len * tick_alpha;
        let fill_canvas = div().id(fill_id).size(box_size_now).flex_none().child(
            canvas(
                move |_, _, _| {},
                move |rect, _, window, _| {
                    let ox = f32::from(rect.origin.x);
                    let oy = f32::from(rect.origin.y);
                    let s = f32::from(rect.size.width).min(f32::from(rect.size.height));
                    if s <= 0.0 {
                        return;
                    }
                    let cv = FillCanvas { ox, oy, scale: s };
                    cv.fill_round_rect(fill_scale, radius, fill_color, window);
                    if drawn_len > 0.5 {
                        let pts = tick_points_to(drawn_len);
                        let k = s / TICK_VIEW;
                        cv.stroke_polyline(TICK_STROKE * k, &pts, false, check_color, window);
                    }
                },
            )
            .size_full(),
        );

        // —— 方框外壳(ring 用 border 模拟) —— //
        let ring_color = Hsla {
            a: cfg.color.a * ring_opacity * (ring_w / 2.0),
            ..cfg.color
        };
        let box_outer = div()
            .relative()
            .size(box_size_now)
            .rounded(px(radius))
            .border_1()
            .border_color(ring_color)
            .overflow_hidden()
            .flex()
            .items_center()
            .justify_center()
            .child(fill_canvas);

        // —— 标签 + 划线 —— //
        let label_color = Hsla {
            a: cfg.color.a * word_opacity,
            ..cfg.color
        };
        let rule_color = Hsla {
            a: cfg.color.a,
            ..cfg.color
        };
        let rule_seg = rule_segment(rule, cfg.strike);
        let label_block = div()
            .relative()
            .text_size(px(cfg.font_size))
            .font_medium()
            .whitespace_nowrap()
            .text_color(label_color)
            .child(self.label.clone())
            .when_some(rule_seg, |el, (x0, x1)| {
                // 划线按百分比宽度 + margin 模拟 transform-origin。
                el.child(
                    div()
                        .absolute()
                        .top(relative(RULE_TOP_RATIO))
                        .h(px(rule_h))
                        .rounded(px(2.0))
                        .bg(rule_color)
                        .left(relative(x0))
                        .w(relative(x1 - x0)),
                )
            });

        // —— 交互 —— //
        let on_change = self.on_change.clone();
        let state_hover = internal.clone();
        let state_down = internal.clone();
        let state_up = internal.clone();
        let state_out = internal.clone();
        let row = div()
            .id(self.id.clone())
            .test_support()
            .role(Role::CheckBox)
            .aria_toggled(if is_on {
                gpui_kit::Toggled::True
            } else {
                gpui_kit::Toggled::False
            })
            .aria_label(
                self.aria_label
                    .clone()
                    .unwrap_or_else(|| self.label.clone()),
            )
            .flex()
            .items_center()
            .gap(px(gap))
            .h(px(row_h))
            .cursor_pointer()
            .when(cfg.disabled, |el| el.opacity(0.5).cursor_default())
            .when(!cfg.disabled, |el| {
                el.on_hover({
                    move |h: &bool, window, cx| {
                        state_hover.update(cx, |s, _| {
                            s.hovered = *h;
                            if !*h {
                                s.pressed = false;
                            }
                        });
                        window.refresh();
                    }
                })
                .on_mouse_down(MouseButton::Left, {
                    move |_, window, cx| {
                        state_down.update(cx, |s, _| s.pressed = true);
                        window.refresh();
                    }
                })
                .on_mouse_up(MouseButton::Left, {
                    move |_, window, cx| {
                        state_up.update(cx, |s, _| s.pressed = false);
                        let next = !self.checked.unwrap_or(state_up.read(cx).uncontrolled);
                        if !is_controlled {
                            state_up.update(cx, |s, _| s.uncontrolled = next);
                        }
                        if let Some(cb) = &on_change {
                            cb(&next, window, cx);
                        }
                        window.refresh();
                    }
                })
                .on_mouse_up_out(MouseButton::Left, {
                    move |_, window, cx| {
                        state_out.update(cx, |s, _| s.pressed = false);
                        window.refresh();
                    }
                })
            })
            .child(div().flex_none().size(box_px).child(box_outer))
            .child(label_block);

        // press 缩放:内边距近似(0.95 缩放 → 2.5% 边距)。
        let press_inset = (1.0 - press_scale) * 0.5 * f32::from(box_px);
        let row = row.p(px(press_inset));

        let _ = FillCanvas {
            ox: 0.0,
            oy: 0.0,
            scale: 0.0,
        };
        row
    }
}

impl FillCanvas {
    fn fill_round_rect(self, grow: f32, radius: f32, color: Hsla, window: &mut Window) {
        if color.a <= 0.005 || grow <= 0.001 {
            return;
        }
        let side = self.scale * grow;
        let x = self.ox + (self.scale - side) / 2.0;
        let y = self.oy + (self.scale - side) / 2.0;
        let quad = gpui_kit::quad(
            gpui_kit::Bounds {
                origin: point(px(x), px(y)),
                size: gpui_kit::Size {
                    width: px(side),
                    height: px(side),
                },
            },
            px(radius * grow.min(1.0)),
            color,
            gpui_kit::Edges::default(),
            gpui_kit::black(),
            gpui_kit::BorderStyle::Solid,
        );
        window.paint_quad(quad);
    }

    fn stroke_polyline(
        self,
        sw: f32,
        pts: &[(f32, f32)],
        closed: bool,
        color: Hsla,
        window: &mut Window,
    ) {
        if color.a <= 0.005 || pts.len() < 2 {
            return;
        }
        let mut b = gpui_kit::PathBuilder::stroke(px(sw));
        for (i, (x, y)) in pts.iter().enumerate() {
            let p = point(px(self.ox + x * self.scale), px(self.oy + y * self.scale));
            if i == 0 {
                b.move_to(p);
            } else {
                b.line_to(p);
            }
        }
        if closed {
            b.close();
        }
        if let Ok(path) = b.build() {
            window.paint_path(path, color);
        }
    }
}

#[cfg(test)]
mod tests {
    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
    use gpui_kit::test::{TestEventExt as _, TestWindowExt as _};
    use gpui_kit::{Context, Render, Role, TestAppContext, div};

    use super::*;

    #[gpui_kit::test]
    fn spring_check_theme_defaults_and_explicit_colors(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            for mode in [ThemeMode::Light, ThemeMode::Dark, ThemeMode::Light] {
                install_arc_theme(mode, Accent::Neutral, cx);
                let colors = cx.arc_theme().colors;
                let cfg = SpringCheckConfig::default().resolve_theme(colors);
                assert_eq!(cfg.color, colors.foreground);
                assert_eq!(cfg.fill_color, colors.accent);
                assert_eq!(cfg.check_color, colors.accent_foreground);
                let custom = SpringCheckConfig {
                    color: colors.danger,
                    ..Default::default()
                }
                .resolve_theme(colors);
                assert_eq!(custom.color, colors.danger);
            }
        });
    }

    struct Host {
        events: Rc<std::cell::RefCell<Vec<bool>>>,
        checked: Option<bool>,
        default_checked: bool,
    }

    impl Render for Host {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            let events = self.events.clone();
            let check = SpringCheck::new("sc-test")
                .label("Ship the build")
                .default_checked(self.default_checked)
                .on_change(move |v, _, _| events.borrow_mut().push(*v));
            let check = if let Some(c) = self.checked {
                check.checked(c)
            } else {
                check
            };
            div().size_full().child(check)
        }
    }

    fn setup(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            install_arc_theme(ThemeMode::Light, Accent::Neutral, cx);
        });
    }

    #[gpui_kit::test]
    fn spring_check_rule_scale_matches_source() {
        // strike_lag=0.12 → RULE_END=0.84 线性区间。
        assert!((rule_scale(0.12, 0.12)).abs() < 1e-4);
        assert!((rule_scale(0.84, 0.12) - 1.0).abs() < 1e-4);
        assert!((rule_scale(0.48, 0.12) - 0.5).abs() < 1e-4);
        assert!((rule_scale(0.06, 0.12)).abs() < 1e-4);
        assert!((rule_scale(1.0, 0.12) - 1.0).abs() < 1e-4);
        // strike_lag 越过 RULE_END 永不出线。
        assert!((rule_scale(1.0, 0.9)).abs() < 1e-4);
    }

    #[gpui_kit::test]
    fn spring_check_zeta_matches_source() {
        assert!((zeta_of(0.0) - 1.0).abs() < 1e-4);
        // bounce=1 → ζ=0(完全无阻尼)。
        assert!(zeta_of(1.0).abs() < 1e-4);
        assert!(zeta_of(0.2) > 0.0 && zeta_of(0.2) < 1.0);
    }

    #[gpui_kit::test]
    fn spring_check_tick_clip_and_rule_segment() {
        let total = tick_total_len();
        assert!(total > 10.0);
        // 画一半:已越过短段(seg1≈7.07 < total/2≈10.6),处于长段中 → 三点。
        let half = tick_points_to(total * 0.5);
        assert_eq!(half.len(), 3);
        // 画完:三点。
        assert_eq!(tick_points_to(total).len(), 3);
        // 0 长度:退化为起点重复两点。
        assert_eq!(tick_points_to(0.0).len(), 2);
        // 越界裁剪:超长不外溢。
        assert_eq!(tick_points_to(total * 2.0).len(), 3);
        // origin 各向。
        assert_eq!(rule_segment(1.0, StrikeOrigin::Left), Some((0.0, 1.0)));
        assert_eq!(rule_segment(0.5, StrikeOrigin::Center), Some((0.25, 0.75)));
        assert_eq!(rule_segment(0.5, StrikeOrigin::Right), Some((0.5, 1.0)));
        assert_eq!(rule_segment(1.0, StrikeOrigin::None), None);
    }

    #[gpui_kit::test]
    fn spring_check_click_toggles_and_reports(cx: &mut TestAppContext) {
        setup(cx);
        let events = Rc::new(std::cell::RefCell::new(Vec::new()));
        let (_view, cx) = cx.add_window_view(|_, _| Host {
            events: events.clone(),
            checked: None,
            default_checked: false,
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            let b = window.find("sc-test").bounds();
            let pos = b.center();
            window.pointer_down(pos, MouseButton::Left, cx);
            window.pointer_up(pos, MouseButton::Left, cx);
            window.render_frame(cx);
            assert_eq!(events.borrow().clone(), vec![true]);
        });
    }

    #[gpui_kit::test]
    fn spring_check_row_has_checkbox_role(cx: &mut TestAppContext) {
        setup(cx);
        let (_view, cx) = cx.add_window_view(|_, _| Host {
            events: Rc::new(std::cell::RefCell::new(Vec::new())),
            checked: None,
            default_checked: false,
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            assert_eq!(window.find("sc-test").role(), Some(Role::CheckBox));
        });
    }
}