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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
//! 原生移植 React Bits LatticeLoader,© David Haz,MIT + Commons Clause。
//! AI 任务状态行:点阵波浪 + 状态词 + 秒表;working 时波浪运行,done/error
//! 时波浪淡出、对勾/叉溶解进入,秒表停在与状态切换同帧的时刻。
//! 所有相位采样来自共享 MotionClock(支持 0.25x 慢放与减弱动画),
//! 每个 cell 的时间轴按源码 `@keyframes lattice-on{,-45,-35,-25}` 逐段还原。

use arc_motion::{CubicBezier, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, CubicBezierSpec, hex};
use gpui_kit::{
    App, Bounds, Corners, Edges, ElementId, Hsla, IntoElement, ParentElement, Pixels, RenderOnce,
    Role, SharedString, Styled, TestSupportExt as _, Window, base::StyledExt as _, canvas, div,
    point, prelude::*, px, quad, size,
};
use std::cell::RefCell;
use std::rc::Rc;

/// 与源码一致的运行层缓动(in-out)与标记层缓动(out)。
const EASE_IN_OUT: CubicBezierSpec = CubicBezierSpec::new(0.77, 0.0, 0.175, 1.0);
const EASE_OUT: CubicBezierSpec = CubicBezierSpec::new(0.23, 1.0, 0.32, 1.0);
const EASE_IN_OUT_SOLVER: CubicBezier = CubicBezier::from_spec(EASE_IN_OUT);
const EASE_OUT_SOLVER: CubicBezier = CubicBezier::from_spec(EASE_OUT);

/// Cell 亮度保持的时间占比(源码 lit:0.62 默认 / 0.45 / 0.35 / 0.25)。
/// 关键帧以周期百分比表达并随 lit 等比压缩:
/// lit=0.62 → 0% idle、18% 起亮、42% 峰值结束、62% 回落;
/// 0.45/0.35/0.25 → 13%/31%/45%、10%/24%/35%、7%/17%/25%(与源码四个 @keyframes 一致)。
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LatticeLit(pub f32);
impl LatticeLit {
    pub const DEFAULT: LatticeLit = LatticeLit(0.62);
    /// `(rise_start, peak_end, settle)` 占周期比例。源码四个 @keyframes 的关键帧:
    /// 0.62 → 18%/42%/62%、0.45 → 13%/31%/45%、0.35 → 10%/24%/35%、0.25 → 7%/17%/25%;
    /// 其它 lit 按内部比例(18/62、42/62)缩放。
    pub fn fractions(self) -> (f32, f32, f32) {
        let lit = self.0.clamp(0.05, 1.0);
        let (r, p) = match lit {
            v if (v - 0.62).abs() < 0.005 => (18.0, 42.0),
            v if (v - 0.45).abs() < 0.005 => (13.0, 31.0),
            v if (v - 0.35).abs() < 0.005 => (10.0, 24.0),
            v if (v - 0.25).abs() < 0.005 => (7.0, 17.0),
            // 自定义 lit:按 0.62 基准的内部比例缩放(百分比)
            v => (v * 18.0 / 0.62, v * 42.0 / 0.62),
        };
        (r / 100.0, p / 100.0, lit)
    }
}

/// 命名波浪几何;`grid=3`/`grid=4` 各有自己的形状、hole 与 lit 占比。
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LatticePattern {
    Arrow,
    Dots,
    Ripple,
    Spiral,
    Orbit,
    Snake,
    Sweep,
    Spin,
    Rain,
    Pulse,
}

impl LatticePattern {
    /// 该模式在指定格宽下的数据:(每 cell 的 delay 单位,可选 hole,loop 步数,scale,lit)。
    fn resolve(self, grid: usize) -> ResolvedPattern {
        let n = grid * grid;
        let (raw, loop_steps, scale, lit) = match (self, grid) {
            (Self::Arrow, 3) => (
                &[1, 2, 3, 0, 1, 2, 1, 2, 3][..],
                7.2,
                1.0,
                LatticeLit::DEFAULT,
            ),
            (Self::Dots, 3) => (
                &[0, 1, 2, 0, 1, 2, 0, 1, 2][..],
                3.0,
                2.4,
                LatticeLit::DEFAULT,
            ),
            (Self::Ripple, 3) => (
                &[2, 1, 2, 1, 0, 1, 2, 1, 2][..],
                4.8,
                1.5,
                LatticeLit::DEFAULT,
            ),
            (Self::Spiral, 3) => (&[0, 1, 2, 7, 8, 3, 6, 5, 4][..], 9.0, 1.2, LatticeLit(0.35)),
            (Self::Orbit, 3) => (
                &[0, 1, 2, 7, USIZE_HOLE, 3, 6, 5, 4][..],
                8.0,
                1.2,
                LatticeLit::DEFAULT,
            ),
            (Self::Orbit, _) => (
                &[
                    0, 1, 2, 3, 11, USIZE_HOLE, USIZE_HOLE, 4, 10, USIZE_HOLE, USIZE_HOLE, 5, 9, 8,
                    7, 6,
                ][..],
                6.0,
                1.2,
                LatticeLit(0.45),
            ),
            (Self::Snake, 3) => (&[0, 1, 2, 5, 4, 3, 6, 7, 8][..], 9.0, 1.0, LatticeLit(0.35)),
            (Self::Snake, _) => (
                &[0, 1, 2, 3, 7, 6, 5, 4, 8, 9, 10, 11, 15, 14, 13, 12][..],
                16.0,
                1.0,
                LatticeLit(0.25),
            ),
            (Self::Sweep, 4) => (
                &[0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5, 3, 4, 5, 6][..],
                5.0,
                1.0,
                LatticeLit(0.45),
            ),
            (Self::Spin, 4) => (
                &[0, 0, 1, 1, 0, 0, 1, 1, 3, 3, 2, 2, 3, 3, 2, 2][..],
                4.0,
                1.6,
                LatticeLit(0.35),
            ),
            (Self::Rain, 4) => (
                &[0, 2, 1, 3, 1, 3, 2, 4, 2, 4, 3, 5, 3, 5, 4, 6][..],
                4.0,
                1.2,
                LatticeLit(0.35),
            ),
            (Self::Pulse, 4) => (
                &[2, 1, 1, 2, 1, 0, 0, 1, 1, 0, 0, 1, 2, 1, 1, 2][..],
                2.4,
                2.5,
                LatticeLit(0.45),
            ),
            // 源码 DEFAULT_PATTERN:4×4 专属模式用于 3×3 时回落到 orbit@3。
            (_, _) => (
                &[0, 1, 2, 7, USIZE_HOLE, 3, 6, 5, 4][..],
                8.0,
                1.2,
                LatticeLit::DEFAULT,
            ),
        };
        let mut cells = Vec::with_capacity(n);
        for i in 0..n {
            let v = raw.get(i).copied().unwrap_or(USIZE_HOLE);
            cells.push(if v == USIZE_HOLE {
                None
            } else {
                Some(v as f32)
            });
        }
        ResolvedPattern {
            cells,
            loop_steps,
            scale,
            lit,
        }
    }
}

/// hole 哨兵(真实 delay 单位不会用到 usize::MAX)。
const USIZE_HOLE: usize = usize::MAX;

/// 解析后的波浪:每 cell 一个 delay(`None` 是洞)、循环步数与 lit 占比。
pub struct ResolvedPattern {
    pub cells: Vec<Option<f32>>,
    pub loop_steps: f32,
    pub scale: f32,
    pub lit: LatticeLit,
}

/// 自定义波浪:每 cell 的 delay 单位(`None` 为洞),可选 loop/scale/lit 覆盖。
#[derive(Clone, Debug, PartialEq)]
pub struct LatticeCells {
    pub cells: Vec<Option<f32>>,
    pub loop_steps: Option<f32>,
    pub scale: Option<f32>,
    pub lit: Option<LatticeLit>,
}

impl LatticeCells {
    /// 按源码:缺省 loop = 最大 delay + 4.2、scale = 1、lit = 0.62;越界 cell 视为洞。
    pub fn resolve(self, grid: usize) -> ResolvedPattern {
        let n = grid * grid;
        let cells: Vec<Option<f32>> = (0..n)
            .map(|i| self.cells.get(i).copied().unwrap_or(None))
            .collect();
        let max = cells.iter().flatten().fold(0.0f32, |a, v| a.max(*v));
        ResolvedPattern {
            cells,
            loop_steps: self.loop_steps.unwrap_or(max + 4.2),
            scale: self.scale.unwrap_or(1.0),
            lit: self.lit.unwrap_or(LatticeLit::DEFAULT),
        }
    }
}

/// 波浪几何来源。
#[derive(Clone, Debug, PartialEq)]
pub enum LatticeWave {
    Named(LatticePattern),
    Custom(LatticeCells),
}

impl LatticeWave {
    fn resolve(self, grid: usize) -> ResolvedPattern {
        match self {
            Self::Named(p) => p.resolve(grid),
            Self::Custom(c) => c.resolve(grid),
        }
    }
}

impl From<LatticePattern> for LatticeWave {
    fn from(p: LatticePattern) -> Self {
        Self::Named(p)
    }
}

impl From<LatticeCells> for LatticeWave {
    fn from(c: LatticeCells) -> Self {
        Self::Custom(c)
    }
}

/// 状态机:驱动波浪、标记与秒表。
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum LatticeStatus {
    #[default]
    Working,
    Done,
    Error,
}

/// 内部锚点:working→done/error 时冻结秒表显示,再次回到 working 重置为 0。
#[derive(Clone)]
struct LatticeState {
    /// 本段 working 的开始时刻(MotionClock 秒)。
    anchor: f64,
    /// 最近一次离开 working 时冻结的十分之一秒读数(ds)。
    frozen_ds: u32,
    last_status: LatticeStatus,
}

/// 单 cell 在周期内 `phase`(秒)处的 opacity,关键帧位置 = 占比 × cycle 秒。
/// 逐段还原 CSS:idle →(in-out 上升)→ peak 平台 →(in-out 回落)→ idle。
pub fn lattice_cell_opacity(phase: f32, cycle: f32, lit: LatticeLit, idle: f32) -> f32 {
    if cycle <= 0.0 {
        return idle;
    }
    let (rise, peak_end, settle) = lit.fractions();
    let rise = rise * cycle;
    let peak_end = peak_end * cycle;
    let settle = settle * cycle;
    let p = if phase <= 0.0 { 0.0 } else { phase };
    if p < rise {
        let t = p / rise.max(1e-6);
        idle + (1.0 - idle) * EASE_IN_OUT_SOLVER.sample(t)
    } else if p < peak_end {
        1.0
    } else if p < settle {
        let t = (p - peak_end) / (settle - peak_end).max(1e-6);
        1.0 - (1.0 - idle) * EASE_IN_OUT_SOLVER.sample(t)
    } else {
        idle
    }
}

/// 秒表读数格式化:`<60s` 为 `12.3s`,否则 `1m 4.5s`(与源码 fmt 一致)。
pub fn lattice_format_ds(ds: u32) -> String {
    if ds < 600 {
        format!("{:.1}s", ds as f32 / 10.0)
    } else {
        format!("{}m {:.1}s", ds / 600, (ds % 600) as f32 / 10.0)
    }
}

/// 无障碍播报文本(与源码 spoken 一致)。
pub fn lattice_spoken_ds(ds: u32) -> String {
    if ds < 600 {
        format!("{:.1} seconds", ds as f32 / 10.0)
    } else {
        format!(
            "{} minutes {:.1} seconds",
            ds / 600,
            (ds % 600) as f32 / 10.0
        )
    }
}

/// 每个 grid 尺寸的标记 cell 集合(对勾 / 叉)。
pub fn lattice_mark_cells(grid: usize, status: LatticeStatus) -> &'static [usize] {
    match (grid, status) {
        (3, LatticeStatus::Done) => &[2, 3, 5, 7],
        (3, _) => &[0, 2, 4, 6, 8],
        (_, LatticeStatus::Done) => &[7, 8, 10, 13],
        (_, _) => &[0, 3, 5, 6, 9, 10, 12, 15],
    }
}

/// 点阵加载状态行:`Thinking ···· 12.3s` → `Done in ✓ 4.1s`。
#[derive(IntoElement)]
pub struct LatticeLoader {
    id: ElementId,
    label: SharedString,
    done_label: SharedString,
    error_label: SharedString,
    status: LatticeStatus,
    wave: LatticeWave,
    grid: usize,
    shape_round: bool,
    color: Option<Hsla>,
    done_color: Hsla,
    error_color: Hsla,
    cell_size: f32,
    gap: f32,
    font_size: f32,
    step_ms: f32,
    idle_opacity: f32,
    glow: bool,
    glow_color: Option<Hsla>,
    show_timer: bool,
    /// 受控经过秒数;设置后内部时钟不运行。
    elapsed_secs: Option<f64>,
}

impl LatticeLoader {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            label: "Thinking".into(),
            done_label: "Done in".into(),
            error_label: "Failed after".into(),
            status: LatticeStatus::Working,
            wave: LatticeWave::Named(LatticePattern::Orbit),
            grid: 3,
            shape_round: true,
            color: None,
            done_color: hex(0x22c55e, 1.0),
            error_color: hex(0xef4444, 1.0),
            cell_size: 6.0,
            gap: 2.0,
            font_size: 14.0,
            step_ms: 90.0,
            idle_opacity: 0.15,
            glow: false,
            glow_color: None,
            show_timer: true,
            elapsed_secs: None,
        }
    }
    pub fn label(mut self, v: impl Into<SharedString>) -> Self {
        self.label = v.into();
        self
    }
    pub fn done_label(mut self, v: impl Into<SharedString>) -> Self {
        self.done_label = v.into();
        self
    }
    pub fn error_label(mut self, v: impl Into<SharedString>) -> Self {
        self.error_label = v.into();
        self
    }
    pub fn status(mut self, v: LatticeStatus) -> Self {
        self.status = v;
        self
    }
    pub fn wave(mut self, v: impl Into<LatticeWave>) -> Self {
        self.wave = v.into();
        self
    }
    /// 格宽:3 或 4(其他值按 3 处理)。
    pub fn grid(mut self, v: usize) -> Self {
        self.grid = if v == 4 { 4 } else { 3 };
        self
    }
    /// `true` 圆点(默认),`false` 圆角方块。
    pub fn shape_round(mut self, v: bool) -> Self {
        self.shape_round = v;
        self
    }
    /// cell / 文字 / 秒表墨色;缺省用主题 foreground。
    pub fn color(mut self, v: Hsla) -> Self {
        self.color = Some(v);
        self
    }
    pub fn done_color(mut self, v: Hsla) -> Self {
        self.done_color = v;
        self
    }
    pub fn error_color(mut self, v: Hsla) -> Self {
        self.error_color = v;
        self
    }
    pub fn cell_size(mut self, v: f32) -> Self {
        self.cell_size = v.max(1.0);
        self
    }
    pub fn gap(mut self, v: f32) -> Self {
        self.gap = v.max(0.0);
        self
    }
    pub fn font_size(mut self, v: f32) -> Self {
        self.font_size = v.max(6.0);
        self
    }
    /// 相邻 cell 点亮的间隔毫秒;整圈循环按此缩放。
    pub fn step_ms(mut self, v: f32) -> Self {
        self.step_ms = v.max(1.0);
        self
    }
    pub fn idle_opacity(mut self, v: f32) -> Self {
        self.idle_opacity = v.clamp(0.0, 1.0);
        self
    }
    pub fn glow(mut self, v: bool) -> Self {
        self.glow = v;
        self
    }
    /// 光晕颜色;缺省跟随墨色(标记跟随标记色)。
    pub fn glow_color(mut self, v: Hsla) -> Self {
        self.glow_color = Some(v);
        self
    }
    pub fn show_timer(mut self, v: bool) -> Self {
        self.show_timer = v;
        self
    }
    /// 受控经过秒数(冻结内部时钟)。
    pub fn elapsed_secs(mut self, v: f64) -> Self {
        self.elapsed_secs = Some(v);
        self
    }
}

impl RenderOnce for LatticeLoader {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let theme = cx.arc_theme();
        let colors = theme.colors;
        let reduced = is_reduced_motion(cx);
        let now = motion_now(cx);

        let grid = if self.grid == 4 { 4 } else { 3 };
        let n = grid;
        let pat = self.wave.clone().resolve(grid);
        let d = (self.step_ms * pat.scale).max(1.0) / 1000.0; // 一 delay 单位的秒数
        let cycle = (pat.loop_steps * d).max(0.05); // 整圈秒数
        let lit = LatticeLit(pat.lit.0.clamp(0.05, 1.0));
        let ink = self.color.unwrap_or(colors.foreground);
        let mark_color = match self.status {
            LatticeStatus::Error => self.error_color,
            _ => self.done_color,
        };
        let glow_ink = self.glow_color.unwrap_or(ink);
        let glow_mark = self.glow_color.unwrap_or(mark_color);

        // —— 秒表:受控 elapsed 优先;内部锚点随 status 变化重置/冻结 —— //
        let state_cell = window
            .use_keyed_state(
                ElementId::NamedChild(self.id.clone().into(), "lattice-state".into()),
                cx,
                |_, _| {
                    Rc::new(RefCell::new(LatticeState {
                        anchor: now,
                        frozen_ds: 0,
                        last_status: LatticeStatus::Working,
                    }))
                },
            )
            .read(cx)
            .clone();
        let ds = {
            let mut st = state_cell.borrow_mut();
            if st.last_status != self.status {
                match self.status {
                    LatticeStatus::Working => {
                        // 回到 working:重新从 0 计时
                        st.anchor = now;
                        st.frozen_ds = 0;
                    }
                    _ => {
                        // 离开 working:冻结当前读数
                        let live = ((now - st.anchor).max(0.0) * 10.0) as u32;
                        st.frozen_ds = live;
                    }
                }
                st.last_status = self.status;
            }
            match (self.status, self.elapsed_secs) {
                (_, Some(e)) => (e.max(0.0) * 10.0) as u32,
                (LatticeStatus::Working, None) => ((now - st.anchor).max(0.0) * 10.0) as u32,
                (_, None) => st.frozen_ds,
            }
        };
        let timer_text = lattice_format_ds(ds);
        let working = self.status == LatticeStatus::Working;
        let needs_anim_frame = working && self.elapsed_secs.is_none();

        // —— 波浪相位:所有 cell 共享一个时钟原点,delay=unit*d —— //
        let wave_progress = if working {
            (now % cycle as f64) as f32
        } else {
            0.0
        };

        // —— 层切换进度:离开 working 时 0→1(200ms),回到 working 时 1→0 —— //
        let layer_progress = if working { 0.0f32 } else { 1.0f32 };

        let grid_px_w = n as f32 * self.cell_size + (n.saturating_sub(1)) as f32 * self.gap;
        let grid_px_h = grid_px_w;

        let cells: Vec<(usize, Option<f32>)> =
            pat.cells.iter().enumerate().map(|(i, v)| (i, *v)).collect();
        let mark_set: Vec<usize> = lattice_mark_cells(grid, self.status).to_vec();
        let status = self.status;

        // 波浪 + 标记统一在一张 canvas 里画:两张 div 网格叠放需要 n²×2 个元素,
        // canvas 一次绘制即可,且能对 hole/idle 透明度做精确采样。
        let lattice_canvas = canvas(
            move |bounds, _, _| bounds,
            move |bounds: Bounds<Pixels>, _, window, _| {
                let cell = self.cell_size.max(1.0);
                let gap = self.gap.max(0.0);
                let radius = if self.shape_round {
                    cell * 0.5
                } else {
                    (cell * 0.25).max(1.0)
                };
                // 标记层整体从 0.9 缩放进入;运行层淡出。两组都乘 layer_progress。
                let mark_alpha = layer_progress;
                let run_alpha = 1.0 - layer_progress;
                let origin_x = f32::from(bounds.origin.x);
                let origin_y = f32::from(bounds.origin.y);

                // —— 运行层 —— //
                if run_alpha > 0.001 {
                    for (i, unit) in &cells {
                        let Some(unit) = unit else { continue };
                        let col = (*i % n) as f32;
                        let row = (*i / n) as f32;
                        let x = origin_x + col * (cell + gap);
                        let y = origin_y + row * (cell + gap);
                        let delay = unit * d;
                        let phase = if reduced {
                            // 减弱动画:所有 delay 归零、固定 1.4s 慢闪,峰值压到 0.7
                            (now % 1.4) as f32 / 1.4 * cycle
                        } else {
                            (wave_progress - delay).rem_euclid(cycle)
                        };
                        let mut alpha = lattice_cell_opacity(phase, cycle, lit, self.idle_opacity);
                        if reduced {
                            alpha *= 0.7;
                        }
                        let mut c = ink;
                        c.a *= alpha * run_alpha;
                        window.paint_quad(quad(
                            Bounds::new(point(px(x), px(y)), size(px(cell), px(cell))),
                            Corners::all(px(radius)),
                            c,
                            Edges::all(px(0.0)),
                            Hsla::default(),
                            gpui_kit::BorderStyle::default(),
                        ));
                        if self.glow && alpha > 0.05 {
                            // box-shadow 光晕:半径按源码 0 0 cell*1.2 spread cell*0.12。
                            // GPUI 没有外发光,用 3 层同心半透明 quad 近似。
                            let halo = cell * 1.2;
                            for k in 1..=3usize {
                                let spread = halo * (k as f32) / 3.0;
                                let mut hc = glow_ink;
                                hc.a *= alpha * run_alpha * 0.10 / k as f32;
                                let b = Bounds::new(
                                    point(px(x - spread + cell * 0.5), px(y - spread + cell * 0.5)),
                                    size(px(cell + spread * 2.0), px(cell + spread * 2.0)),
                                );
                                window.paint_quad(quad(
                                    b,
                                    Corners::all(px((cell + spread * 2.0) * 0.5)),
                                    hc,
                                    Edges::all(px(0.0)),
                                    Hsla::default(),
                                    gpui_kit::BorderStyle::default(),
                                ));
                            }
                        }
                    }
                    // hole:固定 idle*0.47
                    for (i, unit) in &cells {
                        if unit.is_some() {
                            continue;
                        }
                        let col = (*i % n) as f32;
                        let row = (*i / n) as f32;
                        let mut c = ink;
                        c.a *= self.idle_opacity * 0.47 * run_alpha;
                        window.paint_quad(quad(
                            Bounds::new(
                                point(
                                    px(origin_x + col * (cell + gap)),
                                    px(origin_y + row * (cell + gap)),
                                ),
                                size(px(cell), px(cell)),
                            ),
                            Corners::all(px(radius)),
                            c,
                            Edges::all(px(0.0)),
                            Hsla::default(),
                            gpui_kit::BorderStyle::default(),
                        ));
                    }
                }

                // —— 标记层 —— //
                if mark_alpha > 0.001 {
                    let scale = 0.9 + 0.1 * ease_out_sample(mark_alpha);
                    let cx_pt = origin_x + grid_px_w * 0.5;
                    let cy_pt = origin_y + grid_px_h * 0.5;
                    for i in &mark_set {
                        let col = (*i % n) as f32;
                        let row = (*i / n) as f32;
                        let base_x = origin_x + col * (cell + gap);
                        let base_y = origin_y + row * (cell + gap);
                        // 围绕格子中心缩放
                        let cx_cell = base_x + cell * 0.5;
                        let cy_cell = base_y + cell * 0.5;
                        let sx = cx_pt + (cx_cell - cx_pt) * scale;
                        let sy = cy_pt + (cy_cell - cy_pt) * scale;
                        let s = cell * scale;
                        let mut c = mark_color;
                        c.a *= mark_alpha;
                        window.paint_quad(quad(
                            Bounds::new(
                                point(px(sx - s * 0.5), px(sy - s * 0.5)),
                                size(px(s), px(s)),
                            ),
                            Corners::all(px(if self.shape_round {
                                s * 0.5
                            } else {
                                (s * 0.25).max(1.0)
                            })),
                            c,
                            Edges::all(px(0.0)),
                            Hsla::default(),
                            gpui_kit::BorderStyle::default(),
                        ));
                        if self.glow {
                            let halo = cell * 1.2;
                            for k in 1..=2usize {
                                let spread = halo * (k as f32) / 2.0;
                                let mut hc = glow_mark;
                                hc.a *= mark_alpha * 0.12 / k as f32;
                                window.paint_quad(quad(
                                    Bounds::new(
                                        point(
                                            px(sx - s * 0.5 - spread + s * 0.5),
                                            px(sy - s * 0.5 - spread + s * 0.5),
                                        ),
                                        size(px(s + spread * 2.0), px(s + spread * 2.0)),
                                    ),
                                    Corners::all(px((s + spread * 2.0) * 0.5)),
                                    hc,
                                    Edges::all(px(0.0)),
                                    Hsla::default(),
                                    gpui_kit::BorderStyle::default(),
                                ));
                            }
                        }
                    }
                }
            },
        )
        .w(px(grid_px_w))
        .h(px(grid_px_h));

        // —— 三段状态文本交叉切换:激活段静态,其余 blur+透明(BlurFallback)—— //
        let active = status;
        let text_items = [
            (LatticeStatus::Working, self.label.clone()),
            (LatticeStatus::Done, self.done_label.clone()),
            (LatticeStatus::Error, self.error_label.clone()),
        ];
        // 用过渡进度近似交叉淡化:非激活文本透明度按 layer 进度反向;
        // 简化:激活文本直接显示,非激活不渲染(GPUI 无静态多行堆叠文本淡出成本高)。
        let active_label = text_items
            .iter()
            .find(|(s, _)| *s == active)
            .map(|(_, t)| t.clone())
            .unwrap_or_else(|| self.label.clone());

        let timer_el = if self.show_timer {
            Some(
                div()
                    .text_size(px(self.font_size * 0.875))
                    .text_color(ink.opacity(0.6))
                    .child(SharedString::from(timer_text)),
            )
        } else {
            None
        };

        let announce = if working {
            format!("{}, in progress", self.label)
        } else if status == LatticeStatus::Done {
            format!(
                "{}{}",
                self.done_label,
                if self.show_timer {
                    format!(" {}", lattice_spoken_ds(ds))
                } else {
                    String::new()
                }
            )
        } else {
            format!(
                "{}{}",
                self.error_label,
                if self.show_timer {
                    format!(" {}", lattice_spoken_ds(ds))
                } else {
                    String::new()
                }
            )
        };

        if needs_anim_frame {
            window.request_animation_frame();
        }

        div()
            .id(self.id.clone())
            .test_support()
            .role(Role::Status)
            .aria_label(SharedString::from(announce))
            .flex_none()
            .flex()
            .items_center()
            .gap(px(self.font_size * 0.625))
            .child(lattice_canvas)
            .child(
                div()
                    .text_size(px(self.font_size))
                    .font_medium()
                    .text_color(ink)
                    .child(active_label),
            )
            .children(timer_el)
    }
}

/// 标记层 out 缓动(与 EASE_OUT 同曲线)。
fn ease_out_sample(t: f32) -> f32 {
    EASE_OUT_SOLVER.sample(t)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn close(a: f32, b: f32) -> bool {
        (a - b).abs() < 1e-3
    }

    #[test]
    fn lattice_keyframes_track_source_curve_shape() {
        // lit 0.62、cycle 1s:rise=18%、peak_end=42%、settle=62%(秒=比例)。
        let lit = LatticeLit(0.62);
        let idle = 0.15;
        let (rise, peak_end, settle) = lit.fractions();
        assert!(close(lattice_cell_opacity(0.0, 1.0, lit, idle), idle));
        // 上升段中点应在 idle 与 1 之间且超过半程(ease-in-out)
        let mid = lattice_cell_opacity(rise * 0.5, 1.0, lit, idle);
        assert!(mid > idle && mid < 1.0, "mid={mid}");
        // 平台段为峰值
        assert!(close(
            lattice_cell_opacity((rise + peak_end) * 0.5, 1.0, lit, idle),
            1.0
        ));
        // 下降段回到 idle
        let tail = lattice_cell_opacity((peak_end + settle) * 0.5, 1.0, lit, idle);
        assert!(tail < 1.0 && tail > idle, "tail={tail}");
        assert!(close(lattice_cell_opacity(settle, 1.0, lit, idle), idle));
        assert!(close(
            lattice_cell_opacity(settle + 0.1, 1.0, lit, idle),
            idle
        ));
    }

    #[test]
    fn lattice_lit_variants_compress_the_wave() {
        // lit 0.35:平台中点为 1,波形整体压缩在 [0, 0.35] 内。
        let lit = LatticeLit(0.35);
        let idle = 0.15;
        let (rise, peak_end, settle) = lit.fractions();
        assert!(close(
            lattice_cell_opacity((rise + peak_end) * 0.5, 1.0, lit, idle),
            1.0
        ));
        assert!(close(lattice_cell_opacity(settle, 1.0, lit, idle), idle));
        // 与源码比例一致:0.45 → 13%/31%/45%(允许 ±0.5% 浮点差)
        let (r45, p45, s45) = LatticeLit(0.45).fractions();
        assert!(close(r45, 0.13) && close(p45, 0.31) && close(s45, 0.45));
        let (r25, p25, s25) = LatticeLit(0.25).fractions();
        assert!(close(r25, 0.07) && close(p25, 0.17) && close(s25, 0.25));
        // cycle 缩放正确:cycle=2s 时 settle 位置在 2×0.62 秒
        assert!(close(
            lattice_cell_opacity(2.0 * 0.62, 2.0, LatticeLit(0.62), idle),
            idle
        ));
    }

    #[test]
    fn lattice_timer_formats_like_source() {
        assert_eq!(lattice_format_ds(0), "0.0s");
        assert_eq!(lattice_format_ds(41), "4.1s");
        assert_eq!(lattice_format_ds(599), "59.9s");
        assert_eq!(lattice_format_ds(600), "1m 0.0s");
        assert_eq!(lattice_format_ds(641), "1m 4.1s");
        assert_eq!(lattice_spoken_ds(41), "4.1 seconds");
        assert_eq!(lattice_spoken_ds(641), "1 minutes 4.1 seconds");
    }

    #[test]
    fn lattice_marks_match_source_cells() {
        assert_eq!(lattice_mark_cells(3, LatticeStatus::Done), &[2, 3, 5, 7]);
        assert_eq!(
            lattice_mark_cells(3, LatticeStatus::Error),
            &[0, 2, 4, 6, 8]
        );
        assert_eq!(lattice_mark_cells(4, LatticeStatus::Done), &[7, 8, 10, 13]);
        assert_eq!(
            lattice_mark_cells(4, LatticeStatus::Error),
            &[0, 3, 5, 6, 9, 10, 12, 15]
        );
    }

    #[test]
    fn lattice_patterns_resolve_with_holes_and_cycles() {
        // orbit@3:中心是洞;orbit@4:内四格是洞
        let o3 = LatticePattern::Orbit.resolve(3);
        assert_eq!(o3.cells[4], None);
        assert_eq!(o3.cells.len(), 9);
        assert!(close(o3.loop_steps, 8.0));
        assert!(close(o3.scale, 1.2));
        assert!(close(o3.lit.0, 0.62));
        let o4 = LatticePattern::Orbit.resolve(4);
        assert_eq!(o4.cells[5], None);
        assert_eq!(o4.cells[6], None);
        assert!(close(o4.lit.0, 0.45));
        // snake@4 lit 0.25;pulse@4 scale 2.5
        let s4 = LatticePattern::Snake.resolve(4);
        assert!(close(s4.lit.0, 0.25));
        assert!(close(s4.loop_steps, 16.0));
        let p4 = LatticePattern::Pulse.resolve(4);
        assert!(close(p4.scale, 2.5));
        // spin 重复 delay(0,0,1,1,...)保留原值
        let sp = LatticePattern::Spin.resolve(4);
        assert_eq!(sp.cells[0], Some(0.0));
        assert_eq!(sp.cells[1], Some(0.0));
        assert_eq!(sp.cells[2], Some(1.0));
    }

    #[test]
    fn lattice_custom_cells_follow_source_defaults() {
        // 自定义:部分洞,无 loop/scale/lit 时按 max+4.2 / 1 / 0.62。
        let c = LatticeCells {
            cells: vec![Some(0.0), None, Some(3.0)],
            loop_steps: None,
            scale: None,
            lit: None,
        };
        let r = c.resolve(2);
        assert_eq!(r.cells.len(), 4); // 越界补洞
        assert_eq!(r.cells[1], None);
        assert_eq!(r.cells[3], None);
        assert!(close(r.loop_steps, 7.2)); // 3 + 4.2
        assert!(close(r.scale, 1.0));
        assert!(close(r.lit.0, 0.62));
        // 显式覆盖
        let c2 = LatticeCells {
            cells: vec![Some(1.0)],
            loop_steps: Some(5.0),
            scale: Some(2.0),
            lit: Some(LatticeLit(0.4)),
        };
        let r2 = c2.resolve(3);
        assert!(close(r2.loop_steps, 5.0));
        assert!(close(r2.scale, 2.0));
        assert!(close(r2.lit.0, 0.4));
    }

    #[test]
    fn lattice_cycle_and_delay_follow_step_scale() {
        // cycle = loop_steps * step * scale
        let p = LatticePattern::Dots.resolve(3);
        assert!(close(p.loop_steps, 3.0));
        assert!(close(p.scale, 2.4));
        let step_ms = 90.0;
        let d = step_ms * p.scale / 1000.0;
        let cycle = p.loop_steps * d;
        assert!(close(cycle, 3.0 * 90.0 * 2.4 / 1000.0));
    }
}