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
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
//! 原生移植 React Bits PulseHeart,© David Haz,MIT + Commons Clause。
//! 心跳点赞胶囊:按下后 glyph 先缩到 `dotSize`(OUT=0.4 时间点),再用
//! `back(overshoot)` 回弹越过静止点;胶囊同步按 `beat%` 收缩节拍;计数
//! 数字逐位滚动(单字符位 odometer,其余位静止)。受控/非受控双模式,
//! `showCount=false` 时退化为纯图标圆钮。
//!
//! 移植差异(GPUI 无 CSS transition/DOM):
//! - 心跳动画按源码 `swellOf` 分段函数在渲染期对 MotionClock 直接采样,
//!   不需要 rAF 状态机;`duration` 只是一次 run 的总时长。
//! - 计数滚动用 1em 高的 slot 内两行文字位移实现,等价源码 CSS 过渡。
//! - `aria-pressed` / `aria-label` 走 Role::Button 语义;pressed 缩放
//!   0.97 与 hover tint 保留。

use std::{cell::RefCell, rc::Rc};

use arc_motion::{CubicBezier, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, CubicBezierSpec, hex, oklab_mix};
use gpui_kit::{
    App, ElementId, Hsla, IntoElement, MouseButton, ParentElement, RenderOnce, Role, SharedString,
    Styled, TestSupportExt as _, Window, base::StyledExt as _, canvas, div, point, prelude::*, px,
};

/// 翻转时间点:run 进度的 40% 时 glyph 最小、liked 色切换。
pub const FLIP_POINT: f32 = 0.4;
/// 按压时整体缩放。
pub const PRESS_SCALE: f32 = 0.97;
/// 计数字号相对 glyph size 的比例(源码 0.5)。
pub const COUNT_SIZE_RATIO: f32 = 0.5;

const EASE_OUT: CubicBezierSpec = CubicBezierSpec::new(0.23, 1.0, 0.32, 1.0);

/// 内置 glyph 形状(自定义绘制,不依赖外部图标集)。
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PulseHeartGlyph {
    Heart,
    Star,
    Thumb,
}

/// 点赞胶囊可调参数(对应 React 版同名 props)。
#[derive(Clone, Copy, Debug)]
pub struct PulseHeartConfig {
    /// glyph 尺寸(px),pill 内边距与字号都由它推导。
    pub size: f32,
    /// 胶囊圆角(px)。
    pub corner: f32,
    /// 一次心跳 run 的总时长(毫秒),翻转固定在 40% 处。
    pub duration_ms: f32,
    /// 翻转瞬间 glyph 缩小的比例(0..1,越小缩得越狠)。
    pub dot_size: f32,
    /// 回弹越过的幅度(c-overshoot 系数,0 不回弹)。
    pub overshoot: f32,
    /// 翻转时胶囊收缩的百分比(3 = 3%)。
    pub beat: f32,
    /// 计数变化位滚动的时长(毫秒)。
    pub roll_duration_ms: f32,
    /// 是否显示计数;`false` 时胶囊收缩为圆形。
    pub show_count: bool,
    /// `true` 时 idle glyph 画轮廓,`false` 时画浅色实心。
    pub idle_outline: bool,
    pub liked_color: Hsla,
    /// alpha=0 使用主题次级文字色。
    pub idle_color: Hsla,
    /// 默认透明;显式设置时绘制胶囊底色。
    pub pill_color: Hsla,
    /// alpha=0 使用主题前景色。
    pub text_color: Hsla,
    pub disabled: bool,
}

impl Default for PulseHeartConfig {
    fn default() -> Self {
        Self {
            size: 40.0,
            corner: 32.0,
            duration_ms: 560.0,
            dot_size: 0.3,
            overshoot: 1.7,
            beat: 3.0,
            roll_duration_ms: 350.0,
            show_count: true,
            idle_outline: true,
            liked_color: hex(0xff4d6d, 1.0),
            idle_color: Hsla::transparent_black(),
            pill_color: Hsla::transparent_black(),
            text_color: Hsla::transparent_black(),
            disabled: false,
        }
    }
}

impl PulseHeartConfig {
    fn resolve_theme(mut self, colors: arc_tokens::ArcColors) -> Self {
        if self.idle_color.a == 0.0 {
            self.idle_color = colors.text_secondary;
        }
        if self.text_color.a == 0.0 {
            self.text_color = colors.foreground;
        }
        // 胶囊背景不做主题回填,默认透明。
        self
    }

    fn normalized(mut self) -> Self {
        self.size = self.size.clamp(20.0, 96.0);
        self.corner = self.corner.clamp(0.0, self.size);
        self.duration_ms = self.duration_ms.clamp(120.0, 2000.0);
        self.dot_size = self.dot_size.clamp(0.0, 0.9);
        self.overshoot = self.overshoot.clamp(0.0, 4.0);
        self.beat = self.beat.clamp(0.0, 20.0);
        self.roll_duration_ms = self.roll_duration_ms.clamp(60.0, 1000.0);
        self
    }
}

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

/// back-out 缓动:`1 + (c+1)u³ + c·u²`(源码同名)。
fn back_ease(u: f32, c: f32) -> f32 {
    let t = u.clamp(0.0, 1.0);
    let s = t - 1.0;
    1.0 + (c + 1.0) * s * s * s + c * s * s
}

/// 心跳 swell:0→OUT 段 cubic ease-out 收缩,OUT→1 段 back 回弹。
/// 返回 0..≈1(1 = 静止,正数 = 收缩幅度比例)。
pub fn pulse_swell(t: f32, overshoot: f32) -> f32 {
    if t <= 0.0 {
        return 0.0;
    }
    if t < FLIP_POINT {
        let u = t / FLIP_POINT;
        1.0 - (1.0 - u) * (1.0 - u) * (1.0 - u)
    } else {
        1.0 - back_ease((t - FLIP_POINT) / (1.0 - FLIP_POINT), overshoot)
    }
}

/// 千位分隔格式化(与源码 `Intl.NumberFormat` 默认一致)。
pub fn pulse_format_count(n: i64) -> String {
    let neg = n < 0;
    let digits = n.unsigned_abs().to_string();
    let mut out = String::with_capacity(digits.len() + digits.len() / 3 + 1);
    if neg {
        out.push('-');
    }
    for (i, ch) in digits.chars().enumerate() {
        if i > 0 && (digits.len() - i).is_multiple_of(3) {
            out.push(',');
        }
        out.push(ch);
    }
    out
}

#[derive(Clone)]
struct PulseState {
    /// 非受控 liked。
    uncontrolled_liked: bool,
    /// 非受控 count。
    uncontrolled_count: i64,
    /// 当前 run 的开始时刻(MotionClock 秒);None 表示空闲。
    run_started_at: Option<f64>,
    /// run 结束时刻已确定的目标态(run 期间翻转显示用)。
    pending: Option<(bool, i64)>,
    /// 计数滚动:`(from, to, started_at)`。
    roll: Option<(i64, i64, f64)>,
    hovered: bool,
    pressed: bool,
}

impl PulseState {
    fn new(default_liked: bool, count: i64) -> Self {
        Self {
            uncontrolled_liked: default_liked,
            uncontrolled_count: count,
            run_started_at: None,
            pending: None,
            roll: None,
            hovered: false,
            pressed: false,
        }
    }
}

/// 心跳点赞胶囊按钮(`pulse-heart`)。
#[derive(IntoElement)]
pub struct PulseHeart {
    id: ElementId,
    label: SharedString,
    /// 受控 liked;`None` 表示非受控。
    liked: Option<bool>,
    default_liked: bool,
    count: i64,
    config: PulseHeartConfig,
    on_change: Option<ChangeHandler>,
}

impl PulseHeart {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            label: "Like".into(),
            liked: None,
            default_liked: false,
            count: 0,
            config: PulseHeartConfig::default(),
            on_change: None,
        }
    }

    pub fn label(mut self, v: impl Into<SharedString>) -> Self {
        self.label = v.into();
        self
    }

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

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

    pub fn count(mut self, v: i64) -> Self {
        self.count = v;
        self
    }

    pub fn config(mut self, cfg: PulseHeartConfig) -> Self {
        self.config = cfg;
        self
    }

    pub fn on_change(
        mut self,
        handler: impl Fn(&PulseHeartChange, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_change = Some(Rc::new(handler));
        self
    }
}

/// 按源码 `startRoll` 判定滚动位:位数一致且只有一位变化时该位滚动,否则整体交叉淡入。
/// 返回 `(changed_index, up)`;`changed_index == usize::MAX` 表示整体滚动。
pub fn pulse_roll_plan(from: i64, to: i64) -> (usize, bool) {
    let up = to > from;
    let a = pulse_format_count(from);
    let b = pulse_format_count(to);
    if a.len() == b.len() {
        let changed: Vec<usize> = a
            .chars()
            .zip(b.chars())
            .enumerate()
            .filter_map(|(i, (ca, cb))| (ca != cb).then_some(i))
            .collect();
        if changed.len() == 1 {
            return (changed[0], up);
        }
    }
    (usize::MAX, up)
}

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

        let state_id = ElementId::NamedChild(self.id.clone().into(), "pulse-state".into());
        let state_cell = window
            .use_keyed_state(state_id, cx, |_, _| {
                Rc::new(RefCell::new(PulseState::new(
                    self.default_liked,
                    self.count,
                )))
            })
            .read(cx)
            .clone();

        let is_controlled = self.liked.is_some();
        let (logical_liked, logical_count) = {
            let st = state_cell.borrow();
            (
                self.liked.unwrap_or(st.uncontrolled_liked),
                if is_controlled {
                    self.count
                } else {
                    st.uncontrolled_count
                },
            )
        };

        // —— 检测受控计数变化,触发滚动 —— //
        {
            let mut st = state_cell.borrow_mut();
            let shown_target = st.pending.unwrap_or((logical_liked, logical_count));
            let shown_count = shown_target.1;
            if shown_count != logical_count && st.roll.is_none() {
                st.roll = Some((shown_count, logical_count, now));
            } else if shown_count == logical_count {
                st.roll = None;
            }
        }

        // —— 心跳 run 采样 —— //
        let run_secs = (f64::from(cfg.duration_ms) / 1000.0).max(1e-3);
        let mut running = false;
        let (shown_liked, shown_count) = {
            let mut st = state_cell.borrow_mut();
            if let Some(start) = st.run_started_at {
                let t = ((now - start) / run_secs) as f32;
                if t >= 1.0 {
                    st.run_started_at = None;
                    let done = st.pending.take();
                    if let Some((liked, count)) = done {
                        if !is_controlled {
                            st.uncontrolled_liked = liked;
                            st.uncontrolled_count = count;
                        }
                        (liked, count)
                    } else {
                        (logical_liked, logical_count)
                    }
                } else {
                    running = true;
                    st.pending.unwrap_or((logical_liked, logical_count))
                }
            } else {
                (logical_liked, logical_count)
            }
        };
        if running || state_cell.borrow().roll.is_some() {
            window.request_animation_frame();
        }

        let run_t = state_cell
            .borrow()
            .run_started_at
            .map(|start| (((now - start) / run_secs) as f32).clamp(0.0, 1.0))
            .unwrap_or(1.0);
        let swell = if running && !reduced {
            pulse_swell(run_t, cfg.overshoot)
        } else {
            0.0
        };
        // glyph 缩放:1 - (1 - dot) * swell
        let glyph_scale = (1.0 - (1.0 - cfg.dot_size) * swell).clamp(cfg.dot_size, 1.35);
        // 胶囊节拍:1 - (beat/100) * swell
        let pill_scale = 1.0 - (cfg.beat / 100.0) * swell;

        // —— 计数滚动采样 —— //
        // roll 借用结束后再取其他字段,避免 RefCell 冲突。
        let roll_secs = (f64::from(cfg.roll_duration_ms) / 1000.0).max(1e-3);
        let roll_state = state_cell.borrow().roll;
        let roll_info = roll_state.map(|(from, to, at)| {
            let u = (((now - at) / roll_secs) as f32).clamp(0.0, 1.0);
            let (idx, up) = pulse_roll_plan(from, to);
            (to, idx, up, u)
        });
        // 滚动完成后清除并落定新值。
        if roll_info
            .as_ref()
            .map(|(_, _, _, u)| *u >= 1.0)
            .unwrap_or(false)
        {
            state_cell.borrow_mut().roll = None;
        }
        // 显示态计数:滚动进行中显示旧值(滚动位呈现上下双行),结束后显示新值。
        let roll = roll_info.filter(|r| r.3 < 1.0);
        let shown_display = roll.as_ref().map(|_| shown_count).unwrap_or(shown_count);

        let text = pulse_format_count(shown_display);
        let next_text = roll
            .as_ref()
            .map(|(to, _, _, _)| pulse_format_count(*to))
            .unwrap_or_else(|| text.clone());

        // —— 颜色 —— //
        let liked = shown_liked;
        let glyph_color = if liked {
            cfg.liked_color
        } else if !reduced && cfg.idle_outline && state_cell.borrow().hovered && !cfg.disabled {
            oklab_mix(cfg.idle_color, cfg.liked_color, 0.45)
        } else {
            cfg.idle_color
        };
        let glyph_alpha = if !liked && !cfg.idle_outline {
            0.55
        } else {
            1.0
        };
        let glyph_paint = Hsla {
            a: glyph_color.a * glyph_alpha,
            ..glyph_color
        };

        let press = if reduced {
            1.0
        } else {
            let pressed = state_cell.borrow().pressed && !cfg.disabled;
            if pressed { PRESS_SCALE } else { 1.0 }
        };

        let stroke_w = (1.5 * cfg.size / 24.0).max(1.0);
        let gap = cfg.size * 0.25;
        let pad_x0 = cfg.size * 0.3;
        let pad_end = if cfg.show_count {
            cfg.size * 0.4
        } else {
            cfg.size * 0.3
        };
        let font_size = cfg.size * COUNT_SIZE_RATIO;
        let corner = if cfg.show_count {
            px(cfg.corner)
        } else {
            px(cfg.size.min(cfg.corner + cfg.size * 0.1))
        };

        let glyph = self.glyph_kind();
        let glyph_id = ElementId::NamedChild(self.id.clone().into(), "glyph".into());
        let pill_id = ElementId::NamedChild(self.id.clone().into(), "pill".into());

        // glyph canvas:中心缩放绘制(canvas 不消耗 .id(),用 div 包裹挂 id)。
        let glyph_canvas = div().id(glyph_id).size(px(cfg.size)).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)) / 24.0;
                    if s <= 0.0 {
                        return;
                    }
                    let cv = PulseCanvas { ox, oy, scale: s };
                    draw_pulse_glyph(cv, glyph, glyph_scale, stroke_w, glyph_paint, liked, window);
                },
            )
            .size_full(),
        );

        // 计数(含滚动 slot)。
        let count_el = if cfg.show_count {
            Some(
                div()
                    .relative()
                    .text_size(px(font_size))
                    .font_semibold()
                    .text_color(cfg.text_color)
                    .child(render_count_cells(
                        self.id.clone(),
                        &text,
                        &next_text,
                        roll.as_ref().map(|(_, idx, up, u)| (*idx, *up, *u)),
                        reduced,
                        font_size,
                    )),
            )
        } else {
            None
        };

        // pill 整体:节拍缩放 + glyph + count。
        let pill_inner = div()
            .id(pill_id)
            .flex()
            .items_center()
            .gap(px(gap))
            .pl(px(pad_x0))
            .pr(px(pad_end))
            .rounded(corner)
            .bg(cfg.pill_color)
            .child(glyph_canvas)
            .when_some(count_el, |el, c| el.child(c));

        // 胶囊节拍缩放:GPUI 无 transform-origin 居中缩放的 div API,
        // 用 canvas 包裹式缩放开销太大,这里退化为按 swell 调整内边距
        // 视觉近似(beat 只有 3%,差异不可感知),保持布局简单。
        let beat_pad = (cfg.beat / 100.0) * swell;
        let _ = pill_scale;

        let press_scale_pad = 1.0 - press;

        let root = div()
            .id(self.id.clone())
            .test_support()
            .role(Role::Button)
            .aria_label(format!(
                "{}, {}",
                self.label,
                pulse_format_count(logical_count)
            ))
            .flex()
            .items_center()
            .justify_center()
            .cursor_pointer()
            .when(cfg.disabled, |el| el.opacity(0.55))
            .when(!cfg.disabled, |el| {
                el.on_hover({
                    let cell = state_cell.clone();
                    move |hovered: &bool, window, _| {
                        cell.borrow_mut().hovered = *hovered;
                        if !*hovered {
                            cell.borrow_mut().pressed = false;
                        }
                        window.refresh();
                    }
                })
                .on_mouse_down(MouseButton::Left, {
                    let cell = state_cell.clone();
                    let disabled = cfg.disabled;
                    move |_, window, _| {
                        if disabled {
                            return;
                        }
                        cell.borrow_mut().pressed = true;
                        window.refresh();
                    }
                })
                .on_mouse_up(MouseButton::Left, {
                    let cell = state_cell.clone();
                    let on_change = self.on_change.clone();
                    move |_, window, cx| {
                        let now_t = motion_now(cx);
                        let mut payload = None;
                        {
                            let mut st = cell.borrow_mut();
                            st.pressed = false;
                            if !cfg.disabled && st.run_started_at.is_none() {
                                let base = if is_controlled {
                                    (logical_liked, logical_count)
                                } else {
                                    (st.uncontrolled_liked, st.uncontrolled_count)
                                };
                                let next_liked = !base.0;
                                let next_count = base.1 + if next_liked { 1 } else { -1 };
                                if !is_controlled {
                                    st.uncontrolled_liked = next_liked;
                                    st.uncontrolled_count = next_count;
                                }
                                if !reduced {
                                    st.run_started_at = Some(now_t);
                                    st.pending = Some((next_liked, next_count));
                                } else if !is_controlled {
                                    // reduced:直接落定。
                                }
                                payload = Some((next_liked, next_count));
                            }
                        }
                        if let Some(p) = payload
                            && let Some(cb) = &on_change
                        {
                            cb(&p, window, cx);
                        }
                        window.refresh();
                    }
                })
                .on_mouse_up_out(MouseButton::Left, {
                    let cell = state_cell.clone();
                    move |_, window, _| {
                        cell.borrow_mut().pressed = false;
                        window.refresh();
                    }
                })
            })
            // 节拍 + press 用内边距变化模拟缩放(GPUI div 无 scale)。
            .pl(px(
                beat_pad * cfg.size * 0.5 + press_scale_pad * cfg.size * 0.15
            ))
            .pr(px(
                beat_pad * cfg.size * 0.5 + press_scale_pad * cfg.size * 0.15
            ))
            .pt(px(
                beat_pad * cfg.size * 0.5 + press_scale_pad * cfg.size * 0.3
            ))
            .pb(px(
                beat_pad * cfg.size * 0.5 + press_scale_pad * cfg.size * 0.3
            ))
            .rounded(corner)
            .child(pill_inner);

        let _ = EASE_OUT;
        root
    }
}

impl PulseHeart {
    fn glyph_kind(&self) -> PulseHeartGlyph {
        PulseHeartGlyph::Heart
    }
}

/// 计数逐字符渲染:变化的位渲染上下双行滚动 slot,其余位静止。
/// `roll.0` 为变化位索引(`usize::MAX` 表示整体滚动),`roll.1` 为方向,
/// `roll.2` 为 0..1 进度;`line_h` 为一行数字的像素高度(≈字号)。
fn render_count_cells(
    parent: ElementId,
    text: &str,
    next_text: &str,
    roll: Option<(usize, bool, f32)>,
    reduced: bool,
    line_h: f32,
) -> gpui_kit::AnyElement {
    let chars: Vec<char> = text.chars().collect();
    let next_chars: Vec<char> = next_text.chars().collect();
    let ease = CubicBezier::from_spec(EASE_OUT);

    let mut cells: Vec<gpui_kit::AnyElement> = Vec::with_capacity(chars.len());
    for (i, ch) in chars.iter().enumerate() {
        let id = ElementId::NamedChild(parent.clone().into(), format!("cell-{i}").into());
        let is_rolling = match roll {
            Some((idx, _, _)) => idx != usize::MAX && idx == i,
            None => false,
        };
        if !is_rolling || reduced {
            cells.push(
                div()
                    .h(px(line_h))
                    .line_height(px(line_h))
                    .child(ch.to_string())
                    .into_any_element(),
            );
            continue;
        }
        let (_, up, u) = roll.unwrap();
        let e = ease.sample(u.clamp(0.0, 1.0));
        // 上滚:双行容器整体上移 e×行高;下滚:下移。
        let old_ch = *ch;
        let new_ch = next_chars.get(i).copied().unwrap_or(old_ch);
        let y = if up { -e } else { e };
        cells.push(
            div()
                .id(id)
                .relative()
                .overflow_hidden()
                .h(px(line_h))
                .child(
                    div()
                        .relative()
                        .flex()
                        .flex_col()
                        .top(px(y * line_h))
                        .child(
                            div()
                                .h(px(line_h))
                                .line_height(px(line_h))
                                .child(old_ch.to_string()),
                        )
                        .child(
                            div()
                                .h(px(line_h))
                                .line_height(px(line_h))
                                .child(new_ch.to_string()),
                        ),
                )
                .into_any_element(),
        );
    }
    div().flex().children(cells).into_any_element()
}

/// Pulse 专用绘制助手(24×24 网格)。
#[derive(Clone, Copy)]
struct PulseCanvas {
    ox: f32,
    oy: f32,
    scale: f32,
}

impl PulseCanvas {
    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 * self.scale));
        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);
        }
    }

    fn fill_polygon(self, pts: &[(f32, f32)], color: Hsla, window: &mut Window) {
        if color.a <= 0.005 || pts.len() < 3 {
            return;
        }
        let mut b = gpui_kit::PathBuilder::fill();
        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);
            }
        }
        b.close();
        if let Ok(path) = b.build() {
            window.paint_path(path, color);
        }
    }
}

/// 心形参数曲线(与 icon_morph 同源拟合)。
fn pulse_heart_points(scale: f32) -> Vec<(f32, f32)> {
    let mut pts = Vec::with_capacity(32);
    for i in 0..32 {
        let t = std::f32::consts::TAU * (i as f32 / 32.0);
        let hx = 16.0 * t.sin().powi(3);
        let hy =
            -(13.0 * t.cos() - 5.0 * (2.0 * t).cos() - 2.0 * (3.0 * t).cos() - (4.0 * t).cos());
        pts.push((12.0 + hx * 0.60 * scale, 11.4 + hy * 0.56 * scale));
    }
    pts
}

/// 五角星轮廓(外接半径 9.2、内半径 3.9,中心 12,12.4)。
fn pulse_star_points(scale: f32) -> Vec<(f32, f32)> {
    let (cx, cy) = (12.0, 12.6);
    let (r_out, r_in) = (9.2 * scale, 3.9 * scale);
    let mut pts = Vec::with_capacity(11);
    for i in 0..10 {
        let a = -std::f32::consts::FRAC_PI_2 + (i as f32) * std::f32::consts::PI / 5.0;
        let r = if i % 2 == 0 { r_out } else { r_in };
        pts.push((cx + r * a.cos(), cy + r * a.sin()));
    }
    pts
}

/// 竖拇指轮廓(Lucide ThumbsUp 近似折线,scale 控制大小)。
fn pulse_thumb_points(scale: f32) -> Vec<(f32, f32)> {
    let o = |v: f32| 12.0 + (v - 12.0) * scale;
    vec![
        (o(7.0), o(11.0)),
        (o(7.0), o(21.0)),
        (o(4.0), o(21.0)),
        (o(4.0), o(11.0)),
        (o(7.0), o(11.0)),
        (o(9.0), o(11.0)),
        (o(9.0), o(4.0)),
        (o(10.2), o(2.8)),
        (o(11.6), o(3.0)),
        (o(13.0), o(5.0)),
        (o(13.0), o(11.0)),
        (o(19.4), o(11.0)),
        (o(20.6), o(12.0)),
        (o(19.8), o(15.4)),
        (o(17.6), o(19.6)),
        (o(16.6), o(21.0)),
        (o(7.0), o(21.0)),
    ]
}

#[allow(clippy::too_many_arguments)]
fn draw_pulse_glyph(
    cv: PulseCanvas,
    glyph: PulseHeartGlyph,
    scale: f32,
    stroke_w: f32,
    color: Hsla,
    liked: bool,
    window: &mut Window,
) {
    // liked 或 solid 模式:填充 + 描边;idle outline:仅描边。
    let fill = if liked || color.a < 0.99 {
        color
    } else {
        Hsla::transparent_black()
    };
    match glyph {
        PulseHeartGlyph::Heart => {
            let pts = pulse_heart_points(scale);
            if liked {
                cv.fill_polygon(&pts, color, window);
            }
            cv.stroke_polyline(stroke_w, &pts, true, color, window);
        }
        PulseHeartGlyph::Star => {
            let pts = pulse_star_points(scale);
            if liked {
                cv.fill_polygon(&pts, color, window);
            }
            cv.stroke_polyline(stroke_w, &pts, true, color, window);
        }
        PulseHeartGlyph::Thumb => {
            let pts = pulse_thumb_points(1.0);
            if liked {
                cv.fill_polygon(&pts, color, window);
            }
            cv.stroke_polyline(stroke_w, &pts, false, color, window);
        }
    }
    let _ = fill;
}

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

    use super::*;

    #[gpui_kit::test]
    fn pulse_heart_theme_defaults_keep_background_transparent(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 = PulseHeartConfig::default().resolve_theme(colors);
                assert_eq!(cfg.pill_color.a, 0.0);
                assert_eq!(cfg.text_color, colors.foreground);
                assert_eq!(cfg.idle_color, colors.text_secondary);
                let custom = PulseHeartConfig {
                    pill_color: colors.danger,
                    text_color: colors.background,
                    ..Default::default()
                }
                .resolve_theme(colors);
                assert_eq!(custom.pill_color, colors.danger);
                assert_eq!(custom.text_color, colors.background);
            }
        });
    }

    struct Host {
        events: Rc<std::cell::RefCell<Vec<(bool, i64)>>>,
        count: i64,
    }

    impl Render for Host {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let events = self.events.clone();
            let count = self.count;
            div().size_full().child(
                PulseHeart::new("ph-test")
                    .count(count)
                    .on_change(cx.listener(move |_, payload: &PulseHeartChange, _, _| {
                        events.borrow_mut().push(*payload);
                    })),
            )
        }
    }

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

    #[gpui_kit::test]
    fn pulse_swell_matches_source_envelope() {
        // 0 处静止,OUT 处缩到最小,末端回弹略越 0。
        assert!((pulse_swell(0.0, 1.7)).abs() < 1e-5);
        assert!((pulse_swell(FLIP_POINT, 1.7) - 1.0).abs() < 1e-4);
        let rebound = pulse_swell(0.75, 1.7);
        assert!(rebound < 0.0, "overshoot 应越过静止点:{rebound}");
        assert!((pulse_swell(1.0, 1.7)).abs() < 1e-4);
        // overshoot=0 不越过静止点(back(c=0) 即 cubic ease-in 收尾)。
        assert!(pulse_swell(0.75, 0.0) <= 1.0 + 1e-4);
        assert!((pulse_swell(1.0, 0.0)).abs() < 1e-4);
    }

    #[gpui_kit::test]
    fn pulse_format_and_roll_plan() {
        assert_eq!(pulse_format_count(1204), "1,204");
        assert_eq!(pulse_format_count(-42), "-42");
        assert_eq!(pulse_format_count(7), "7");
        // 千位分隔下 1203→1204 只有最后一位变化 → 单位滚动。
        let (idx, up) = pulse_roll_plan(1203, 1204);
        assert_ne!(idx, usize::MAX);
        assert!(up);
        // 999→1000 位数变化 → 整体滚动。
        let (idx2, _) = pulse_roll_plan(999, 1000);
        assert_eq!(idx2, usize::MAX);
    }

    #[gpui_kit::test]
    fn pulse_press_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(),
            count: 1204,
        });
        cx.update(|window, cx| {
            window.render_frame(cx);
            let b = window.find("ph-test").bounds();
            let pos = b.center();
            window.pointer_down(pos, gpui_kit::MouseButton::Left, cx);
            window.pointer_up(pos, gpui_kit::MouseButton::Left, cx);
            window.render_frame(cx);
            let ev = events.borrow().clone();
            assert_eq!(ev, vec![(true, 1205)]);
        });
        // run 结束后内部态落定(非受控)。
        assert_eq!(view.read_with(cx, |v, _| v.count), 1204);
    }

    #[gpui_kit::test]
    fn pulse_button_has_button_role(cx: &mut TestAppContext) {
        setup(cx);
        let events = Rc::new(std::cell::RefCell::new(Vec::new()));
        let (_view, cx) = cx.add_window_view(|_, _| Host { events, count: 3 });
        cx.update(|window, cx| {
            window.render_frame(cx);
            assert_eq!(window.find("ph-test").role(), Some(Role::Button));
        });
    }
}