Skip to main content

arc_ui/data/
commit.rs

1//! React Bits Commit 原生移植,© David Haz,MIT + Commons Clause。
2//! 独立数据卡片:变更文件摘要 + 文件夹分组折叠 + 增删行统计 + Open diff 回调。
3//!
4//! 与源码的差异(本地设计):
5//! - React/Badge 版本带完整按钮系统;此处头部两枚操作用项目 Button(Ghost 尺寸)与
6//!   canvas 旋转 chevron 实现,箭头使用共享 snappy 弹簧并支持中断续接。
7//! - 增删色使用主题 `success`/`danger` 语义 token(源码是 emerald/red Tailwind 硬编码),
8//!   文件类型图标着色复用 `tree_file_tone_color` 的同一张类型映射表。
9//! - 折叠展开为瞬时高度切换 + 150ms 内容淡入(GPUI 无 grid-rows 过渡)。
10use std::{cell::RefCell, collections::BTreeMap, rc::Rc};
11
12use arc_motion::{arc_spring, is_reduced_motion, motion_now};
13use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography, hex, oklab_mix};
14use gpui_kit::{
15    App, ElementId, Hsla, IntoElement, MouseButton, ParentElement, RenderOnce, Role, SharedString,
16    Styled, TestSupportExt as _, Window, assets::IconName, base::StyledExt as _, canvas, div,
17    prelude::*, px, svg,
18};
19
20/// 单条变更文件记录(路径 + 增删行数)。
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct CommitFile {
23    /// 完整仓库相对路径;分组目录取最后一级 `/` 之前的部分。
24    pub path: SharedString,
25    pub additions: u32,
26    pub deletions: u32,
27}
28
29impl CommitFile {
30    pub fn new(path: impl Into<SharedString>, additions: u32, deletions: u32) -> Self {
31        Self {
32            path: path.into(),
33            additions,
34            deletions,
35        }
36    }
37
38    /// 路径末段文件名(含扩展名)。
39    pub fn basename(&self) -> &str {
40        self.path.rsplit('/').next().unwrap_or(&self.path)
41    }
42
43    /// 所属目录;根级文件返回 `None`。
44    pub fn folder(&self) -> Option<&str> {
45        let idx = self.path.rfind('/')?;
46        Some(&self.path[..idx])
47    }
48}
49
50type ChangeCallback = Rc<dyn Fn(&mut Window, &mut App)>;
51
52/// 按 `.tsx/.ts → 代码蓝、.md → 文档绿、其余 → 次级灰` 返回图标着色;
53/// 复用 TreeView 的文件类型映射表(同一张表,不另起第二套色值)。
54pub fn commit_file_icon(name: &str, foreground: Hsla, muted: Hsla) -> (IconName, Hsla) {
55    let lower = name.to_ascii_lowercase();
56    let icon = if lower.ends_with(".tsx") || lower.ends_with(".jsx") {
57        IconName::Atom
58    } else if lower.ends_with(".ts") || lower.ends_with(".js") {
59        IconName::FileCode
60    } else if lower.ends_with(".md") || lower.ends_with(".mdx") {
61        IconName::FileText
62    } else {
63        IconName::File
64    };
65    let tone = if lower.ends_with(".tsx") || lower.ends_with(".jsx") {
66        oklab_mix(hex_sky(), foreground, 0.72)
67    } else if lower.ends_with(".md") || lower.ends_with(".mdx") {
68        oklab_mix(hex_green(), foreground, 0.74)
69    } else if lower.ends_with(".ts") || lower.ends_with(".js") {
70        oklab_mix(hex_sky(), foreground, 0.80)
71    } else {
72        muted
73    };
74    (icon, tone)
75}
76
77// emerald-600(#059669)/emerald-400(#34d399) 的中点近似,供 oklab_mix 与前景混合。
78fn hex_sky() -> Hsla {
79    hex(0x0ea5e9, 1.0)
80}
81fn hex_green() -> Hsla {
82    hex(0x10b981, 1.0)
83}
84
85#[derive(Clone)]
86struct CommitInternal {
87    expanded: bool,
88    content_shown_at: f64,
89    collapsed_folders: Vec<SharedString>,
90}
91
92// 路径的基础朝向为右箭头;展开态顺时针转 90°,不能用收起时间推导朝向。
93fn chevron_target(expanded: bool) -> f32 {
94    if expanded { 90.0 } else { 0.0 }
95}
96
97fn fade_alpha(elapsed: f64, reduced: bool) -> f32 {
98    if reduced {
99        return 1.0;
100    }
101    let t = (elapsed / 0.15).min(1.0);
102    // 源码 150ms ease;线性近似足够(淡入本身宽容)。
103    t as f32
104}
105
106/// 变更摘要卡片(React Bits `commit`):文件按目录分组、目录可折叠、
107/// 头部展示总增删统计并可整体收起,Open diff 交宿主处理。
108#[derive(IntoElement)]
109pub struct Commit {
110    id: ElementId,
111    files: Vec<CommitFile>,
112    heading: Option<SharedString>,
113    open_label: SharedString,
114    expanded: Option<bool>,
115    on_expanded_change: Option<ChangeCallback>,
116    on_open_diff: Option<ChangeCallback>,
117}
118
119impl Commit {
120    pub fn new(id: impl Into<ElementId>, files: impl IntoIterator<Item = CommitFile>) -> Self {
121        Self {
122            id: id.into(),
123            files: files.into_iter().collect(),
124            heading: None,
125            open_label: "Open diff".into(),
126            expanded: None,
127            on_expanded_change: None,
128            on_open_diff: None,
129        }
130    }
131
132    /// 覆盖默认的「N changed files」标题。
133    pub fn heading(mut self, heading: impl Into<SharedString>) -> Self {
134        self.heading = Some(heading.into());
135        self
136    }
137
138    /// Open diff 按钮文案。
139    pub fn open_label(mut self, label: impl Into<SharedString>) -> Self {
140        self.open_label = label.into();
141        self
142    }
143
144    /// 受控展开态;缺省走内部状态。
145    pub fn expanded(mut self, expanded: bool) -> Self {
146        self.expanded = Some(expanded);
147        self
148    }
149
150    pub fn on_expanded_change(mut self, cb: impl Fn(&mut Window, &mut App) + 'static) -> Self {
151        self.on_expanded_change = Some(Rc::new(cb));
152        self
153    }
154
155    pub fn on_open_diff(mut self, cb: impl Fn(&mut Window, &mut App) + 'static) -> Self {
156        self.on_open_diff = Some(Rc::new(cb));
157        self
158    }
159
160    fn totals(&self) -> (u32, u32) {
161        self.files
162            .iter()
163            .fold((0, 0), |(a, d), f| (a + f.additions, d + f.deletions))
164    }
165}
166
167impl RenderOnce for Commit {
168    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
169        let colors = cx.arc_theme().colors;
170        let reduced = is_reduced_motion(cx);
171        let now = motion_now(cx);
172
173        let state_cell = window
174            .use_keyed_state(
175                ElementId::NamedChild(self.id.clone().into(), SharedString::from("commit-state")),
176                cx,
177                |_, _| {
178                    Rc::new(RefCell::new(CommitInternal {
179                        expanded: true,
180                        content_shown_at: now - 1.0,
181                        collapsed_folders: Vec::new(),
182                    }))
183                },
184            )
185            .read(cx)
186            .clone();
187
188        let expanded = self
189            .expanded
190            .unwrap_or_else(|| state_cell.borrow().expanded);
191        let collapsed: Vec<SharedString> = state_cell.borrow().collapsed_folders.clone();
192
193        // 内容重挂时刷新淡入锚点:受控切换或内部切换都走这里。
194        {
195            let mut st = state_cell.borrow_mut();
196            if st.expanded != expanded {
197                st.expanded = expanded;
198                st.content_shown_at = now;
199            }
200        }
201        let fade_elapsed = (now - state_cell.borrow().content_shown_at).max(0.0);
202        if !reduced && fade_elapsed < 0.2 {
203            window.request_animation_frame();
204        }
205        // 每个实例、目录独享稳定动画通道,反向点击时从当前角度续接。
206        let header_chevron_angle = arc_spring(
207            (self.id.clone(), "chevron"),
208            chevron_target(expanded),
209            cx.arc_theme().motion.spring.snappy,
210            window,
211            cx,
212        );
213
214        let (add_total, del_total) = self.totals();
215        let file_count = self.files.len();
216        let heading = self.heading.unwrap_or_else(|| {
217            SharedString::from(format!(
218                "{file_count} changed {}",
219                if file_count == 1 { "file" } else { "files" }
220            ))
221        });
222
223        // 按目录分组;根级文件保持输入顺序放最后(BTreeMap 保证目录名稳定排序)。
224        let mut groups: BTreeMap<&str, Vec<&CommitFile>> = BTreeMap::new();
225        let mut root_files: Vec<&CommitFile> = Vec::new();
226        for file in &self.files {
227            match file.folder() {
228                Some(folder) => groups.entry(folder).or_default().push(file),
229                None => root_files.push(file),
230            }
231        }
232
233        let plus_color = colors.success;
234        let minus_color = colors.danger;
235        let text_fg = colors.text_secondary;
236        let file_fg = oklab_mix(colors.foreground, colors.text_secondary, 0.35);
237        let fade = fade_alpha(fade_elapsed, reduced);
238        let open_diff = self.on_open_diff.clone();
239        let has_diff_cb = open_diff.is_some();
240
241        // ── 头部 ──
242        let header_focus = window
243            .use_keyed_state(
244                ElementId::NamedChild(self.id.clone().into(), "header-focus".into()),
245                cx,
246                |_, cx| cx.focus_handle(),
247            )
248            .read(cx)
249            .clone();
250        let header_mouse_focus = header_focus.clone();
251        let diff_focus = window
252            .use_keyed_state(
253                ElementId::NamedChild(self.id.clone().into(), "diff-focus".into()),
254                cx,
255                |_, cx| cx.focus_handle(),
256            )
257            .read(cx)
258            .clone();
259        let diff_mouse_focus = diff_focus.clone();
260        let exp_toggle_state = state_cell.clone();
261        let on_exp_cb = self.on_expanded_change.clone();
262        let controlled = self.expanded.is_some();
263        let toggle: ChangeCallback = Rc::new(move |window, cx| {
264            if !controlled {
265                exp_toggle_state.borrow_mut().expanded = !expanded;
266            }
267            exp_toggle_state.borrow_mut().content_shown_at = motion_now(cx);
268            if let Some(ref cb) = on_exp_cb {
269                cb(window, cx);
270            }
271            window.refresh();
272        });
273        let toggle_key = toggle.clone();
274        let header = div()
275            .flex()
276            .flex_wrap()
277            .items_center()
278            .gap_x(Spacing::S3)
279            .gap_y(Spacing::S1)
280            .px(Spacing::S4)
281            .py(Spacing::S3)
282            .bg(oklab_mix(colors.surface_raised, colors.surface, 0.75))
283            .border_b_1()
284            .border_color(colors.border_subtle)
285            .child(
286                div()
287                    .text_size(Typography::TEXT_SM)
288                    .font_semibold()
289                    .text_color(colors.foreground)
290                    .child(heading.clone()),
291            )
292            .child(
293                div()
294                    .flex()
295                    .gap(Spacing::S1)
296                    .text_size(Typography::TEXT_SM)
297                    .child(
298                        div()
299                            .text_color(plus_color)
300                            .child(SharedString::from(format!("+{add_total}"))),
301                    )
302                    .child(
303                        div()
304                            .text_color(minus_color)
305                            .child(SharedString::from(format!("\u{2212}{del_total}"))),
306                    ),
307            )
308            .child(
309                div()
310                    .ml_auto()
311                    .flex()
312                    .items_center()
313                    .gap(Spacing::S2)
314                    // 折叠 chevron:整卡展开/收起(角度在渲染期采样,paint 内不取时钟)
315                    .child(
316                        div()
317                            .id(ElementId::NamedChild(
318                                self.id.clone().into(),
319                                "chevron".into(),
320                            ))
321                            .test_support()
322                            .role(Role::Button)
323                            .aria_label("Toggle changed files")
324                            .aria_expanded(expanded)
325                            .track_focus(&header_focus)
326                            .on_key_down(move |event, window, cx| {
327                                if matches!(event.keystroke.key.as_str(), "enter" | "space") {
328                                    toggle_key(window, cx);
329                                    cx.stop_propagation();
330                                }
331                            })
332                            .size(px(24.0))
333                            .flex()
334                            .items_center()
335                            .justify_center()
336                            .cursor_pointer()
337                            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
338                                header_mouse_focus.focus(window, cx);
339                                toggle(window, cx);
340                                cx.stop_propagation();
341                            })
342                            .child(
343                                canvas(
344                                    move |_, _, _| {},
345                                    move |bounds, _, window, _| {
346                                        let cx_p = f32::from(bounds.origin.x)
347                                            + f32::from(bounds.size.width) * 0.5;
348                                        let cy_p = f32::from(bounds.origin.y)
349                                            + f32::from(bounds.size.height) * 0.5;
350                                        paint_chevron(
351                                            cx_p,
352                                            cy_p,
353                                            header_chevron_angle,
354                                            colors.text_muted,
355                                            window,
356                                        );
357                                    },
358                                )
359                                .size_full(),
360                            ),
361                    )
362                    // Open diff:交给宿主;无回调时降透明度并禁点
363                    .when(has_diff_cb, |el| {
364                        let cb = open_diff.clone().unwrap();
365                        el.child(
366                            div()
367                                .id(ElementId::NamedChild(
368                                    self.id.clone().into(),
369                                    "open-diff".into(),
370                                ))
371                                .test_support()
372                                .role(Role::Button)
373                                .aria_label(self.open_label.clone())
374                                .track_focus(&diff_focus)
375                                .on_key_down({
376                                    let cb = cb.clone();
377                                    move |event, window, cx| {
378                                        if matches!(event.keystroke.key.as_str(), "enter" | "space")
379                                        {
380                                            cb(window, cx);
381                                            cx.stop_propagation();
382                                        }
383                                    }
384                                })
385                                .flex()
386                                .items_center()
387                                .gap_1()
388                                .h(px(28.0))
389                                .px(Spacing::S2)
390                                .rounded(Radii::CONTROL)
391                                .text_size(Typography::TEXT_SM)
392                                .text_color(colors.text_secondary)
393                                .cursor_pointer()
394                                .hover(move |s| {
395                                    s.bg(oklab_mix(colors.surface_muted, colors.surface, 0.72))
396                                        .text_color(colors.foreground)
397                                })
398                                .on_mouse_down(MouseButton::Left, move |_, window, cx| {
399                                    diff_mouse_focus.focus(window, cx);
400                                    cb(window, cx);
401                                    cx.stop_propagation();
402                                })
403                                .child(
404                                    svg()
405                                        .path(IconName::FileDiff.path())
406                                        .size(px(14.0))
407                                        .text_color(colors.text_muted),
408                                )
409                                .child(self.open_label.clone()),
410                        )
411                    })
412                    .when(!has_diff_cb, |el| {
413                        el.child(
414                            div()
415                                .flex()
416                                .items_center()
417                                .gap_1()
418                                .h(px(28.0))
419                                .px(Spacing::S2)
420                                .rounded(Radii::CONTROL)
421                                .text_size(Typography::TEXT_SM)
422                                .opacity(0.5)
423                                .text_color(colors.text_secondary)
424                                .child(
425                                    svg()
426                                        .path(IconName::FileDiff.path())
427                                        .size(px(14.0))
428                                        .text_color(colors.text_muted),
429                                )
430                                .child(self.open_label.clone()),
431                        )
432                    }),
433            );
434
435        // ── 文件列表 ──
436        let mut list = div().flex().flex_col();
437        if expanded {
438            let content = div().flex().flex_col().py(Spacing::S2).opacity(fade).when(
439                self.files.is_empty(),
440                |el| {
441                    el.child(
442                        div()
443                            .px(Spacing::S4)
444                            .py(Spacing::S2)
445                            .text_size(Typography::TEXT_XS)
446                            .text_color(colors.text_muted)
447                            .child("No changed files."),
448                    )
449                },
450            );
451
452            let mut rows = div().flex().flex_col();
453            for (folder, group_files) in &groups {
454                let folder_id: SharedString = SharedString::from(*folder);
455                let is_collapsed = collapsed.contains(&folder_id);
456                let folder_angle = arc_spring(
457                    (
458                        ElementId::NamedChild(self.id.clone().into(), folder_id.clone()),
459                        "chevron",
460                    ),
461                    chevron_target(!is_collapsed),
462                    cx.arc_theme().motion.spring.snappy,
463                    window,
464                    cx,
465                );
466                let (f_add, f_del) = group_files
467                    .iter()
468                    .fold((0u32, 0u32), |(a, d), f| (a + f.additions, d + f.deletions));
469
470                let folder_focus = window
471                    .use_keyed_state(
472                        ElementId::NamedChild(
473                            ElementId::NamedChild(self.id.clone().into(), folder_id.clone()).into(),
474                            "focus".into(),
475                        ),
476                        cx,
477                        |_, cx| cx.focus_handle(),
478                    )
479                    .read(cx)
480                    .clone();
481                let folder_mouse_focus = folder_focus.clone();
482                let folder_state = state_cell.clone();
483                let folder_name = folder_id.clone();
484                let toggle_folder: ChangeCallback = Rc::new(move |window, _| {
485                    let mut st = folder_state.borrow_mut();
486                    if st.collapsed_folders.contains(&folder_name) {
487                        st.collapsed_folders.retain(|f| f != &folder_name);
488                    } else {
489                        st.collapsed_folders.push(folder_name.clone());
490                    }
491                    drop(st);
492                    window.refresh();
493                });
494                let toggle_folder_key = toggle_folder.clone();
495                let folder_header = div()
496                    .id(ElementId::NamedChild(
497                        self.id.clone().into(),
498                        SharedString::from(format!("folder-{folder}")),
499                    ))
500                    .test_support()
501                    .role(Role::Button)
502                    .aria_label(SharedString::from(*folder))
503                    .aria_expanded(!is_collapsed)
504                    .track_focus(&folder_focus)
505                    .on_key_down(move |event, window, cx| {
506                        if matches!(event.keystroke.key.as_str(), "enter" | "space") {
507                            toggle_folder_key(window, cx);
508                            cx.stop_propagation();
509                        }
510                    })
511                    .flex()
512                    .items_center()
513                    .gap_2()
514                    .w_full()
515                    .h(px(32.0))
516                    .px(Spacing::S4)
517                    .text_size(Typography::TEXT_SM)
518                    .text_color(text_fg)
519                    .cursor_pointer()
520                    .hover(move |s| s.bg(oklab_mix(colors.surface_muted, colors.surface, 0.80)))
521                    .on_mouse_down(MouseButton::Left, move |_, window, cx| {
522                        folder_mouse_focus.focus(window, cx);
523                        toggle_folder(window, cx);
524                        cx.stop_propagation();
525                    })
526                    .child(
527                        div()
528                            .size(px(14.0))
529                            .flex()
530                            .items_center()
531                            .justify_center()
532                            .child(
533                                canvas(
534                                    move |_, _, _| {},
535                                    move |bounds, _, window, _| {
536                                        let cx_p = f32::from(bounds.origin.x)
537                                            + f32::from(bounds.size.width) * 0.5;
538                                        let cy_p = f32::from(bounds.origin.y)
539                                            + f32::from(bounds.size.height) * 0.5;
540                                        paint_chevron(
541                                            cx_p,
542                                            cy_p,
543                                            folder_angle,
544                                            colors.text_muted,
545                                            window,
546                                        );
547                                    },
548                                )
549                                .size_full(),
550                            ),
551                    )
552                    .child(
553                        svg()
554                            .path(IconName::Folder.path())
555                            .size(px(16.0))
556                            .flex_shrink_0()
557                            .text_color(colors.text_muted),
558                    )
559                    .child(
560                        div()
561                            .flex_1()
562                            .min_w_0()
563                            .truncate()
564                            .text_color(text_fg)
565                            .child(SharedString::from(*folder)),
566                    )
567                    .child(change_counts(f_add, f_del, plus_color, minus_color));
568
569                rows = rows.child(folder_header);
570                if !is_collapsed {
571                    for file in group_files {
572                        rows = rows.child(file_row(
573                            self.id.clone(),
574                            file,
575                            true,
576                            file_fg,
577                            plus_color,
578                            minus_color,
579                            colors,
580                        ));
581                    }
582                }
583            }
584            for file in root_files {
585                rows = rows.child(file_row(
586                    self.id.clone(),
587                    file,
588                    false,
589                    file_fg,
590                    plus_color,
591                    minus_color,
592                    colors,
593                ));
594            }
595
596            list = list.child(content.child(rows));
597        }
598
599        div()
600            .id(self.id.clone())
601            .test_support()
602            .role(Role::Region)
603            .overflow_hidden()
604            .w_full()
605            .min_w_0()
606            .rounded(Radii::SURFACE)
607            .border_1()
608            .border_color(colors.border)
609            .bg(colors.surface_raised)
610            .text_size(Typography::TEXT_SM)
611            .text_color(text_fg)
612            .child(header)
613            .child(list)
614    }
615}
616
617#[allow(clippy::too_many_arguments)]
618fn file_row(
619    card_id: ElementId,
620    file: &CommitFile,
621    nested: bool,
622    file_fg: Hsla,
623    plus: Hsla,
624    minus: Hsla,
625    colors: arc_tokens::ArcColors,
626) -> impl IntoElement {
627    let name = file.basename().to_string();
628    let (icon, tone) = commit_file_icon(&name, colors.foreground, colors.text_muted);
629    div()
630        .id(ElementId::NamedChild(
631            card_id.into(),
632            SharedString::from(format!("file-{}", file.path)),
633        ))
634        .test_support()
635        .flex()
636        .items_center()
637        .gap_2()
638        .w_full()
639        .min_h(px(32.0))
640        .pl(if nested { Spacing::S12 } else { Spacing::S8 })
641        .pr(Spacing::S4)
642        .text_size(Typography::TEXT_SM)
643        .child(
644            svg()
645                .path(icon.path())
646                .size(px(16.0))
647                .flex_shrink_0()
648                .text_color(tone),
649        )
650        .child(
651            div()
652                .flex_1()
653                .min_w_0()
654                .truncate()
655                .text_color(file_fg)
656                .child(SharedString::from(name)),
657        )
658        .child(change_counts(file.additions, file.deletions, plus, minus))
659}
660
661fn change_counts(add: u32, del: u32, plus: Hsla, minus: Hsla) -> gpui_kit::Div {
662    div()
663        .ml_auto()
664        .flex_shrink_0()
665        .flex()
666        .gap(Spacing::S4)
667        .text_size(Typography::TEXT_XS)
668        .child(
669            div()
670                .text_color(plus)
671                .child(SharedString::from(format!("+{add}"))),
672        )
673        .child(
674            div()
675                .text_color(minus)
676                .child(SharedString::from(format!("\u{2212}{del}"))),
677        )
678}
679
680fn paint_chevron(cx: f32, cy: f32, angle_deg: f32, color: Hsla, window: &mut Window) {
681    let angle = angle_deg.to_radians();
682    let cos = angle.cos();
683    let sin = angle.sin();
684    let rot = |dx: f32, dy: f32| {
685        gpui_kit::point(px(cx + dx * cos - dy * sin), px(cy + dx * sin + dy * cos))
686    };
687    let mut pb = gpui_kit::PathBuilder::stroke(px(1.75));
688    pb.move_to(rot(-2.6, -4.2));
689    pb.line_to(rot(2.6, 0.0));
690    pb.line_to(rot(-2.6, 4.2));
691    if let Ok(path) = pb.build() {
692        window.paint_path(path, color);
693    }
694}
695
696#[cfg(test)]
697mod tests {
698    use super::*;
699    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
700
701    struct Host {
702        controlled: bool,
703        notifications: usize,
704    }
705
706    impl Render for Host {
707        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
708            let host = cx.entity().clone();
709            let mut first = Commit::new(
710                "commit-a",
711                [
712                    CommitFile::new("src/a.ts", 1, 0),
713                    CommitFile::new("src-b/c.ts", 2, 1),
714                    CommitFile::new("src/b-c.ts", 3, 0),
715                ],
716            )
717            .on_expanded_change(move |_, cx| {
718                host.update(cx, |this, cx| {
719                    this.notifications += 1;
720                    cx.notify();
721                });
722            });
723            if self.controlled {
724                first = first.expanded(false);
725            }
726            div()
727                .w_full()
728                .flex()
729                .flex_col()
730                .child(first)
731                .child(Commit::new("commit-b", [CommitFile::new("src/a.ts", 1, 0)]))
732        }
733    }
734
735    fn part(card: &str, name: &str) -> ElementId {
736        ElementId::NamedChild(
737            ElementId::from(card.to_string()).into(),
738            name.to_string().into(),
739        )
740    }
741
742    fn init(cx: &mut TestAppContext) {
743        cx.update(|cx| {
744            gpui_kit::init(cx);
745            arc_tokens::install_arc_theme(
746                arc_tokens::ThemeMode::Light,
747                arc_tokens::Accent::Neutral,
748                cx,
749            );
750            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
751        });
752    }
753
754    #[gpui_kit::test]
755    fn commit_folders_and_instances_keep_independent_state(cx: &mut TestAppContext) {
756        init(cx);
757        let (_, window) = cx.add_window_view(|_, _| Host {
758            controlled: false,
759            notifications: 0,
760        });
761        window.update(|w, cx| {
762            w.render_frame(cx);
763            // 完整路径保留,避免 src-b/c.ts 与 src/b-c.ts 的 id 冲突。
764            assert!(w.try_find(part("commit-a", "file-src-b/c.ts")).is_some());
765            assert!(w.try_find(part("commit-a", "file-src/b-c.ts")).is_some());
766            w.click(part("commit-a", "folder-src"), cx);
767            assert!(w.try_find(part("commit-a", "file-src/a.ts")).is_none());
768            assert!(w.try_find(part("commit-a", "file-src-b/c.ts")).is_some());
769            assert!(w.try_find(part("commit-b", "file-src/a.ts")).is_some());
770            w.click(part("commit-a", "chevron"), cx);
771            assert!(w.try_find(part("commit-a", "folder-src")).is_none());
772            w.click(part("commit-a", "chevron"), cx);
773            assert!(
774                w.try_find(part("commit-a", "file-src/a.ts")).is_none(),
775                "整卡重开保留目录折叠"
776            );
777            w.click(part("commit-a", "folder-src"), cx);
778            assert!(w.try_find(part("commit-a", "file-src/a.ts")).is_some());
779            w.press("space", cx);
780            assert!(
781                w.try_find(part("commit-a", "file-src/a.ts")).is_none(),
782                "空格收起聚焦目录"
783            );
784            w.press("enter", cx);
785            assert!(
786                w.try_find(part("commit-a", "file-src/a.ts")).is_some(),
787                "回车展开聚焦目录"
788            );
789        });
790    }
791
792    #[gpui_kit::test]
793    fn commit_controlled_state_does_not_mutate_without_host_update(cx: &mut TestAppContext) {
794        init(cx);
795        let (view, window) = cx.add_window_view(|_, _| Host {
796            controlled: true,
797            notifications: 0,
798        });
799        window.update(|w, cx| {
800            w.render_frame(cx);
801            for expected in 1..=2 {
802                w.click(part("commit-a", "chevron"), cx);
803                assert!(w.try_find(part("commit-a", "folder-src")).is_none());
804                assert_eq!(view.read(cx).notifications, expected);
805            }
806        });
807    }
808
809    fn close(a: f32, b: f32) -> bool {
810        (a - b).abs() < 1e-3
811    }
812
813    #[test]
814    fn commit_groups_files_by_folder_with_stable_order() {
815        let files = vec![
816            CommitFile::new("src/components/ai/permission-grant.tsx", 1, 1),
817            CommitFile::new("DESIGN.md", 1, 0),
818            CommitFile::new("src/auth/verify.ts", 3, 2),
819        ];
820        let mut groups: BTreeMap<&str, Vec<&CommitFile>> = BTreeMap::new();
821        let mut root = Vec::new();
822        for f in &files {
823            match f.folder() {
824                Some(folder) => groups.entry(folder).or_default().push(f),
825                None => root.push(f),
826            }
827        }
828        let keys: Vec<_> = groups.keys().copied().collect();
829        assert_eq!(keys, vec!["src/auth", "src/components/ai"]);
830        assert_eq!(root.len(), 1);
831        assert_eq!(root[0].basename(), "DESIGN.md");
832        let grant = groups["src/components/ai"][0];
833        assert_eq!(grant.basename(), "permission-grant.tsx");
834    }
835
836    #[test]
837    fn commit_totals_and_headings() {
838        let card = Commit::new(
839            "t",
840            [
841                CommitFile::new("a.rs", 2, 1),
842                CommitFile::new("b/c.md", 0, 3),
843            ],
844        );
845        assert_eq!(card.totals(), (2, 4));
846        // 默认标题在 render 内生成;这里验证复数规则与源码一致。
847        let one = Commit::new("t1", [CommitFile::new("a.rs", 1, 0)]);
848        assert_eq!(one.files.len(), 1);
849    }
850
851    #[test]
852    fn commit_icon_tone_maps_by_extension() {
853        //tsx → Atom + sky 调;md → FileText + green 调;其他 → File + muted。
854        assert!(matches!(
855            commit_file_icon("App.tsx", Hsla::default(), Hsla::default()).0,
856            IconName::Atom
857        ));
858        assert!(matches!(
859            commit_file_icon("README.md", Hsla::default(), Hsla::default()).0,
860            IconName::FileText
861        ));
862        assert!(matches!(
863            commit_file_icon("main.rs", Hsla::default(), Hsla::default()).0,
864            IconName::File
865        ));
866    }
867
868    #[test]
869    fn commit_chevron_angle_and_fade_are_bounded() {
870        let reduced = true;
871        assert!(close(chevron_target(false), 0.0));
872        assert!(close(chevron_target(true), 90.0));
873        assert!(close(fade_alpha(5.0, reduced), 1.0));
874        let normal = false;
875        assert!(fade_alpha(0.075, normal) > 0.0 && fade_alpha(0.075, normal) < 1.0);
876        assert!(close(fade_alpha(0.2, normal), 1.0));
877    }
878}