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)
}
pub fn folder(&self) -> Option<&str> {
let idx = self.path.rfind('/')?;
Some(&self.path[..idx])
}
}
type ChangeCallback = Rc<dyn Fn(&mut Window, &mut App)>;
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)
}
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>,
}
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);
t as f32
}
#[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,
}
}
pub fn heading(mut self, heading: impl Into<SharedString>) -> Self {
self.heading = Some(heading.into());
self
}
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" }
))
});
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)
.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(),
),
)
.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);
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));
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() {
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));
}
}