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
//! React Bits Commit 原生移植,© David Haz,MIT + Commons Clause。
//! 独立数据卡片:变更文件摘要 + 文件夹分组折叠 + 增删行统计 + Open diff 回调。
//!
//! 与源码的差异(本地设计):
//! - React/Badge 版本带完整按钮系统;此处头部两枚操作用项目 Button(Ghost 尺寸)与
//!   canvas 旋转 chevron 实现,箭头使用共享 snappy 弹簧并支持中断续接。
//! - 增删色使用主题 `success`/`danger` 语义 token(源码是 emerald/red Tailwind 硬编码),
//!   文件类型图标着色复用 `tree_file_tone_color` 的同一张类型映射表。
//! - 折叠展开为瞬时高度切换 + 150ms 内容淡入(GPUI 无 grid-rows 过渡)。
use std::{cell::RefCell, collections::BTreeMap, rc::Rc};

use arc_motion::{arc_spring, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, hex, oklab_mix};
use gpui_kit::{
    App, ElementId, Hsla, IntoElement, MouseButton, ParentElement, RenderOnce, Role, SharedString,
    Styled, TestSupportExt as _, Window, assets::IconName, base::StyledExt as _, canvas, div,
    prelude::*, px, svg,
};

/// 单条变更文件记录(路径 + 增删行数)。
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommitFile {
    /// 完整仓库相对路径;分组目录取最后一级 `/` 之前的部分。
    pub path: SharedString,
    pub additions: u32,
    pub deletions: u32,
}

impl CommitFile {
    pub fn new(path: impl Into<SharedString>, additions: u32, deletions: u32) -> Self {
        Self {
            path: path.into(),
            additions,
            deletions,
        }
    }

    /// 路径末段文件名(含扩展名)。
    pub fn basename(&self) -> &str {
        self.path.rsplit('/').next().unwrap_or(&self.path)
    }

    /// 所属目录;根级文件返回 `None`。
    pub fn folder(&self) -> Option<&str> {
        let idx = self.path.rfind('/')?;
        Some(&self.path[..idx])
    }
}

type ChangeCallback = Rc<dyn Fn(&mut Window, &mut App)>;

/// 按 `.tsx/.ts → 代码蓝、.md → 文档绿、其余 → 次级灰` 返回图标着色;
/// 复用 TreeView 的文件类型映射表(同一张表,不另起第二套色值)。
pub fn commit_file_icon(name: &str, foreground: Hsla, muted: Hsla) -> (IconName, Hsla) {
    let lower = name.to_ascii_lowercase();
    let icon = if lower.ends_with(".tsx") || lower.ends_with(".jsx") {
        IconName::Atom
    } else if lower.ends_with(".ts") || lower.ends_with(".js") {
        IconName::FileCode
    } else if lower.ends_with(".md") || lower.ends_with(".mdx") {
        IconName::FileText
    } else {
        IconName::File
    };
    let tone = if lower.ends_with(".tsx") || lower.ends_with(".jsx") {
        oklab_mix(hex_sky(), foreground, 0.72)
    } else if lower.ends_with(".md") || lower.ends_with(".mdx") {
        oklab_mix(hex_green(), foreground, 0.74)
    } else if lower.ends_with(".ts") || lower.ends_with(".js") {
        oklab_mix(hex_sky(), foreground, 0.80)
    } else {
        muted
    };
    (icon, tone)
}

// emerald-600(#059669)/emerald-400(#34d399) 的中点近似,供 oklab_mix 与前景混合。
fn hex_sky() -> Hsla {
    hex(0x0ea5e9, 1.0)
}
fn hex_green() -> Hsla {
    hex(0x10b981, 1.0)
}

#[derive(Clone)]
struct CommitInternal {
    expanded: bool,
    content_shown_at: f64,
    collapsed_folders: Vec<SharedString>,
}

// 路径的基础朝向为右箭头;展开态顺时针转 90°,不能用收起时间推导朝向。
fn chevron_target(expanded: bool) -> f32 {
    if expanded { 90.0 } else { 0.0 }
}

fn fade_alpha(elapsed: f64, reduced: bool) -> f32 {
    if reduced {
        return 1.0;
    }
    let t = (elapsed / 0.15).min(1.0);
    // 源码 150ms ease;线性近似足够(淡入本身宽容)。
    t as f32
}

/// 变更摘要卡片(React Bits `commit`):文件按目录分组、目录可折叠、
/// 头部展示总增删统计并可整体收起,Open diff 交宿主处理。
#[derive(IntoElement)]
pub struct Commit {
    id: ElementId,
    files: Vec<CommitFile>,
    heading: Option<SharedString>,
    open_label: SharedString,
    expanded: Option<bool>,
    on_expanded_change: Option<ChangeCallback>,
    on_open_diff: Option<ChangeCallback>,
}

impl Commit {
    pub fn new(id: impl Into<ElementId>, files: impl IntoIterator<Item = CommitFile>) -> Self {
        Self {
            id: id.into(),
            files: files.into_iter().collect(),
            heading: None,
            open_label: "Open diff".into(),
            expanded: None,
            on_expanded_change: None,
            on_open_diff: None,
        }
    }

    /// 覆盖默认的「N changed files」标题。
    pub fn heading(mut self, heading: impl Into<SharedString>) -> Self {
        self.heading = Some(heading.into());
        self
    }

    /// Open diff 按钮文案。
    pub fn open_label(mut self, label: impl Into<SharedString>) -> Self {
        self.open_label = label.into();
        self
    }

    /// 受控展开态;缺省走内部状态。
    pub fn expanded(mut self, expanded: bool) -> Self {
        self.expanded = Some(expanded);
        self
    }

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

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

    fn totals(&self) -> (u32, u32) {
        self.files
            .iter()
            .fold((0, 0), |(a, d), f| (a + f.additions, d + f.deletions))
    }
}

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

        let state_cell = window
            .use_keyed_state(
                ElementId::NamedChild(self.id.clone().into(), SharedString::from("commit-state")),
                cx,
                |_, _| {
                    Rc::new(RefCell::new(CommitInternal {
                        expanded: true,
                        content_shown_at: now - 1.0,
                        collapsed_folders: Vec::new(),
                    }))
                },
            )
            .read(cx)
            .clone();

        let expanded = self
            .expanded
            .unwrap_or_else(|| state_cell.borrow().expanded);
        let collapsed: Vec<SharedString> = state_cell.borrow().collapsed_folders.clone();

        // 内容重挂时刷新淡入锚点:受控切换或内部切换都走这里。
        {
            let mut st = state_cell.borrow_mut();
            if st.expanded != expanded {
                st.expanded = expanded;
                st.content_shown_at = now;
            }
        }
        let fade_elapsed = (now - state_cell.borrow().content_shown_at).max(0.0);
        if !reduced && fade_elapsed < 0.2 {
            window.request_animation_frame();
        }
        // 每个实例、目录独享稳定动画通道,反向点击时从当前角度续接。
        let header_chevron_angle = arc_spring(
            (self.id.clone(), "chevron"),
            chevron_target(expanded),
            cx.arc_theme().motion.spring.snappy,
            window,
            cx,
        );

        let (add_total, del_total) = self.totals();
        let file_count = self.files.len();
        let heading = self.heading.unwrap_or_else(|| {
            SharedString::from(format!(
                "{file_count} changed {}",
                if file_count == 1 { "file" } else { "files" }
            ))
        });

        // 按目录分组;根级文件保持输入顺序放最后(BTreeMap 保证目录名稳定排序)。
        let mut groups: BTreeMap<&str, Vec<&CommitFile>> = BTreeMap::new();
        let mut root_files: Vec<&CommitFile> = Vec::new();
        for file in &self.files {
            match file.folder() {
                Some(folder) => groups.entry(folder).or_default().push(file),
                None => root_files.push(file),
            }
        }

        let plus_color = colors.success;
        let minus_color = colors.danger;
        let text_fg = colors.text_secondary;
        let file_fg = oklab_mix(colors.foreground, colors.text_secondary, 0.35);
        let fade = fade_alpha(fade_elapsed, reduced);
        let open_diff = self.on_open_diff.clone();
        let has_diff_cb = open_diff.is_some();

        // ── 头部 ──
        let header_focus = window
            .use_keyed_state(
                ElementId::NamedChild(self.id.clone().into(), "header-focus".into()),
                cx,
                |_, cx| cx.focus_handle(),
            )
            .read(cx)
            .clone();
        let header_mouse_focus = header_focus.clone();
        let diff_focus = window
            .use_keyed_state(
                ElementId::NamedChild(self.id.clone().into(), "diff-focus".into()),
                cx,
                |_, cx| cx.focus_handle(),
            )
            .read(cx)
            .clone();
        let diff_mouse_focus = diff_focus.clone();
        let exp_toggle_state = state_cell.clone();
        let on_exp_cb = self.on_expanded_change.clone();
        let controlled = self.expanded.is_some();
        let toggle: ChangeCallback = Rc::new(move |window, cx| {
            if !controlled {
                exp_toggle_state.borrow_mut().expanded = !expanded;
            }
            exp_toggle_state.borrow_mut().content_shown_at = motion_now(cx);
            if let Some(ref cb) = on_exp_cb {
                cb(window, cx);
            }
            window.refresh();
        });
        let toggle_key = toggle.clone();
        let header = div()
            .flex()
            .flex_wrap()
            .items_center()
            .gap_x(Spacing::S3)
            .gap_y(Spacing::S1)
            .px(Spacing::S4)
            .py(Spacing::S3)
            .bg(oklab_mix(colors.surface_raised, colors.surface, 0.75))
            .border_b_1()
            .border_color(colors.border_subtle)
            .child(
                div()
                    .text_size(Typography::TEXT_SM)
                    .font_semibold()
                    .text_color(colors.foreground)
                    .child(heading.clone()),
            )
            .child(
                div()
                    .flex()
                    .gap(Spacing::S1)
                    .text_size(Typography::TEXT_SM)
                    .child(
                        div()
                            .text_color(plus_color)
                            .child(SharedString::from(format!("+{add_total}"))),
                    )
                    .child(
                        div()
                            .text_color(minus_color)
                            .child(SharedString::from(format!("\u{2212}{del_total}"))),
                    ),
            )
            .child(
                div()
                    .ml_auto()
                    .flex()
                    .items_center()
                    .gap(Spacing::S2)
                    // 折叠 chevron:整卡展开/收起(角度在渲染期采样,paint 内不取时钟)
                    .child(
                        div()
                            .id(ElementId::NamedChild(
                                self.id.clone().into(),
                                "chevron".into(),
                            ))
                            .test_support()
                            .role(Role::Button)
                            .aria_label("Toggle changed files")
                            .aria_expanded(expanded)
                            .track_focus(&header_focus)
                            .on_key_down(move |event, window, cx| {
                                if matches!(event.keystroke.key.as_str(), "enter" | "space") {
                                    toggle_key(window, cx);
                                    cx.stop_propagation();
                                }
                            })
                            .size(px(24.0))
                            .flex()
                            .items_center()
                            .justify_center()
                            .cursor_pointer()
                            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                                header_mouse_focus.focus(window, cx);
                                toggle(window, cx);
                                cx.stop_propagation();
                            })
                            .child(
                                canvas(
                                    move |_, _, _| {},
                                    move |bounds, _, window, _| {
                                        let cx_p = f32::from(bounds.origin.x)
                                            + f32::from(bounds.size.width) * 0.5;
                                        let cy_p = f32::from(bounds.origin.y)
                                            + f32::from(bounds.size.height) * 0.5;
                                        paint_chevron(
                                            cx_p,
                                            cy_p,
                                            header_chevron_angle,
                                            colors.text_muted,
                                            window,
                                        );
                                    },
                                )
                                .size_full(),
                            ),
                    )
                    // Open diff:交给宿主;无回调时降透明度并禁点
                    .when(has_diff_cb, |el| {
                        let cb = open_diff.clone().unwrap();
                        el.child(
                            div()
                                .id(ElementId::NamedChild(
                                    self.id.clone().into(),
                                    "open-diff".into(),
                                ))
                                .test_support()
                                .role(Role::Button)
                                .aria_label(self.open_label.clone())
                                .track_focus(&diff_focus)
                                .on_key_down({
                                    let cb = cb.clone();
                                    move |event, window, cx| {
                                        if matches!(event.keystroke.key.as_str(), "enter" | "space")
                                        {
                                            cb(window, cx);
                                            cx.stop_propagation();
                                        }
                                    }
                                })
                                .flex()
                                .items_center()
                                .gap_1()
                                .h(px(28.0))
                                .px(Spacing::S2)
                                .rounded(Radii::CONTROL)
                                .text_size(Typography::TEXT_SM)
                                .text_color(colors.text_secondary)
                                .cursor_pointer()
                                .hover(move |s| {
                                    s.bg(oklab_mix(colors.surface_muted, colors.surface, 0.72))
                                        .text_color(colors.foreground)
                                })
                                .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                                    diff_mouse_focus.focus(window, cx);
                                    cb(window, cx);
                                    cx.stop_propagation();
                                })
                                .child(
                                    svg()
                                        .path(IconName::FileDiff.path())
                                        .size(px(14.0))
                                        .text_color(colors.text_muted),
                                )
                                .child(self.open_label.clone()),
                        )
                    })
                    .when(!has_diff_cb, |el| {
                        el.child(
                            div()
                                .flex()
                                .items_center()
                                .gap_1()
                                .h(px(28.0))
                                .px(Spacing::S2)
                                .rounded(Radii::CONTROL)
                                .text_size(Typography::TEXT_SM)
                                .opacity(0.5)
                                .text_color(colors.text_secondary)
                                .child(
                                    svg()
                                        .path(IconName::FileDiff.path())
                                        .size(px(14.0))
                                        .text_color(colors.text_muted),
                                )
                                .child(self.open_label.clone()),
                        )
                    }),
            );

        // ── 文件列表 ──
        let mut list = div().flex().flex_col();
        if expanded {
            let content = div().flex().flex_col().py(Spacing::S2).opacity(fade).when(
                self.files.is_empty(),
                |el| {
                    el.child(
                        div()
                            .px(Spacing::S4)
                            .py(Spacing::S2)
                            .text_size(Typography::TEXT_XS)
                            .text_color(colors.text_muted)
                            .child("No changed files."),
                    )
                },
            );

            let mut rows = div().flex().flex_col();
            for (folder, group_files) in &groups {
                let folder_id: SharedString = SharedString::from(*folder);
                let is_collapsed = collapsed.contains(&folder_id);
                let folder_angle = arc_spring(
                    (
                        ElementId::NamedChild(self.id.clone().into(), folder_id.clone()),
                        "chevron",
                    ),
                    chevron_target(!is_collapsed),
                    cx.arc_theme().motion.spring.snappy,
                    window,
                    cx,
                );
                let (f_add, f_del) = group_files
                    .iter()
                    .fold((0u32, 0u32), |(a, d), f| (a + f.additions, d + f.deletions));

                let folder_focus = window
                    .use_keyed_state(
                        ElementId::NamedChild(
                            ElementId::NamedChild(self.id.clone().into(), folder_id.clone()).into(),
                            "focus".into(),
                        ),
                        cx,
                        |_, cx| cx.focus_handle(),
                    )
                    .read(cx)
                    .clone();
                let folder_mouse_focus = folder_focus.clone();
                let folder_state = state_cell.clone();
                let folder_name = folder_id.clone();
                let toggle_folder: ChangeCallback = Rc::new(move |window, _| {
                    let mut st = folder_state.borrow_mut();
                    if st.collapsed_folders.contains(&folder_name) {
                        st.collapsed_folders.retain(|f| f != &folder_name);
                    } else {
                        st.collapsed_folders.push(folder_name.clone());
                    }
                    drop(st);
                    window.refresh();
                });
                let toggle_folder_key = toggle_folder.clone();
                let folder_header = div()
                    .id(ElementId::NamedChild(
                        self.id.clone().into(),
                        SharedString::from(format!("folder-{folder}")),
                    ))
                    .test_support()
                    .role(Role::Button)
                    .aria_label(SharedString::from(*folder))
                    .aria_expanded(!is_collapsed)
                    .track_focus(&folder_focus)
                    .on_key_down(move |event, window, cx| {
                        if matches!(event.keystroke.key.as_str(), "enter" | "space") {
                            toggle_folder_key(window, cx);
                            cx.stop_propagation();
                        }
                    })
                    .flex()
                    .items_center()
                    .gap_2()
                    .w_full()
                    .h(px(32.0))
                    .px(Spacing::S4)
                    .text_size(Typography::TEXT_SM)
                    .text_color(text_fg)
                    .cursor_pointer()
                    .hover(move |s| s.bg(oklab_mix(colors.surface_muted, colors.surface, 0.80)))
                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
                        folder_mouse_focus.focus(window, cx);
                        toggle_folder(window, cx);
                        cx.stop_propagation();
                    })
                    .child(
                        div()
                            .size(px(14.0))
                            .flex()
                            .items_center()
                            .justify_center()
                            .child(
                                canvas(
                                    move |_, _, _| {},
                                    move |bounds, _, window, _| {
                                        let cx_p = f32::from(bounds.origin.x)
                                            + f32::from(bounds.size.width) * 0.5;
                                        let cy_p = f32::from(bounds.origin.y)
                                            + f32::from(bounds.size.height) * 0.5;
                                        paint_chevron(
                                            cx_p,
                                            cy_p,
                                            folder_angle,
                                            colors.text_muted,
                                            window,
                                        );
                                    },
                                )
                                .size_full(),
                            ),
                    )
                    .child(
                        svg()
                            .path(IconName::Folder.path())
                            .size(px(16.0))
                            .flex_shrink_0()
                            .text_color(colors.text_muted),
                    )
                    .child(
                        div()
                            .flex_1()
                            .min_w_0()
                            .truncate()
                            .text_color(text_fg)
                            .child(SharedString::from(*folder)),
                    )
                    .child(change_counts(f_add, f_del, plus_color, minus_color));

                rows = rows.child(folder_header);
                if !is_collapsed {
                    for file in group_files {
                        rows = rows.child(file_row(
                            self.id.clone(),
                            file,
                            true,
                            file_fg,
                            plus_color,
                            minus_color,
                            colors,
                        ));
                    }
                }
            }
            for file in root_files {
                rows = rows.child(file_row(
                    self.id.clone(),
                    file,
                    false,
                    file_fg,
                    plus_color,
                    minus_color,
                    colors,
                ));
            }

            list = list.child(content.child(rows));
        }

        div()
            .id(self.id.clone())
            .test_support()
            .role(Role::Region)
            .overflow_hidden()
            .w_full()
            .min_w_0()
            .rounded(Radii::SURFACE)
            .border_1()
            .border_color(colors.border)
            .bg(colors.surface_raised)
            .text_size(Typography::TEXT_SM)
            .text_color(text_fg)
            .child(header)
            .child(list)
    }
}

#[allow(clippy::too_many_arguments)]
fn file_row(
    card_id: ElementId,
    file: &CommitFile,
    nested: bool,
    file_fg: Hsla,
    plus: Hsla,
    minus: Hsla,
    colors: arc_tokens::ArcColors,
) -> impl IntoElement {
    let name = file.basename().to_string();
    let (icon, tone) = commit_file_icon(&name, colors.foreground, colors.text_muted);
    div()
        .id(ElementId::NamedChild(
            card_id.into(),
            SharedString::from(format!("file-{}", file.path)),
        ))
        .test_support()
        .flex()
        .items_center()
        .gap_2()
        .w_full()
        .min_h(px(32.0))
        .pl(if nested { Spacing::S12 } else { Spacing::S8 })
        .pr(Spacing::S4)
        .text_size(Typography::TEXT_SM)
        .child(
            svg()
                .path(icon.path())
                .size(px(16.0))
                .flex_shrink_0()
                .text_color(tone),
        )
        .child(
            div()
                .flex_1()
                .min_w_0()
                .truncate()
                .text_color(file_fg)
                .child(SharedString::from(name)),
        )
        .child(change_counts(file.additions, file.deletions, plus, minus))
}

fn change_counts(add: u32, del: u32, plus: Hsla, minus: Hsla) -> gpui_kit::Div {
    div()
        .ml_auto()
        .flex_shrink_0()
        .flex()
        .gap(Spacing::S4)
        .text_size(Typography::TEXT_XS)
        .child(
            div()
                .text_color(plus)
                .child(SharedString::from(format!("+{add}"))),
        )
        .child(
            div()
                .text_color(minus)
                .child(SharedString::from(format!("\u{2212}{del}"))),
        )
}

fn paint_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
    let angle = angle_deg.to_radians();
    let cos = angle.cos();
    let sin = angle.sin();
    let rot = |dx: f32, dy: f32| {
        gpui_kit::point(px(cx + dx * cos - dy * sin), px(cy + dx * sin + dy * cos))
    };
    let mut pb = gpui_kit::PathBuilder::stroke(px(1.75));
    pb.move_to(rot(-2.6, -4.2));
    pb.line_to(rot(2.6, 0.0));
    pb.line_to(rot(-2.6, 4.2));
    if let Ok(path) = pb.build() {
        window.paint_path(path, color);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};

    struct Host {
        controlled: bool,
        notifications: usize,
    }

    impl Render for Host {
        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let host = cx.entity().clone();
            let mut first = Commit::new(
                "commit-a",
                [
                    CommitFile::new("src/a.ts", 1, 0),
                    CommitFile::new("src-b/c.ts", 2, 1),
                    CommitFile::new("src/b-c.ts", 3, 0),
                ],
            )
            .on_expanded_change(move |_, cx| {
                host.update(cx, |this, cx| {
                    this.notifications += 1;
                    cx.notify();
                });
            });
            if self.controlled {
                first = first.expanded(false);
            }
            div()
                .w_full()
                .flex()
                .flex_col()
                .child(first)
                .child(Commit::new("commit-b", [CommitFile::new("src/a.ts", 1, 0)]))
        }
    }

    fn part(card: &str, name: &str) -> ElementId {
        ElementId::NamedChild(
            ElementId::from(card.to_string()).into(),
            name.to_string().into(),
        )
    }

    fn init(cx: &mut TestAppContext) {
        cx.update(|cx| {
            gpui_kit::init(cx);
            arc_tokens::install_arc_theme(
                arc_tokens::ThemeMode::Light,
                arc_tokens::Accent::Neutral,
                cx,
            );
            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
        });
    }

    #[gpui_kit::test]
    fn commit_folders_and_instances_keep_independent_state(cx: &mut TestAppContext) {
        init(cx);
        let (_, window) = cx.add_window_view(|_, _| Host {
            controlled: false,
            notifications: 0,
        });
        window.update(|w, cx| {
            w.render_frame(cx);
            // 完整路径保留,避免 src-b/c.ts 与 src/b-c.ts 的 id 冲突。
            assert!(w.try_find(part("commit-a", "file-src-b/c.ts")).is_some());
            assert!(w.try_find(part("commit-a", "file-src/b-c.ts")).is_some());
            w.click(part("commit-a", "folder-src"), cx);
            assert!(w.try_find(part("commit-a", "file-src/a.ts")).is_none());
            assert!(w.try_find(part("commit-a", "file-src-b/c.ts")).is_some());
            assert!(w.try_find(part("commit-b", "file-src/a.ts")).is_some());
            w.click(part("commit-a", "chevron"), cx);
            assert!(w.try_find(part("commit-a", "folder-src")).is_none());
            w.click(part("commit-a", "chevron"), cx);
            assert!(
                w.try_find(part("commit-a", "file-src/a.ts")).is_none(),
                "整卡重开保留目录折叠"
            );
            w.click(part("commit-a", "folder-src"), cx);
            assert!(w.try_find(part("commit-a", "file-src/a.ts")).is_some());
            w.press("space", cx);
            assert!(
                w.try_find(part("commit-a", "file-src/a.ts")).is_none(),
                "空格收起聚焦目录"
            );
            w.press("enter", cx);
            assert!(
                w.try_find(part("commit-a", "file-src/a.ts")).is_some(),
                "回车展开聚焦目录"
            );
        });
    }

    #[gpui_kit::test]
    fn commit_controlled_state_does_not_mutate_without_host_update(cx: &mut TestAppContext) {
        init(cx);
        let (view, window) = cx.add_window_view(|_, _| Host {
            controlled: true,
            notifications: 0,
        });
        window.update(|w, cx| {
            w.render_frame(cx);
            for expected in 1..=2 {
                w.click(part("commit-a", "chevron"), cx);
                assert!(w.try_find(part("commit-a", "folder-src")).is_none());
                assert_eq!(view.read(cx).notifications, expected);
            }
        });
    }

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

    #[test]
    fn commit_groups_files_by_folder_with_stable_order() {
        let files = vec![
            CommitFile::new("src/components/ai/permission-grant.tsx", 1, 1),
            CommitFile::new("DESIGN.md", 1, 0),
            CommitFile::new("src/auth/verify.ts", 3, 2),
        ];
        let mut groups: BTreeMap<&str, Vec<&CommitFile>> = BTreeMap::new();
        let mut root = Vec::new();
        for f in &files {
            match f.folder() {
                Some(folder) => groups.entry(folder).or_default().push(f),
                None => root.push(f),
            }
        }
        let keys: Vec<_> = groups.keys().copied().collect();
        assert_eq!(keys, vec!["src/auth", "src/components/ai"]);
        assert_eq!(root.len(), 1);
        assert_eq!(root[0].basename(), "DESIGN.md");
        let grant = groups["src/components/ai"][0];
        assert_eq!(grant.basename(), "permission-grant.tsx");
    }

    #[test]
    fn commit_totals_and_headings() {
        let card = Commit::new(
            "t",
            [
                CommitFile::new("a.rs", 2, 1),
                CommitFile::new("b/c.md", 0, 3),
            ],
        );
        assert_eq!(card.totals(), (2, 4));
        // 默认标题在 render 内生成;这里验证复数规则与源码一致。
        let one = Commit::new("t1", [CommitFile::new("a.rs", 1, 0)]);
        assert_eq!(one.files.len(), 1);
    }

    #[test]
    fn commit_icon_tone_maps_by_extension() {
        //tsx → Atom + sky 调;md → FileText + green 调;其他 → File + muted。
        assert!(matches!(
            commit_file_icon("App.tsx", Hsla::default(), Hsla::default()).0,
            IconName::Atom
        ));
        assert!(matches!(
            commit_file_icon("README.md", Hsla::default(), Hsla::default()).0,
            IconName::FileText
        ));
        assert!(matches!(
            commit_file_icon("main.rs", Hsla::default(), Hsla::default()).0,
            IconName::File
        ));
    }

    #[test]
    fn commit_chevron_angle_and_fade_are_bounded() {
        let reduced = true;
        assert!(close(chevron_target(false), 0.0));
        assert!(close(chevron_target(true), 90.0));
        assert!(close(fade_alpha(5.0, reduced), 1.0));
        let normal = false;
        assert!(fade_alpha(0.075, normal) > 0.0 && fade_alpha(0.075, normal) < 1.0);
        assert!(close(fade_alpha(0.2, normal), 1.0));
    }
}