diff --git a/Cargo.lock b/Cargo.lock index ecff233..98e8e31 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7159,6 +7159,7 @@ dependencies = [ "gix-worktree", "gix-worktree-state", "ignore", + "jiff", "log", "nostr", "serde", diff --git a/Cargo.toml b/Cargo.toml index d5c189a..21861e0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,6 +25,8 @@ nostr-sdk = { git = "https://github.com/rust-nostr/nostr" } gix = { version = "0.88", default-features = false, features = ["sha1", "blocking-network-client", "blocking-http-transport-reqwest-rust-tls", "worktree-mutation", "status"] } +jiff = "0.2" + smol = "2" futures = "0.3" flume = { version = "0.11.1", default-features = false, features = ["async", "select"] } diff --git a/crates/signed_app/Cargo.toml b/crates/signed_app/Cargo.toml index 2d32dad..24d73b7 100644 --- a/crates/signed_app/Cargo.toml +++ b/crates/signed_app/Cargo.toml @@ -21,5 +21,8 @@ anyhow.workspace = true futures.workspace = true log.workspace = true +[dev-dependencies] +gpui = { workspace = true, features = ["test-support"] } + [lints] workspace = true diff --git a/crates/signed_app/src/pull_requests/detail.rs b/crates/signed_app/src/pull_requests/detail.rs index f9c8719..9d87c59 100644 --- a/crates/signed_app/src/pull_requests/detail.rs +++ b/crates/signed_app/src/pull_requests/detail.rs @@ -1,5 +1,4 @@ use std::path::PathBuf; - use std::sync::Arc; use gpui::prelude::FluentBuilder as _; @@ -305,7 +304,9 @@ impl PullRequestDetailView { &workspace, id, move |window, cx| { - cx.new(|cx| CommitDiffView::new(worktree.clone(), commit_id.clone(), window, cx)) + cx.new(|cx| { + CommitDiffView::new(worktree.clone(), commit_id.clone(), false, window, cx) + }) }, window, cx, diff --git a/crates/signed_app/src/pull_requests/new.rs b/crates/signed_app/src/pull_requests/new.rs index e8c9371..265b4c1 100644 --- a/crates/signed_app/src/pull_requests/new.rs +++ b/crates/signed_app/src/pull_requests/new.rs @@ -1,5 +1,4 @@ use std::path::PathBuf; - use std::sync::Arc; use gpui::prelude::FluentBuilder as _; @@ -232,7 +231,9 @@ impl NewPullRequestView { &workspace, id, move |window, cx| { - cx.new(|cx| CommitDiffView::new(repo_path.clone(), commit_id.clone(), window, cx)) + cx.new(|cx| { + CommitDiffView::new(repo_path.clone(), commit_id.clone(), false, window, cx) + }) }, window, cx, diff --git a/crates/signed_app/src/repo/commit_diff.rs b/crates/signed_app/src/repo/commit_diff.rs index c16c3ec..dc23e02 100644 --- a/crates/signed_app/src/repo/commit_diff.rs +++ b/crates/signed_app/src/repo/commit_diff.rs @@ -3,54 +3,91 @@ use std::path::PathBuf; use gpui::prelude::FluentBuilder as _; use gpui::{ - AnyElement, App, AppContext as _, Axis, Context, Entity, IntoElement, ParentElement as _, - Render, ScrollStrategy, SharedString, Styled as _, Task, UniformListScrollHandle, Window, div, - px, uniform_list, + AnyElement, App, AppContext as _, Axis, Context, Entity, EventEmitter, InteractiveElement as _, + IntoElement, ListAlignment, ListState, ParentElement as _, Render, SharedString, + StatefulInteractiveElement as _, Styled as _, Subscription, Task, WeakEntity, Window, div, + list, px, }; -use signed_git::{CommitDiff, DiffStatus, FileCommit, FileDiff, Repo}; -use ui::badge::{Badge, BadgeVariant}; +use signed_git::{CommitDiff, FileCommit, FileDiff, Repo}; +use ui::avatar::Avatar; +use ui::badge::GroupedBadge; +use ui::button::{Button, ButtonVariant}; use ui::clipboard::ClipboardButton; -use ui::common::{StyledExt as _, h_flex, v_flex}; +use ui::common::{Sizable as _, StyledExt as _, h_flex, v_flex}; use ui::icons::{Icon, IconRole}; use ui::layout::panel::Panel; use ui::layout::resizable::{Resizable, ResizableState}; +use ui::separator::Separator; +use ui::switch::Switch; use ui::theme::ActiveTheme as _; +use ui::toggle::Toggle; +use ui::tooltip::Tooltip; use ui::tree::{Tree, TreeItem}; use utils::relative_time_secs; -use super::helpers::{DiffRow, diff_rows, render_diff_row}; +use super::helpers::{DiffRow, co_authors, diff_rows, render_diff_row, short_id}; use crate::shared::tree::{TreeItemSeed, TreeRow, build_tree_items, collect_expanded, flatten}; -use crate::shared::widgets::empty_state; +use crate::shared::widgets::{centered_spinner, empty_state, scroll_overlay}; + +/// Emitted when the user activates the Download commit button. +pub enum DiffPaneEvent { + DownloadCommit, +} + +impl EventEmitter for DiffPane {} + +/// One virtualized row of the multi-file diff list. +#[derive(Clone)] +enum PaneRow { + Header { + file_index: usize, + gap: bool, + expanded: bool, + }, + Note { + message: SharedString, + last: bool, + }, + Line { + file_index: usize, + row: DiffRow, + last: bool, + }, +} pub struct DiffPane { diff: Option, seeds: Vec, expanded: HashSet, rows: Vec, - selected_file: Option, selected_index: Option, - /// Rows of the selected file's diff, hunk headers and lines. - diff_rows: Vec, - scroll_handle: UniformListScrollHandle, + tree_visible: bool, split: Entity, + expanded_files: HashSet, + pane_rows: Vec, + list: ListState, + wrap: bool, + downloadable: bool, } impl DiffPane { pub fn new(cx: &mut Context) -> Self { + let split = ResizableState::new(cx); + split.update(cx, |split, cx| split.set_sizes([px(260.)], cx)); + Self { diff: None, seeds: Vec::new(), expanded: HashSet::new(), rows: Vec::new(), - selected_file: None, selected_index: None, - diff_rows: Vec::new(), - scroll_handle: UniformListScrollHandle::new(), - split: { - let split = ResizableState::new(cx); - split.update(cx, |split, cx| split.set_sizes([px(260.)], cx)); - split - }, + tree_visible: false, + split, + expanded_files: HashSet::new(), + pane_rows: Vec::new(), + list: ListState::new(0, ListAlignment::Top, px(320.)), + wrap: false, + downloadable: false, } } @@ -65,26 +102,16 @@ impl DiffPane { .map(|file| PathBuf::from(&file.path)) .collect(); paths.sort(); + self.seeds = build_tree_items(&paths); self.expanded = collect_expanded(&self.seeds); self.rows = flatten(&self.seeds, &self.expanded); - - let first = diff - .files - .first() - .map(|file| SharedString::from(file.path.as_str())); - - self.selected_file = first.clone(); - self.selected_index = first - .as_ref() - .and_then(|path| self.rows.iter().position(|row| row.id == path.as_ref())); + self.selected_index = None; self.diff = Some(diff); - if let Some(path) = first { - self.set_diff_rows(path.as_ref()); - } else { - self.diff_rows.clear(); - } + self.expanded_files.clear(); + self.rebuild_rows(); + self.list = ListState::new(self.pane_rows.len(), ListAlignment::Top, px(320.)); cx.notify(); } @@ -93,28 +120,129 @@ impl DiffPane { self.seeds.clear(); self.expanded.clear(); self.rows.clear(); - self.selected_file = None; self.selected_index = None; - self.diff_rows.clear(); + self.expanded_files.clear(); + self.pane_rows.clear(); + self.list = ListState::new(0, ListAlignment::Top, px(320.)); cx.notify(); } - fn select_file(&mut self, path: &str, cx: &mut Context) { - self.selected_file = Some(path.into()); + pub fn set_tree_visible(&mut self, visible: bool, cx: &mut Context) { + self.tree_visible = visible; + cx.notify(); + } + + pub fn set_downloadable(&mut self, downloadable: bool, cx: &mut Context) { + self.downloadable = downloadable; + cx.notify(); + } + + pub fn toggle_wrap(&mut self, cx: &mut Context) { + self.wrap = !self.wrap; + self.rebuild_rows(); + cx.notify(); + } + + fn toggle_file(&mut self, path: &str, cx: &mut Context) { + if !self.expanded_files.remove(path) { + self.expanded_files.insert(path.to_owned()); + } + self.rebuild_rows(); + cx.notify(); + } + + fn all_expanded(&self) -> bool { + self.diff.as_ref().is_some_and(|diff| { + !diff.files.is_empty() + && diff + .files + .iter() + .all(|file| self.expanded_files.contains(&file.path)) + }) + } + + fn toggle_all_files(&mut self, cx: &mut Context) { + if self.all_expanded() { + self.expanded_files.clear(); + } else if let Some(diff) = self.diff.as_ref() { + self.expanded_files = diff.files.iter().map(|file| file.path.clone()).collect(); + } + self.rebuild_rows(); + cx.notify(); + } + + fn select_tree_file(&mut self, path: &str, cx: &mut Context) { self.selected_index = self.rows.iter().position(|row| row.id == path); - self.set_diff_rows(path); + if self.expanded_files.insert(path.to_owned()) { + self.rebuild_rows(); + } + + let header_index = self.pane_rows.iter().position(|row| match row { + PaneRow::Header { file_index, .. } => self + .diff + .as_ref() + .and_then(|diff| diff.files.get(*file_index)) + .is_some_and(|file| file.path == path), + _ => false, + }); + if let Some(header_index) = header_index { + self.list.scroll_to_reveal_item(header_index); + } cx.notify(); } - fn set_diff_rows(&mut self, path: &str) { + fn rebuild_rows(&mut self) { let Some(diff) = self.diff.as_ref() else { + self.pane_rows.clear(); + self.list.reset(0); return; }; - let Some(file) = diff.files.iter().find(|file| file.path == path) else { - return; - }; - self.diff_rows = diff_rows(file); - self.scroll_handle.scroll_to_item(0, ScrollStrategy::Top); + + let mut pane_rows = Vec::new(); + for (file_index, file) in diff.files.iter().enumerate() { + let expanded = self.expanded_files.contains(&file.path); + pane_rows.push(PaneRow::Header { + file_index, + gap: file_index > 0, + expanded, + }); + + if !expanded { + continue; + } + + if file.binary { + pane_rows.push(PaneRow::Note { + message: SharedString::from("Diff not available"), + last: true, + }); + continue; + } + + if file.hunks.is_empty() { + pane_rows.push(PaneRow::Note { + message: SharedString::from("No content changes"), + last: true, + }); + continue; + } + + let rows = diff_rows(file); + let last_row = rows.len().saturating_sub(1); + + pane_rows.extend( + rows.into_iter() + .enumerate() + .map(|(row_index, row)| PaneRow::Line { + file_index, + row, + last: row_index == last_row, + }), + ); + } + + self.pane_rows = pane_rows; + self.list.reset(self.pane_rows.len()); } fn toggle_folder(&mut self, id: &str, cx: &mut Context) { @@ -123,9 +251,8 @@ impl DiffPane { } self.rows = flatten(&self.seeds, &self.expanded); self.selected_index = self - .selected_file - .as_ref() - .and_then(|path| self.rows.iter().position(|row| row.id == path.as_ref())); + .selected_index + .and_then(|index| self.rows.get(index).map(|_| index)); cx.notify(); } @@ -195,138 +322,298 @@ impl DiffPane { if expandable { self.toggle_folder(&id, cx); } else { - self.select_file(&id, cx); + self.select_tree_file(&id, cx); } } - fn render_detail_column(&self, cx: &mut Context) -> AnyElement { + fn render_toolbar(&self, cx: &mut Context) -> AnyElement { + let view = cx.entity().downgrade(); + let (insertions, deletions) = self.diff().map_or((0, 0), |diff| { + ( + diff.files.iter().map(|file| file.insertions).sum(), + diff.files.iter().map(|file| file.deletions).sum(), + ) + }); + let files = self.diff().map_or(0, |diff| diff.files.len()); + let all_expanded = self.all_expanded(); + + h_flex() + .h_12() + .px_2() + .gap_2() + .flex_none() + .border_b_1() + .border_color(cx.theme().colors.border) + .child( + Toggle::new("toggle-tree") + .icon(Icon::named(IconRole::PanelLeft)) + .pressed(self.tree_visible) + .accessibility_label("Toggle file tree") + .on_change({ + let view = view.clone(); + move |pressed, _, cx| { + if let Err(error) = + view.update(cx, |this, cx| this.set_tree_visible(pressed, cx)) + { + log::warn!("failed to toggle file tree: {error}"); + } + } + }), + ) + .when(insertions > 0 || deletions > 0, |this| { + this.child(GroupedBadge::new( + "toolbar-diff-stats", + insertions, + deletions, + )) + }) + .child( + div() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .child(format!("{files} changed files")), + ) + .child(div().flex_1()) + .child( + Switch::new("wrap-lines") + .label("Wrap") + .checked(self.wrap) + .small() + .on_change({ + let view = view.clone(); + move |checked, _, cx| { + if let Err(error) = view.update(cx, |this, cx| { + if checked != this.wrap { + this.toggle_wrap(cx); + } + }) { + log::warn!("failed to toggle wrap: {error}"); + } + } + }), + ) + .child( + Button::new("expand-all") + .label(if all_expanded { "Collapse" } else { "Expand" }) + .icon(Icon::named(IconRole::UnfoldVertical)) + .variant(ButtonVariant::Ghost) + .small() + .on_click({ + let view = view; + move |_, _, cx| { + if let Err(error) = + view.update(cx, |this, cx| this.toggle_all_files(cx)) + { + log::warn!("failed to toggle all diff files: {error}"); + } + } + }), + ) + .when(self.downloadable, |this| { + this.child( + Button::new("download") + .label("Download") + .icon(Icon::named(IconRole::Download)) + .variant(ButtonVariant::Ghost) + .tooltip(Tooltip::text("Download commit")) + .small() + .on_click(cx.listener(|_, _, _, cx| { + cx.emit(DiffPaneEvent::DownloadCommit); + })), + ) + }) + .into_any_element() + } + + fn render_file_list(&self, cx: &mut Context) -> AnyElement { let Some(diff) = self.diff.as_ref() else { return empty_state("No changes"); }; - let Some(path) = self.selected_file.clone() else { - return if diff.files.is_empty() { - empty_state("No files changed") - } else { - empty_state("Select a file") - }; - }; - let Some(file) = diff.files.iter().find(|file| file.path == path.as_ref()) else { - return empty_state("File not found"); - }; - self.render_file_diff(file, cx) - } - fn render_file_diff(&self, file: &FileDiff, cx: &App) -> AnyElement { - let status_label = match file.status { - DiffStatus::Added => "A", - DiffStatus::Modified => "M", - DiffStatus::Deleted => "D", - DiffStatus::Renamed => "R", - DiffStatus::Copied => "C", - }; - let status_color = match file.status { - DiffStatus::Added => cx.theme().ramps.success.base, - DiffStatus::Modified => cx.theme().ramps.info.base, - DiffStatus::Deleted => cx.theme().ramps.destructive.base, - DiffStatus::Renamed | DiffStatus::Copied => cx.theme().colors.muted_foreground, - }; - let title = match &file.old_path { - Some(old) => format!("{old} → {}", file.path), - None => file.path.clone(), - }; + let files = diff.files.clone(); + let pane_rows = self.pane_rows.clone(); + let wrap = self.wrap; + let view = cx.entity().downgrade(); - let body: AnyElement = if file.binary { - empty_state("Diff not available") - } else if file.hunks.is_empty() { - empty_state("No content changes") - } else { - let hunks = file.hunks.clone(); - let rows = self.diff_rows.clone(); - - v_flex() - .size_full() - .relative() - .child( - uniform_list("commit-diff-rows", rows.len(), move |range, _, cx| { - range - .map(|ix| render_diff_row(&hunks, rows[ix], cx)) - .collect() - }) - .track_scroll(&self.scroll_handle) - .size_full(), - ) - .child(crate::shared::widgets::scroll_overlay( - "commit-diff-scroll", - self.scroll_handle.clone(), - )) - .into_any_element() - }; - - v_flex() + div() + .relative() .flex_1() - .min_w_0() + .min_h_0() .h_full() + .debug_selector(|| "commit-diff-files-list".to_owned()) .child( - h_flex() - .px_3() - .h_9() - .gap_2() - .child( - div() - .text_xs() - .font_medium() - .text_color(status_color) - .child(status_label), - ) - .child( - div() - .flex_1() - .min_w_0() - .text_xs() - .font_medium() - .text_ellipsis() - .whitespace_nowrap() - .child(title), - ) - .when(!file.binary, |this| { - this.child( - h_flex() - .gap_2() - .text_xs() - .child( - Badge::new("file-insertions", format!("+ {}", file.insertions)) - .variant(BadgeVariant::Success), - ) - .child( - Badge::new("file-deletions", format!("- {}", file.deletions)) - .variant(BadgeVariant::Danger), - ), - ) - }), + list(self.list.clone(), move |ix, _, cx| { + match pane_rows.get(ix) { + Some(row) => render_pane_row(row, &files, &view, wrap, cx), + None => div().into_any_element(), + } + }) + .size_full() + .p_2(), ) - .child(div().flex_1().min_h_0().child(body)) + .child(scroll_overlay("commit-diff-files", self.list.clone())) .into_any_element() } } +fn render_pane_row( + row: &PaneRow, + files: &[FileDiff], + pane: &WeakEntity, + wrap: bool, + cx: &App, +) -> AnyElement { + let border = cx.theme().colors.border; + let surface = cx.theme().colors.surface; + + match row { + PaneRow::Header { + file_index, + gap, + expanded, + } => { + let Some(file) = files.get(*file_index) else { + return div().into_any_element(); + }; + let path = file.path.clone(); + let title = match &file.old_path { + Some(old) => SharedString::from(format!("{old} → {}", file.path)), + None => SharedString::from(file.path.clone()), + }; + + div() + .w_full() + .when(*gap, |this| this.pt_2()) + .child( + h_flex() + .id(("file-header", *file_index)) + .debug_selector(move || format!("commit-diff-file-card-{file_index}")) + .h_10() + .px_2() + .gap_2() + .bg(surface) + .border_1() + .border_color(border) + .cursor_pointer() + .hover(|this| this.bg(cx.theme().colors.muted_hover)) + .when(*expanded, |this| this.rounded_t_lg().border_b_0()) + .when(!*expanded, |this| this.rounded_lg()) + .child( + Icon::named(if *expanded { + IconRole::ChevronDown + } else { + IconRole::ChevronRight + }) + .color(cx.theme().colors.muted_foreground), + ) + .child(div().min_w_0().truncate().text_sm().child(title)) + .when(file.insertions > 0 || file.deletions > 0, |this| { + this.child(GroupedBadge::new( + ("file-diff-stats", *file_index), + file.insertions, + file.deletions, + )) + }) + .child(div().flex_1()) + .child( + Button::new(("view-file", *file_index)) + .label("View file") + .icon(Icon::named(IconRole::Eye)) + .variant(ButtonVariant::Ghost) + .small() + .on_click(|_, _, cx| cx.stop_propagation()), + ) + .on_click({ + let pane = pane.clone(); + move |_, _, cx| { + if let Err(error) = + pane.update(cx, |this, cx| this.toggle_file(&path, cx)) + { + log::warn!("failed to toggle diff file: {error}"); + } + } + }), + ) + .into_any_element() + } + PaneRow::Note { message, last, .. } => div() + .w_full() + .border_x_1() + .border_color(border) + .bg(surface) + .px_3() + .py_2() + .text_xs() + .text_color(cx.theme().colors.muted_foreground) + .when(*last, |this| this.border_b_1().rounded_b_lg()) + .child(message.clone()) + .into_any_element(), + PaneRow::Line { + file_index, + row, + last, + } => { + let Some(file) = files.get(*file_index) else { + return div().into_any_element(); + }; + div() + .w_full() + .border_x_1() + .border_color(border) + .bg(surface) + .when(*last, |this| this.border_b_1().rounded_b_lg()) + .child(render_diff_row(&file.hunks, *row, wrap, cx)) + .into_any_element() + } + } +} + impl Render for DiffPane { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let tree = self.render_tree_column(cx); - let detail = self.render_detail_column(cx); + if self.diff.is_none() { + return empty_state("No changes"); + } - h_flex() + let diff = self.diff.as_ref().expect("diff checked above"); + + if diff.files.is_empty() { + return empty_state("No files changed"); + } + + let toolbar = self.render_toolbar(cx); + let file_list = self.render_file_list(cx); + + let content = if self.tree_visible { + let tree = self.render_tree_column(cx); + h_flex() + .flex_1() + .min_h_0() + .child( + Resizable::new("commit-diff-split", self.split.clone()) + .axis(Axis::Horizontal) + .pane_with_min(tree, px(120.)) + .pane_with_min(file_list, px(240.)) + .flex_1() + .min_w_0() + .h_full(), + ) + .into_any_element() + } else { + div() + .flex_1() + .min_w_0() + .h_full() + .child(file_list) + .into_any_element() + }; + + v_flex() .size_full() .min_h_0() .bg(cx.theme().colors.background) - .child( - Resizable::new("commit-diff-split", self.split.clone()) - .axis(Axis::Horizontal) - .pane_with_min(tree, px(120.)) - .pane_with_min(detail, px(240.)) - .flex_1() - .min_w_0() - .h_full(), - ) + .child(toolbar) + .child(content) + .into_any_element() } } @@ -338,16 +625,25 @@ pub struct CommitDiffView { error: Option, pane: Entity, tasks: Vec>>, + _download_subscription: Subscription, } impl CommitDiffView { pub fn new( worktree: PathBuf, commit_id: String, + downloadable: bool, window: &mut Window, cx: &mut Context, ) -> Self { - let pane = cx.new(DiffPane::new); + let pane = cx.new(|cx| { + let mut pane = DiffPane::new(cx); + pane.set_downloadable(downloadable, cx); + pane + }); + let subscription = cx.subscribe(&pane, |this, _, DiffPaneEvent::DownloadCommit, cx| { + this.download_patch(cx); + }); let weak = cx.entity().downgrade(); window.defer(cx, move |window, cx| { @@ -364,11 +660,14 @@ impl CommitDiffView { description: None, author: String::new(), time: 0, + date_label: String::new(), + parents: Vec::new(), }, loading: true, error: None, pane, tasks: Vec::new(), + _download_subscription: subscription, } } @@ -424,15 +723,59 @@ impl CommitDiffView { self.push_task(task); } + fn download_patch(&mut self, cx: &mut Context) { + let worktree = self.worktree.clone(); + let id = self.commit.id.clone(); + + let suggested_name = format!("{}.patch", short_id(&id)); + let prompt = cx.prompt_for_new_path(&worktree, Some(suggested_name.as_str())); + + let task: Task> = cx.spawn(async move |this, cx| { + let destination = match prompt.await { + Ok(Ok(Some(path))) => path, + Ok(Ok(None)) => return Ok(()), + Ok(Err(error)) => { + log::warn!("failed to open the commit patch save dialog: {error}"); + return Ok(()); + } + Err(_) => return Ok(()), + }; + + let patch = cx + .background_spawn(async move { + Repo::open(&worktree).and_then(|repo| repo.commit_patch(&id)) + }) + .await; + + match patch { + Ok(patch) => { + if let Err(error) = std::fs::write(&destination, patch) { + log::warn!("failed to write commit patch: {error}"); + } + } + Err(error) => log::warn!("failed to build commit patch: {error}"), + } + + this.update(cx, |_, cx| cx.notify())?; + Ok(()) + }); + + self.push_task(task); + } + fn render_header(&self, cx: &mut Context) -> AnyElement { let commit = &self.commit; - let (files, insertions, deletions) = self.pane.read(cx).diff().map_or((0, 0, 0), |diff| { - ( - diff.files.len(), - diff.files.iter().map(|file| file.insertions).sum(), - diff.files.iter().map(|file| file.deletions).sum(), - ) - }); + let muted = cx.theme().colors.muted_foreground; + + let row = |label: &'static str, value: AnyElement| -> AnyElement { + h_flex() + .h_6() + .gap_2() + .text_xs() + .child(div().w_20().flex_none().text_color(muted).child(label)) + .child(div().flex_1().min_w_0().child(value)) + .into_any_element() + }; v_flex() .flex_none() @@ -443,55 +786,100 @@ impl CommitDiffView { .border_b_1() .border_color(cx.theme().colors.border) .child( - v_flex() - .child( - div() - .text_sm() - .font_semibold() - .text_ellipsis() - .whitespace_nowrap() - .child(commit.summary.clone()), - ) - .child( - h_flex() - .gap_2() - .text_base() - .child(SharedString::from(format!("{} committed", commit.author))) - .child( - h_flex() - .gap_1() - .text_color(cx.theme().colors.muted_foreground) - .child(SharedString::from(&commit.id)) - .child(ClipboardButton::new("commit-id", &commit.id)), - ) - .child( - div() - .text_color(cx.theme().colors.muted_foreground) - .child(relative_time_secs(commit.time)), - ), - ), + div() + .min_w_0() + .font_semibold() + .truncate() + .text_ellipsis() + .child(SharedString::from(commit.summary.clone())), ) .when_some(commit.description.as_ref(), |this, description| { - this.child(div().text_base().child(SharedString::from(description))) + this.child( + div() + .text_sm() + .text_color(cx.theme().colors.muted_foreground) + .child(SharedString::from(description)), + ) }) - .child( + .child(Separator::horizontal()) + .child(row( + "Author", h_flex() .gap_2() - .text_xs() - .child(Badge::new("commit-files", format!("{files} files changed"))) - .when(insertions > 0, |this| { - this.child( - Badge::new("commit-insertions", format!("+ {insertions}")) - .variant(BadgeVariant::Success), - ) - }) - .when(deletions > 0, |this| { - this.child( - Badge::new("commit-deletions", format!("- {deletions}")) - .variant(BadgeVariant::Danger), - ) + .child( + Avatar::new(commit.author.clone()) + .name(commit.author.clone()) + .small(), + ) + .child( + div() + .truncate() + .child(SharedString::from(commit.author.clone())), + ) + .into_any_element(), + )) + .children( + commit + .description + .as_ref() + .map_or_else(Vec::new, |description| { + co_authors(description) + .into_iter() + .map(|name| { + row( + "Co-author", + h_flex() + .gap_2() + .child(Avatar::new(name.clone()).name(name.clone()).small()) + .child(div().truncate().text_ellipsis().child(name)) + .into_any_element(), + ) + }) + .collect::>() }), ) + .child(row( + "Date", + h_flex() + .gap_2() + .child(relative_time_secs(commit.time)) + .when(!commit.date_label.is_empty(), |this| { + this.child( + div() + .text_color(muted) + .child(SharedString::from(format!("({})", commit.date_label))), + ) + }) + .into_any_element(), + )) + .child(row( + "Commit", + h_flex() + .gap_2() + .child( + div() + .text_ellipsis() + .truncate() + .child(SharedString::from(commit.id.clone())), + ) + .child(ClipboardButton::new("commit-id", &commit.id).xsmall()) + .into_any_element(), + )) + .children(commit.parents.iter().enumerate().map(|(ix, parent)| { + row( + "Parent", + h_flex() + .gap_2() + .child( + div() + .text_ellipsis() + .truncate() + .child(SharedString::from(parent.clone())), + ) + .child(ClipboardButton::new(("commit-parent", ix), parent).xsmall()) + .into_any_element(), + ) + })) .into_any_element() } } @@ -509,8 +897,8 @@ impl Panel for CommitDiffView { impl Render for CommitDiffView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { - let body: AnyElement = if self.loading { - crate::shared::widgets::centered_spinner("commit-diff-loading") + let body = if self.loading { + centered_spinner("commit-diff-loading") } else if let Some(error) = self.error.clone() { empty_state(error) } else { diff --git a/crates/signed_app/src/repo/files.rs b/crates/signed_app/src/repo/files.rs index 1d4f856..a916727 100644 --- a/crates/signed_app/src/repo/files.rs +++ b/crates/signed_app/src/repo/files.rs @@ -16,6 +16,7 @@ use ui::theme::ActiveTheme as _; use ui::tree::{Tree, TreeItem}; use super::helpers::{code_language, is_markdown_path, preview_spinner, source_hash}; +use crate::repo::helpers::short_id; use crate::shared::tree::{TreeItemSeed, TreeRow, collect_expanded, flatten}; use crate::shared::widgets::empty_state; @@ -367,7 +368,7 @@ impl RepoFilesView { div() .text_xs() .font_family(cx.theme().mono_font) - .child(commit.id.clone()), + .child(short_id(&commit.id)), ) .child( div() diff --git a/crates/signed_app/src/repo/helpers.rs b/crates/signed_app/src/repo/helpers.rs index 9172f17..aab8867 100644 --- a/crates/signed_app/src/repo/helpers.rs +++ b/crates/signed_app/src/repo/helpers.rs @@ -39,6 +39,29 @@ pub fn short_id(hex: &str) -> SharedString { SharedString::from(hex.get(..8).unwrap_or(hex).to_owned()) } +/// The co-author names credited in a commit body, deduplicated in order. +pub(super) fn co_authors(description: &str) -> Vec { + let mut names: Vec = Vec::new(); + for line in description.lines() { + let trimmed = line.trim(); + if !trimmed.to_lowercase().starts_with("co-authored-by:") { + continue; + } + let name = trimmed + .split_once(':') + .map(|(_, value)| value.trim()) + .unwrap_or_default() + .split('<') + .next() + .unwrap_or_default() + .trim(); + if !name.is_empty() && !names.iter().any(|existing| existing.as_ref() == name) { + names.push(SharedString::from(name.to_owned())); + } + } + names +} + /// Snapshots the worktree and derives the explorer's tree rows and paths. pub(super) fn snapshot_worktree( worktree: PathBuf, @@ -295,7 +318,12 @@ pub(super) fn diff_rows(file: &FileDiff) -> Vec { rows } -pub(super) fn render_diff_row(hunks: &[DiffHunk], row: DiffRow, cx: &App) -> AnyElement { +pub(super) fn render_diff_row( + hunks: &[DiffHunk], + row: DiffRow, + wrap: bool, + cx: &App, +) -> AnyElement { match row { DiffRow::Hunk { old_start, @@ -318,14 +346,14 @@ pub(super) fn render_diff_row(hunks: &[DiffHunk], row: DiffRow, cx: &App) -> Any ))) .into_any_element(), DiffRow::Line { hunk, line } => match hunks.get(hunk).and_then(|h| h.lines.get(line)) { - Some(line) => render_diff_line(line, cx), + Some(line) => render_diff_line(line, wrap, cx), // A stale row index renders as a blank row rather than panicking. None => div().w_full().h(px(DIFF_ROW_HEIGHT)).into_any_element(), }, } } -fn render_diff_line(line: &DiffLine, cx: &App) -> AnyElement { +fn render_diff_line(line: &DiffLine, wrap: bool, cx: &App) -> AnyElement { let bg = match line.kind { DiffLineKind::Addition => Some(cx.theme().ramps.success.base.opacity(0.2)), DiffLineKind::Deletion => Some(cx.theme().ramps.destructive.base.opacity(0.2)), @@ -335,7 +363,8 @@ fn render_diff_line(line: &DiffLine, cx: &App) -> AnyElement { h_flex() .w_full() - .h(px(DIFF_ROW_HEIGHT)) + .when(wrap, |row| row.min_h(px(DIFF_ROW_HEIGHT))) + .when(!wrap, |row| row.h(px(DIFF_ROW_HEIGHT))) .font_family(cx.theme().mono_font) .text_xs() .when_some(bg, |this, bg| this.bg(bg)) @@ -361,9 +390,10 @@ fn render_diff_line(line: &DiffLine, cx: &App) -> AnyElement { div() .flex_1() .min_w_0() - .overflow_hidden() - .whitespace_nowrap() .text_color(cx.theme().colors.foreground) + .when(!wrap, |content| { + content.overflow_hidden().whitespace_nowrap() + }) .child(line.text.clone()), ) .into_any_element() @@ -400,7 +430,7 @@ pub(crate) fn commit_row( .font_family(cx.theme().mono_font) .text_sm() .text_color(cx.theme().colors.muted_foreground) - .child(commit.id.clone()), + .child(short_id(&commit.id)), ) .child( div() diff --git a/crates/signed_app/src/repo/history.rs b/crates/signed_app/src/repo/history.rs index 71c82f6..2827ec4 100644 --- a/crates/signed_app/src/repo/history.rs +++ b/crates/signed_app/src/repo/history.rs @@ -145,7 +145,9 @@ impl RepoHistoryView { &workspace, id, move |window, cx| { - cx.new(|cx| CommitDiffView::new(worktree.clone(), commit_id.clone(), window, cx)) + cx.new(|cx| { + CommitDiffView::new(worktree.clone(), commit_id.clone(), true, window, cx) + }) }, window, cx, @@ -227,7 +229,7 @@ impl Render for RepoHistoryView { let detail = detail.clone(); let path = path.clone(); let target = ahead_id.clone(); - let short = commit.id.clone(); + let short = super::helpers::short_id(&commit.id); Button::new(("sync-commit", ix)) .label("Sync") diff --git a/crates/signed_app/src/workspace.rs b/crates/signed_app/src/workspace.rs index 21383ce..d23ef91 100644 --- a/crates/signed_app/src/workspace.rs +++ b/crates/signed_app/src/workspace.rs @@ -1,6 +1,7 @@ use std::collections::HashMap; use std::sync::Arc; +use gpui::prelude::FluentBuilder as _; use gpui::{ App, Context, IntoElement, ParentElement as _, Render, SharedString, Styled as _, Window, div, }; @@ -205,38 +206,38 @@ impl Render for Workspace { .collect(); let weak = cx.entity().downgrade(); - let close_weak = weak.clone(); - - let tabs = Tabs::new("signed-detail-tabs") - .variant(TabsVariant::Pill) - .overflow_scroll(true) - .selected(selected) - .tabs(move |_, cx| { - details - .iter() - .map(|(id, view)| match view { - Some(view) => view.tab(id.clone().into(), cx).closeable(true), - None => Tab::new(id.clone(), id.clone()).closeable(true), - }) - .collect() - }) - .on_change(move |index, _, cx| { - log_dropped(weak.update(cx, |workspace, cx| { - workspace.activate_detail_at(index, cx); - })); - }) - .on_close(move |index, _, cx| { - log_dropped(close_weak.update(cx, |workspace, cx| { - workspace.close_detail_at(index, cx); - })); - }); - let body = self.active_detail().map(|view| view.view()); v_flex() .size_full() .gap_2() - .child(tabs) + .when(self.details.len() > 1, |this| { + let close_weak = weak.clone(); + let tabs = Tabs::new("signed-detail-tabs") + .variant(TabsVariant::Pill) + .overflow_scroll(true) + .selected(selected) + .tabs(move |_, cx| { + details + .iter() + .map(|(id, view)| match view { + Some(view) => view.tab(id.clone().into(), cx).closeable(true), + None => Tab::new(id.clone(), id.clone()).closeable(true), + }) + .collect() + }) + .on_change(move |index, _, cx| { + log_dropped(weak.update(cx, |workspace, cx| { + workspace.activate_detail_at(index, cx); + })); + }) + .on_close(move |index, _, cx| { + log_dropped(close_weak.update(cx, |workspace, cx| { + workspace.close_detail_at(index, cx); + })); + }); + this.child(tabs) + }) .child(div().flex_1().min_h_0().w_full().children(body)) } } diff --git a/crates/signed_git/Cargo.toml b/crates/signed_git/Cargo.toml index 35869b5..b137df3 100644 --- a/crates/signed_git/Cargo.toml +++ b/crates/signed_git/Cargo.toml @@ -12,6 +12,7 @@ serde.workspace = true serde_json.workspace = true log.workspace = true anyhow.workspace = true +jiff.workspace = true gix = { workspace = true, features = ["revision", "blob-diff"] } gix-worktree = "0.57" gix-worktree-state = "0.35" diff --git a/crates/signed_git/src/diff.rs b/crates/signed_git/src/diff.rs index 1c315f2..4163818 100644 --- a/crates/signed_git/src/diff.rs +++ b/crates/signed_git/src/diff.rs @@ -235,3 +235,53 @@ impl ConsumeHunk for HunkCollector<'_> { /// Marks the end of the unified diff stream. fn finish(self) {} } + +/// Collects hunks as unified-diff text for patch export. +pub(crate) struct PatchCollector { + text: String, +} + +impl PatchCollector { + pub(crate) fn new() -> Self { + Self { + text: String::new(), + } + } +} + +impl ConsumeHunk for PatchCollector { + type Out = String; + + fn consume_hunk( + &mut self, + header: HunkHeader, + lines: &[(GixLineKind, &[u8])], + ) -> std::io::Result<()> { + self.text.push_str(&format!( + "@@ -{},{} +{},{} @@\n", + header.before_hunk_start, + header.before_hunk_len, + header.after_hunk_start, + header.after_hunk_len, + )); + + for (kind, content) in lines { + let prefix = match kind { + GixLineKind::Context => ' ', + GixLineKind::Remove => '-', + GixLineKind::Add => '+', + }; + // Tokens may already carry the line's newline; emit exactly one. + let content = content.strip_suffix(b"\n").unwrap_or(content); + self.text.push(prefix); + self.text.push_str(&String::from_utf8_lossy(content)); + self.text.push('\n'); + } + + Ok(()) + } + + fn finish(self) -> String { + self.text + } +} diff --git a/crates/signed_git/src/history.rs b/crates/signed_git/src/history.rs index 3babe2b..5dfe18d 100644 --- a/crates/signed_git/src/history.rs +++ b/crates/signed_git/src/history.rs @@ -19,16 +19,23 @@ pub struct FileCommit { pub description: Option, pub author: String, pub time: i64, + /// Human-readable absolute date in the commit's recorded offset, e.g. + /// "Nov 21, 2026 at 4:40 AM GMT+7"; empty when the date cannot be formatted. + pub date_label: String, + /// Full hex parent ids; empty for patch-parsed commits. + pub parents: Vec, } impl FileCommit { - /// Creates a commit entry from its id, message parts, author, and timestamp. + /// Creates a commit entry from its id, message parts, author, timestamp, date label, and parents. pub fn new( id: String, summary: String, description: Option, author: String, time: i64, + date_label: String, + parents: Vec, ) -> Self { Self { id, @@ -36,6 +43,8 @@ impl FileCommit { description, author, time, + date_label, + parents, } } @@ -58,9 +67,10 @@ impl FileCommit { let author = commit.author().into_anyhow()?; let message = commit.message().into_anyhow()?; + let time = author.time().into_anyhow()?; Ok(FileCommit::new( - commit.id().shorten_or_id().to_string(), + commit.id().to_string(), String::from_utf8_lossy(message.title).trim().to_string(), if include_description { message @@ -71,7 +81,40 @@ impl FileCommit { None }, String::from_utf8_lossy(author.name).trim().to_string(), - author.time().into_anyhow()?.seconds, + time.seconds, + format_commit_date(time), + commit.parent_ids().map(|id| id.to_string()).collect(), )) } } + +/// Formats a gix time as "Nov 21, 2026 at 4:40 AM GMT+7" in the commit's own offset. +pub(crate) fn format_commit_date(time: gix::date::Time) -> String { + let Ok(timestamp) = jiff::Timestamp::from_second(time.seconds) else { + return String::new(); + }; + let Ok(offset) = jiff::tz::Offset::from_seconds(time.offset) else { + return String::new(); + }; + let datetime = offset.to_datetime(timestamp); + + let label = datetime.strftime("%b %-d, %Y at %-I:%M %p").to_string(); + format!("{label} {}", gmt_label(time.offset)) +} + +/// The GMT offset label for a seconds offset, e.g. "GMT", "GMT+7", "GMT-5:30". +fn gmt_label(offset: i32) -> String { + if offset == 0 { + return "GMT".to_owned(); + } + + let sign = if offset < 0 { '-' } else { '+' }; + let total_minutes = offset.abs() / 60; + let hours = total_minutes / 60; + let minutes = total_minutes % 60; + if minutes == 0 { + format!("GMT{sign}{hours}") + } else { + format!("GMT{sign}{hours}:{minutes:02}") + } +} diff --git a/crates/signed_git/src/patch.rs b/crates/signed_git/src/patch.rs index b9883a1..f2c7935 100644 --- a/crates/signed_git/src/patch.rs +++ b/crates/signed_git/src/patch.rs @@ -3,7 +3,7 @@ use diffy::patch_set::{FileOperation, FilePatch, ParseOptions, PatchSet}; use diffy::{Hunk, Line}; use crate::diff::{CommitDiff, DiffHunk, DiffLineKind, DiffStatus, FileDiff, HunkBuilder}; -use crate::history::FileCommit; +use crate::history::{FileCommit, format_commit_date}; pub struct PatchParser; @@ -37,6 +37,10 @@ impl PatchParser { .into_iter() .filter(|message| !message.id.is_empty()) .map(|message| { + let time = message + .header("Date") + .and_then(|value| gix::date::parse(value.trim(), None).ok()); + FileCommit::new( message.id.to_string(), message @@ -48,11 +52,9 @@ impl PatchParser { .header("From") .map(Self::name_from_address) .unwrap_or_default(), - message - .header("Date") - .and_then(|value| gix::date::parse(value.trim(), None).ok()) - .map(|time| time.seconds) - .unwrap_or(0), + time.map(|time| time.seconds).unwrap_or(0), + time.map(format_commit_date).unwrap_or_default(), + Vec::new(), ) }) .collect() diff --git a/crates/signed_git/src/repo.rs b/crates/signed_git/src/repo.rs index e20b638..4cae1bc 100644 --- a/crates/signed_git/src/repo.rs +++ b/crates/signed_git/src/repo.rs @@ -10,7 +10,7 @@ use gix::progress::Discard; use nostr::prelude::*; use crate::GixResultExt as _; -use crate::diff::{CommitDiff, DiffStatus, FileDiff, HunkCollector}; +use crate::diff::{CommitDiff, DiffStatus, FileDiff, HunkCollector, PatchCollector}; use crate::history::{CommitList, FileCommit, MAX_LISTED_COMMITS}; use crate::nip34::{GraspSignals, Nip34Binding, Nip34Json, Nip34Kind}; use crate::sync::{RefSync, RepoSyncStatus}; @@ -481,6 +481,151 @@ impl Repo { Self::tree_diff(self, old_tree.as_ref(), &new_tree) } + /// Produces the unified diff patch text of a commit against its first parent. + pub fn commit_patch(&self, id: &str) -> Result { + use gix::diff::blob::platform::prepare_diff::Operation; + use gix::object::tree::diff::Change; + use gix::objs::tree::EntryKind; + + let commit_id = self.inner.rev_parse_single(id.as_bytes())?; + let commit = commit_id.object()?.into_commit(); + let new_tree = commit.tree()?; + let old_tree = match commit.parent_ids().next() { + Some(parent) => Some(parent.object()?.into_commit().tree()?), + None => None, + }; + + let changes = self + .inner + .diff_tree_to_tree(old_tree.as_ref(), Some(&new_tree), None)?; + + let mut cache = self.inner.diff_resource_cache_for_tree_diff()?; + let mut patch = String::new(); + + for change in changes { + let attached = Change::from_change_ref(change.to_ref(), &self.inner, &self.inner); + + let (path, old_path, status, mode) = match attached { + Change::Addition { + location, + entry_mode, + .. + } if !matches!(entry_mode.kind(), EntryKind::Tree | EntryKind::Commit) => { + (location.to_owned(), None, DiffStatus::Added, entry_mode) + } + Change::Deletion { + location, + entry_mode, + .. + } if !matches!(entry_mode.kind(), EntryKind::Tree | EntryKind::Commit) => { + (location.to_owned(), None, DiffStatus::Deleted, entry_mode) + } + Change::Modification { + location, + previous_entry_mode, + entry_mode, + .. + } if !matches!(entry_mode.kind(), EntryKind::Tree | EntryKind::Commit) + && !matches!( + previous_entry_mode.kind(), + EntryKind::Tree | EntryKind::Commit + ) => + { + (location.to_owned(), None, DiffStatus::Modified, entry_mode) + } + Change::Rewrite { + location, + source_location, + source_entry_mode, + entry_mode, + copy, + .. + } if !matches!(entry_mode.kind(), EntryKind::Tree | EntryKind::Commit) + && !matches!( + source_entry_mode.kind(), + EntryKind::Tree | EntryKind::Commit + ) => + { + let status = if copy { + DiffStatus::Copied + } else { + DiffStatus::Renamed + }; + ( + location.to_owned(), + Some(source_location.to_owned()), + status, + entry_mode, + ) + } + _ => continue, + }; + + let old = String::from_utf8_lossy(old_path.as_ref().unwrap_or(&path)).into_owned(); + let new = String::from_utf8_lossy(&path).into_owned(); + patch.push_str(&format!("diff --git a/{old} b/{new}\n")); + + match status { + DiffStatus::Added => { + patch.push_str(&format!("new file mode {:o}\n", mode.value())); + } + DiffStatus::Deleted => { + patch.push_str(&format!("deleted file mode {:o}\n", mode.value())); + } + DiffStatus::Renamed => { + patch.push_str(&format!("rename from {old}\nrename to {new}\n")); + } + DiffStatus::Copied => { + patch.push_str(&format!("copy from {old}\ncopy to {new}\n")); + } + DiffStatus::Modified => {} + } + + if status == DiffStatus::Added { + patch.push_str("--- /dev/null\n"); + } else { + patch.push_str(&format!("--- a/{old}\n")); + } + + if status == DiffStatus::Deleted { + patch.push_str("+++ /dev/null\n"); + } else { + patch.push_str(&format!("+++ b/{new}\n")); + } + + let platform = attached.diff(&mut cache)?; + platform + .resource_cache + .options + .skip_internal_diff_if_external_is_configured = true; + + let outcome = platform.resource_cache.prepare_diff().into_anyhow()?; + + match outcome.operation { + Operation::InternalDiff { algorithm } => { + let input = outcome.interned_input(); + let diff = gix::diff::blob::diff_with_slider_heuristics(algorithm, &input); + let text = gix::diff::blob::UnifiedDiff::new( + &diff, + &input, + PatchCollector::new(), + Default::default(), + ) + .consume()?; + patch.push_str(&text); + } + Operation::SourceOrDestinationIsBinary => { + patch.push_str(&format!("Binary files a/{old} and b/{new} differ\n")); + } + Operation::ExternalCommand { .. } => { + unreachable!("external diff drivers are disabled") + } + } + } + + Ok(patch) + } + /// Diffs the trees of `base` and `tip` directly, files sorted by path. pub fn range_diff(&self, base: &str, tip: &str) -> Result { let base_tree = self @@ -1810,6 +1955,44 @@ mod tests { assert!(binding_of(&path).is_none()); } + #[test] + fn commit_patch_applies_cleanly_to_parent() { + let (dir, path) = init_repo(); + git(&path, &["config", "user.name", "Test Author"]); + git(&path, &["config", "user.email", "test@example.com"]); + std::fs::write(path.join("file.txt"), "one\n").expect("write"); + git(&path, &["add", "."]); + git(&path, &["commit", "-q", "-m", "first"]); + std::fs::write(path.join("file.txt"), "two\n").expect("write"); + std::fs::write(path.join("file2.txt"), "added\n").expect("write"); + git(&path, &["add", "."]); + git(&path, &["commit", "-q", "-m", "second"]); + + let patch = Repo::open(&path) + .expect("open repo") + .commit_patch("HEAD") + .expect("commit patch"); + assert!(patch.contains("diff --git a/file.txt b/file.txt")); + assert!(patch.contains("diff --git a/file2.txt b/file2.txt")); + assert!(patch.contains("--- /dev/null")); + assert!(patch.contains("+added")); + + let patch_path = dir.path().join("head.patch"); + std::fs::write(&patch_path, &patch).expect("write patch"); + git(&path, &["checkout", "-q", "--detach", "HEAD~1"]); + git( + &path, + &["apply", patch_path.to_str().expect("utf8 patch path")], + ); + + let applied = std::fs::read_to_string(path.join("file.txt")).expect("read"); + assert_eq!(applied, "two\n"); + assert_eq!( + std::fs::read_to_string(path.join("file2.txt")).expect("read"), + "added\n" + ); + } + #[test] fn nak_exclude_and_state_refs_are_detected() { let (_dir, path) = init_repo(); diff --git a/crates/ui/src/components/badge.rs b/crates/ui/src/components/badge.rs index 4b00d8a..30b44d7 100644 --- a/crates/ui/src/components/badge.rs +++ b/crates/ui/src/components/badge.rs @@ -181,3 +181,95 @@ impl RenderOnce for Badge { }) } } + +/// A pill pairing a green additions segment with a red deletions segment. +#[derive(IntoElement)] +#[must_use] +pub struct GroupedBadge { + id: ElementId, + insertions: usize, + deletions: usize, + style: StyleRefinement, +} + +impl GroupedBadge { + /// Creates a grouped badge from insertion and deletion counts. + pub fn new(id: I, insertions: usize, deletions: usize) -> Self + where + I: Into, + { + Self { + id: id.into(), + insertions, + deletions, + style: StyleRefinement::default(), + } + } +} + +impl gpui::Styled for GroupedBadge { + fn style(&mut self) -> &mut gpui::StyleRefinement { + &mut self.style + } +} + +impl RenderOnce for GroupedBadge { + fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement { + let theme = cx.theme(); + + let additions = ( + theme.ramps.success.base.opacity(0.2), + theme.ramps.success.base, + ); + + let deletions = ( + theme.ramps.destructive.base.opacity(0.2), + theme.ramps.destructive.base, + ); + + h_flex() + .id(self.id.clone()) + .debug_selector({ + let id = self.id.clone(); + move || format!("{id}") + }) + .flex_none() + .text_xs() + .font_medium() + .when(self.insertions > 0, |group| { + group.child( + h_flex() + .justify_center() + .h_5() + .px_1p5() + .bg(additions.0) + .text_color(additions.1) + .debug_selector({ + let id = self.id.clone(); + move || format!("{id}-additions") + }) + .when(self.deletions == 0, |segment| segment.rounded_full()) + .when(self.deletions > 0, |segment| segment.rounded_l_full()) + .child(SharedString::from(format!("+{}", self.insertions))), + ) + }) + .when(self.deletions > 0, |group| { + group.child( + h_flex() + .justify_center() + .h_5() + .px_1p5() + .bg(deletions.0) + .text_color(deletions.1) + .debug_selector({ + let id = self.id.clone(); + move || format!("{id}-deletions") + }) + .when(self.insertions == 0, |segment| segment.rounded_full()) + .when(self.insertions > 0, |segment| segment.rounded_r_full()) + .child(SharedString::from(format!("-{}", self.deletions))), + ) + }) + .refine_style(&self.style) + } +} diff --git a/crates/ui/src/components/button.rs b/crates/ui/src/components/button.rs index 555b368..32969bc 100644 --- a/crates/ui/src/components/button.rs +++ b/crates/ui/src/components/button.rs @@ -326,6 +326,8 @@ impl RenderOnce for Button { h_flex() .id(self.id.clone()) + .refine_style(&self.style) + .flex_shrink_0() .when_some(self.debug_selector, |button, selector| { button.debug_selector(move || selector()) }) @@ -351,7 +353,6 @@ impl RenderOnce for Button { .border_color(border) .when_some(background, |button, background| button.bg(background)) .text_color(foreground) - .refine_style(&self.style) .when_some(a11y_label, |button, label| button.aria_label(label)) .child( h_flex() diff --git a/crates/ui/src/components/switch.rs b/crates/ui/src/components/switch.rs index f64ea8e..fc181ee 100644 --- a/crates/ui/src/components/switch.rs +++ b/crates/ui/src/components/switch.rs @@ -133,7 +133,7 @@ impl RenderOnce for Switch { h_flex() .id(self.id) - .gap_2() + .gap_1() .control_text(self.size) .refine_style(&self.style) .role(Role::Switch) @@ -179,7 +179,11 @@ impl RenderOnce for Switch { .left(inset) .switch_knob(self.size) .rounded(theme.radius.full) - .bg(colors.primary_foreground) + .bg(if self.checked { + colors.primary_foreground + } else { + colors.muted_foreground + }) .with_spring("switch-thumb", anim, move |thumb, offset| { thumb.left(inset + offset) }), diff --git a/crates/ui/src/icons/assets/download.svg b/crates/ui/src/icons/assets/download.svg new file mode 100644 index 0000000..60c0474 --- /dev/null +++ b/crates/ui/src/icons/assets/download.svg @@ -0,0 +1 @@ + diff --git a/crates/ui/src/icons/assets/panel-left.svg b/crates/ui/src/icons/assets/panel-left.svg new file mode 100644 index 0000000..90c72c4 --- /dev/null +++ b/crates/ui/src/icons/assets/panel-left.svg @@ -0,0 +1 @@ + diff --git a/crates/ui/src/icons/assets/unfold-vertical.svg b/crates/ui/src/icons/assets/unfold-vertical.svg new file mode 100644 index 0000000..a2f4d32 --- /dev/null +++ b/crates/ui/src/icons/assets/unfold-vertical.svg @@ -0,0 +1 @@ + diff --git a/crates/ui/src/icons/mod.rs b/crates/ui/src/icons/mod.rs index f2b24cd..76c60d6 100644 --- a/crates/ui/src/icons/mod.rs +++ b/crates/ui/src/icons/mod.rs @@ -59,6 +59,9 @@ pub enum IconRole { ArrowUp, Inbox, Stack, + PanelLeft, + UnfoldVertical, + Download, } impl IconRole { @@ -106,6 +109,9 @@ impl IconRole { Self::ArrowUp => "arrow-up", Self::Inbox => "inbox", Self::Stack => "stack", + Self::PanelLeft => "panel-left", + Self::UnfoldVertical => "unfold-vertical", + Self::Download => "download", } }