diff --git a/CHANGELOG.md b/CHANGELOG.md index 82bc178..1b31b51 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,10 @@ All notable changes to `diffs-rs` are recorded here. The forked crates in - `Engine::set_markers` draws host markers in the gutter for ranges of source lines. - `Engine::reveal` moves the cursor to a source line, and `Engine::select_range` selects a range of source lines as the user would. +- The Files sidebar and the file headers color each status by kind (added, modified, deleted, + renamed or copied) and show `+N` in the addition color and `−N` in the deletion color, as + Hunk does. Folder totals use the same count colors. `theme::Colors` gains `modified` and + `renamed`, which breaks code that builds `Colors` by hand. ## 0.1.0 - 2026-10-27 diff --git a/README.md b/README.md index fadc9df..5d7aa05 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,8 @@ the viewer for all key bindings. - Syntax colors for the bundled grammars, with changed-word emphasis. - For `files` and `git`, colors are computed from the complete old and new sources, and unchanged gaps can be expanded 20 lines at a time. -- A changed-file sidebar with the patch's directory tree and per-file and per-folder counts. +- A changed-file sidebar with the patch's directory tree, per-file status, and per-file and + per-folder counts, colored by kind of change. - Large patches open progressively; the first screen appears while the rest is still indexing. - Literal search across the whole diff (`/`, F3). - Source-line selection (`V`), saving the original bytes (Ctrl-S), and plain-text copy (`y`, macOS). diff --git a/docs/design/SIDEBAR_SPEC.md b/docs/design/SIDEBAR_SPEC.md index e786e35..dfb22d9 100644 --- a/docs/design/SIDEBAR_SPEC.md +++ b/docs/design/SIDEBAR_SPEC.md @@ -71,6 +71,10 @@ Folder totals include every descendant file, regardless of expansion or scrollin Totals use checked arithmetic and never wrap silently. Binary entries show their binary status instead of a misleading textual `+0 -0` claim. Metadata-only entries remain selectable with their status and zero textual counts. +The status letter takes the theme color of its kind: the addition color for added files, the deletion color for deleted files, `terminal.ansiBlue` for modified and type-changed files, and `terminal.ansiMagenta` for renamed and copied files. +A nonzero `+N` takes the addition color and a nonzero `−N` the deletion color; zero counts, folder file counts, and binary entries stay muted. +The file header in the diff colors its status and counts the same way. Colors change only the text, never the row background, width, or layout. +With `NO_COLOR` set, the terminal backend drops every color and the text stays the same. Renames use the destination hierarchy. The diff header retains the existing old-to-new path display. ## 4. Layout and visibility diff --git a/src/render.rs b/src/render.rs index eaa92ff..5f970ed 100644 --- a/src/render.rs +++ b/src/render.rs @@ -13,6 +13,7 @@ mod sidebar; use crate::{ app::{App, Position}, model::{Kind, RowKind}, + theme::Colors, view::LineId, }; @@ -537,6 +538,7 @@ fn file_header(buf: &mut Buffer, app: &App, file: usize, x: u16, y: u16) { }; let summary = format!(" {} +{} −{} ", f.status, f.additions, f.deletions); let summary_width = summary.width().min(app.width as usize) as u16; + let summary_x = x + app.width.saturating_sub(summary_width); label( buf, x, @@ -549,7 +551,7 @@ fn file_header(buf: &mut Buffer, app: &App, file: usize, x: u16, y: u16) { ); label( buf, - x + app.width.saturating_sub(summary_width), + summary_x, y, summary_width, &summary, @@ -557,6 +559,21 @@ fn file_header(buf: &mut Buffer, app: &App, file: usize, x: u16, y: u16) { c.chrome, false, ); + color_summary( + buf, + summary_x, + y, + summary_width, + Summary { + at: 1, + lead: f.status.width() as u16, + lead_fg: status_color(c, &f.status), + gap: 3, + additions: f.additions, + deletions: f.deletions, + }, + c, + ); } fn draw_row( @@ -909,5 +926,57 @@ fn label( buf.set_stringn(x, y, text, width as usize, style); } +/// The color of a file status in the Files tree and file headers. +fn status_color(c: &Colors, status: &str) -> Color { + match status { + "Added" => c.added, + "Deleted" => c.deleted, + "Renamed" | "Copied" => c.renamed, + "Binary change" => c.dim, + _ => c.modified, + } +} + +/// The parts of a `STATUS +A −D` change summary that `color_summary` colors. +struct Summary { + /// The first cell of the status or file count. + at: u16, + /// The width of the status or file count. + lead: u16, + lead_fg: Color, + /// The cells between the status and `+A`. + gap: u16, + additions: usize, + deletions: usize, +} + +/// Colors a change summary already drawn as muted text from `x`: the status in its color, +/// `+A` in the addition color and `−D` in the deletion color. A zero count stays muted, as do +/// cells from `visible` on. +fn color_summary(buf: &mut Buffer, x: u16, y: u16, visible: u16, s: Summary, c: &Colors) { + let count = |n: usize, color: Color| if n == 0 { c.dim } else { color }; + let plus = s.at + s.lead + s.gap; + let minus = plus + 1 + digits(s.additions) + 1; + let spans = [ + (s.at, s.at + s.lead, s.lead_fg), + (plus, minus - 1, count(s.additions, c.added)), + ( + minus, + minus + 1 + digits(s.deletions), + count(s.deletions, c.deleted), + ), + ]; + for (start, end, fg) in spans { + for cell in start..end.min(visible) { + buf[(x + cell, y)].set_fg(fg); + } + } +} + +/// The number of decimal digits in `n`. +fn digits(n: usize) -> u16 { + n.checked_ilog10().map_or(1, |log| log as u16 + 1) +} + #[cfg(test)] mod tests; diff --git a/src/render/sidebar.rs b/src/render/sidebar.rs index 4feb469..ecea463 100644 --- a/src/render/sidebar.rs +++ b/src/render/sidebar.rs @@ -1,7 +1,7 @@ use ratatui::buffer::Buffer; use unicode_width::UnicodeWidthStr; -use super::{ellipsize, fill, label}; +use super::{Summary, color_summary, digits, ellipsize, fill, label, status_color}; use crate::{app::App, tree::Kind}; pub(super) const HELP: &str = " ↑/↓, j/k Move cursor; PgUp/PgDn page; Home/End bounds\n ←/→ Collapse / expand folders; parent / child\n Enter Open file or toggle folder; Space toggles\n Esc, Tab Return to diff; f hides Files\n Wheel Scroll the pane under the pointer\n * Current diff file; > keyboard cursor\n Esc, ? Close help\n q, Ctrl-C Quit / cancel"; @@ -56,7 +56,7 @@ pub(super) fn draw(buf: &mut Buffer, app: &App) { ratatui::layout::Rect::new(area.x, y, area.width, 1), bg, ); - let (name, summary, suffix) = match &node.kind { + let (name, summary, colors, suffix) = match &node.kind { Kind::Folder { expanded, .. } => ( format!("{} {}/", if *expanded { "▾" } else { "▸" }, node.label), format!( @@ -66,6 +66,14 @@ pub(super) fn draw(buf: &mut Buffer, app: &App) { node.totals.deletions, if node.totals.binary > 0 { " B" } else { "" } ), + Some(Summary { + at: 0, + lead: digits(node.totals.files), + lead_fg: c.dim, + gap: 1, + additions: node.totals.additions, + deletions: node.totals.deletions, + }), String::new(), ), Kind::File { id, occurrence } => { @@ -75,17 +83,27 @@ pub(super) fn draw(buf: &mut Buffer, app: &App) { } else { format!(" [{}]", occurrence) }; - let summary = if file.status.as_ref() == "Binary change" { - "B binary".into() + let (summary, colors) = if file.status.as_ref() == "Binary change" { + ("B binary".into(), None) } else { - format!( - "{} +{} −{}", - file.status.chars().next().unwrap_or('M'), - file.additions, - file.deletions + ( + format!( + "{} +{} −{}", + file.status.chars().next().unwrap_or('M'), + file.additions, + file.deletions + ), + Some(Summary { + at: 0, + lead: 1, + lead_fg: status_color(c, &file.status), + gap: 1, + additions: file.additions, + deletions: file.deletions, + }), ) }; - (node.label.clone(), summary, suffix) + (node.label.clone(), summary, colors, suffix) } }; let summary_width = summary.width().min(16) as u16; @@ -117,9 +135,10 @@ pub(super) fn draw(buf: &mut Buffer, app: &App) { bg, focused || current, ); + let summary_x = area.right() - summary_width - 1; label( buf, - area.right() - summary_width - 1, + summary_x, y, summary_width, &ellipsize(&summary, summary_width as usize), @@ -127,5 +146,14 @@ pub(super) fn draw(buf: &mut Buffer, app: &App) { bg, false, ); + if let Some(colors) = colors { + // A truncated summary ends in a muted ellipsis. + let visible = if summary.width() > usize::from(summary_width) { + summary_width.saturating_sub(1) + } else { + summary_width + }; + color_summary(buf, summary_x, y, visible, colors, c); + } } } diff --git a/src/render/tests.rs b/src/render/tests.rs index 04b3c43..23c30c8 100644 --- a/src/render/tests.rs +++ b/src/render/tests.rs @@ -1,6 +1,6 @@ use std::sync::mpsc; -use ratatui::{Terminal, backend::TestBackend, buffer::Buffer, layout::Rect}; +use ratatui::{Terminal, backend::TestBackend, buffer::Buffer, layout::Rect, style::Color}; use crate::{ app::{App, Layout}, @@ -23,10 +23,14 @@ fn standalone(width: u16) -> ReadingControls<'static> { } fn review(patch: &str, label: &str) -> App { + review_in(patch, label, Appearance::Dark) +} + +fn review_in(patch: &str, label: &str, appearance: Appearance) -> App { let mut doc = storage::Document::default(); storage::read(patch.as_bytes(), |file| doc.append(file)).unwrap(); let (wake, _) = mpsc::sync_channel(1); - let mut app = App::new(doc, label.into(), Layout::Split, Appearance::Dark, wake).unwrap(); + let mut app = App::new(doc, label.into(), Layout::Split, appearance, wake).unwrap(); app.loading = false; app } @@ -48,13 +52,22 @@ fn draw( height: u16, controls: Option<&ReadingControls<'_>>, ) -> Vec { + rows(&draw_buffer(app, width, height, controls)) +} + +fn draw_buffer( + app: &mut App, + width: u16, + height: u16, + controls: Option<&ReadingControls<'_>>, +) -> Buffer { let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); terminal .draw(|frame| { super::draw_with_controls(frame, app, frame.area(), None, controls).unwrap(); }) .unwrap(); - rows(terminal.backend().buffer()) + terminal.backend().buffer().clone() } fn rows(buffer: &Buffer) -> Vec { @@ -195,3 +208,219 @@ fn small_terminal_notice_wraps_instead_of_clipping() { ); } } + +/// An added, a copied, a deleted, a modified, and a renamed file under `src/`. +const KINDS: &str = "diff --git a/src/added.rs b/src/added.rs +new file mode 100644 +index 0000000..1111111 +--- /dev/null ++++ b/src/added.rs +@@ -0,0 +1,2 @@ ++fn added() {} ++fn more() {} +diff --git a/src/modified.rs b/src/modified.rs +index 2222222..3333333 100644 +--- a/src/modified.rs ++++ b/src/modified.rs +@@ -1 +1 @@ +-fn old() {} ++fn new() {} +diff --git a/src/deleted.rs b/src/deleted.rs +deleted file mode 100644 +index 4444444..0000000 +--- a/src/deleted.rs ++++ /dev/null +@@ -1,2 +0,0 @@ +-fn gone() {} +-fn also() {} +diff --git a/old.rs b/src/renamed.rs +similarity index 100% +rename from old.rs +rename to src/renamed.rs +diff --git a/src/modified.rs b/src/copied.rs +similarity index 100% +copy from src/modified.rs +copy to src/copied.rs +"; + +/// The foreground and background of each cell of `text` on the first row of `area` that +/// contains `row` and then `text`. +fn styled(buffer: &Buffer, area: Rect, row: &str, text: &str) -> Vec<(Color, Color)> { + for y in area.top()..area.bottom() { + let line = (area.left()..area.right()) + .map(|x| buffer[(x, y)].symbol()) + .collect::(); + let Some(start) = line.find(row) else { + continue; + }; + let Some(found) = line[start..].find(text) else { + continue; + }; + let column = line[..start + found].chars().count() as u16; + return (0..text.chars().count() as u16) + .map(|n| { + let cell = &buffer[(area.x + column + n, y)]; + (cell.fg, cell.bg) + }) + .collect(); + } + panic!("no {row:?} row with {text:?}:\n{}", rows(buffer).join("\n")); +} + +/// The foreground of each cell of `text`, in the row containing `row`. +fn fg(buffer: &Buffer, area: Rect, row: &str, text: &str) -> Vec { + styled(buffer, area, row, text) + .into_iter() + .map(|(fg, _)| fg) + .collect() +} + +#[test] +fn sidebar_colors_status_letters_and_counts_by_kind() { + for (appearance, modified, renamed) in [ + ( + Appearance::Dark, + Color::Rgb(0x00, 0x9f, 0xff), + Color::Rgb(0xe1, 0x30, 0xac), + ), + ( + Appearance::Light, + Color::Rgb(0x1a, 0x85, 0xd4), + Color::Rgb(0xbd, 0x2e, 0x90), + ), + ] { + let mut app = review_in(KINDS, "kinds.patch", appearance); + let buffer = draw_buffer(&mut app, 160, 24, None); + let tree = app.sidebar.area; + let c = app.colors.clone(); + assert_eq!( + (c.modified, c.renamed), + (modified, renamed), + "{appearance:?}" + ); + let (add, del, dim) = (c.added, c.deleted, c.dim); + for (row, summary, expected) in [ + ("added.rs", "A +2 −0", [add, dim, add, add, dim, dim, dim]), + ( + "modified.rs", + "M +1 −1", + [modified, dim, add, add, dim, del, del], + ), + ("deleted.rs", "D +0 −2", [del, dim, dim, dim, dim, del, del]), + ( + "renamed.rs", + "R +0 −0", + [renamed, dim, dim, dim, dim, dim, dim], + ), + ( + "copied.rs", + "C +0 −0", + [renamed, dim, dim, dim, dim, dim, dim], + ), + // A folder's file count stays muted; its aggregate counts are colored. + ("src/", "5 +3 −3", [dim, dim, add, add, dim, del, del]), + ] { + let cells = styled(&buffer, tree, row, summary); + assert_eq!( + cells.iter().map(|(fg, _)| *fg).collect::>(), + expected, + "{appearance:?} {row}" + ); + // Colors change only the text: the row keeps the sidebar background. + assert!(cells.iter().all(|(_, bg)| *bg == c.chrome), "{row}"); + } + // The text and layout are unchanged. + let text = rows(&buffer); + let folder = text[2].chars().take(33).collect::(); + assert_eq!(folder, " ▾ src/ 5 +3 −3 │"); + let file = text[3].chars().take(33).collect::(); + assert_eq!(file, " * added.rs A +2 −0 │"); + // The sticky file header colors its status and counts the same way. + let diff = app.sidebar.diff; + assert_eq!(fg(&buffer, diff, "src/added.rs", "Added"), [add; 5]); + assert_eq!( + fg(&buffer, diff, "src/added.rs", "+2 −0"), + [add, add, dim, dim, dim] + ); + } +} + +#[test] +fn sidebar_cursor_row_keeps_kind_colors_on_its_highlight() { + let mut app = review(KINDS, "kinds.patch"); + draw_buffer(&mut app, 160, 24, None); + // Focusing Files puts the keyboard cursor on the current file, `added.rs`. + app.files_command().unwrap(); + let buffer = draw_buffer(&mut app, 160, 24, None); + let c = app.colors.clone(); + let cells = styled(&buffer, app.sidebar.area, ">*", "A +2 −0"); + assert_eq!( + cells, + [c.added, c.dim, c.added, c.added, c.dim, c.dim, c.dim] + .map(|fg| (fg, c.context)) + .to_vec() + ); + let name = styled(&buffer, app.sidebar.area, ">*", "added.rs"); + assert!(name.iter().all(|(fg, bg)| (*fg, *bg) == (c.fg, c.context))); + // Other rows keep the sidebar background. + let other = styled(&buffer, app.sidebar.area, "modified.rs", "M +1 −1"); + assert!(other.iter().all(|(_, bg)| *bg == c.chrome)); +} + +#[test] +fn file_headers_color_each_status_kind() { + let mut app = review(KINDS, "kinds.patch"); + // Every file header fits on one screen. + let buffer = draw_buffer(&mut app, 160, 40, None); + let c = app.colors.clone(); + let diff = app.sidebar.diff; + for (path, status, color) in [ + ("src/added.rs", "Added", c.added), + ("src/modified.rs", "Modified", c.modified), + ("src/deleted.rs", "Deleted", c.deleted), + ("old.rs → src/renamed.rs", "Renamed", c.renamed), + ("src/modified.rs → src/copied.rs", "Copied", c.renamed), + ] { + assert_eq!( + fg(&buffer, diff, path, status), + vec![color; status.len()], + "{path}" + ); + } + assert_eq!( + fg(&buffer, diff, "src/modified.rs ", "+1 −1"), + [c.added, c.added, c.dim, c.deleted, c.deleted] + ); +} + +#[test] +fn truncated_summaries_keep_a_muted_ellipsis() { + let (wake, _) = mpsc::sync_channel(1); + let app = App::new( + storage::Document::default(), + "empty".into(), + Layout::Split, + Appearance::Dark, + wake, + ) + .unwrap(); + let c = &app.colors; + let mut buffer = Buffer::empty(Rect::new(0, 0, 16, 1)); + let text = super::ellipsize("2188 +1009257 −4024", 16); + assert_eq!(text, "2188 +1009257 −…"); + super::label(&mut buffer, 0, 0, 16, &text, c.dim, c.chrome, false); + let summary = super::Summary { + at: 0, + lead: 4, + lead_fg: c.dim, + gap: 1, + additions: 1_009_257, + deletions: 4024, + }; + super::color_summary(&mut buffer, 0, 0, 15, summary, c); + let colors = (0..16).map(|x| buffer[(x, 0)].fg).collect::>(); + let mut expected = vec![c.dim; 5]; + expected.extend([c.added; 8]); + expected.extend([c.dim, c.deleted, c.dim]); + assert_eq!(colors, expected); +} diff --git a/src/theme.rs b/src/theme.rs index cd413e3..497a0d3 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -42,6 +42,10 @@ pub struct Colors { pub added: Color, pub deleted: Color, pub accent: Color, + /// The status color of a modified file in the Files tree and file headers. + pub modified: Color, + /// The status color of a renamed or copied file in the Files tree and file headers. + pub renamed: Color, pub add_bg: Color, pub del_bg: Color, pub add_word: Color, @@ -96,6 +100,10 @@ pub fn load(appearance: Appearance) -> Result<(Colors, Theme)> { dim: get("editorLineNumber.foreground")?, chrome: get("sideBar.background")?, accent: get("gitDecoration.modifiedResourceForeground")?, + // The terminal blue matches the modified accent in dark and is darker in light, where + // the accent is too faint for a single status letter on the sidebar background. + modified: get("terminal.ansiBlue")?, + renamed: get("terminal.ansiMagenta")?, separator: lab_mix(bg, fg, if dark { 0.15 } else { 0.04 }), empty: lab_mix(bg, fg, if dark { 0.18 } else { 0.10 }), context: lab_mix(bg, fg, if dark { 0.075 } else { 0.015 }), diff --git a/tests/process.rs b/tests/process.rs index 6a1f122..566ace1 100644 --- a/tests/process.rs +++ b/tests/process.rs @@ -375,7 +375,12 @@ impl Session { } } - fn spawn(mut cmd: CommandBuilder) -> Self { + fn spawn(cmd: CommandBuilder) -> Self { + Self::spawn_colored(cmd, true) + } + + /// Spawns the viewer with truecolor, or with `NO_COLOR` set when `color` is false. + fn spawn_colored(mut cmd: CommandBuilder, color: bool) -> Self { let pair = NativePtySystem::default() .openpty(PtySize { rows: 50, @@ -387,7 +392,11 @@ impl Session { let initial_modes = format!("{:?}", pair.master.get_termios().unwrap()); cmd.env("TERM", "xterm-256color"); cmd.env("COLORTERM", "truecolor"); - cmd.env_remove("NO_COLOR"); + if color { + cmd.env_remove("NO_COLOR"); + } else { + cmd.env("NO_COLOR", "1"); + } let child = pair.slave.spawn_command(cmd).unwrap(); drop(pair.slave); let mut reader = pair.master.try_clone_reader().unwrap(); diff --git a/tests/process/sidebar_contract.rs b/tests/process/sidebar_contract.rs index fe72631..ed3aab6 100644 --- a/tests/process/sidebar_contract.rs +++ b/tests/process/sidebar_contract.rs @@ -176,6 +176,96 @@ fn sidebar_real_git_hierarchy_counts_status_activation_and_focus() { terminal.finish(b"q", 0); } +/// The foreground of each cell of `summary` in the tree row that shows `name`. +fn summary_colors(screen: &vt100::Screen, name: &str, summary: &str) -> Vec { + let (y, row) = (1..screen.size().0 - 1) + .map(|y| (y, cells(screen, y, 0, 32))) + .find(|(_, row)| row.contains(name)) + .unwrap_or_else(|| panic!("no {name} row:\n{}", tree_text(screen))); + let x = row[..row.find(summary).unwrap_or_else(|| panic!("{row:?}"))] + .chars() + .count() as u16; + (x..x + summary.chars().count() as u16) + .map(|x| screen.cell(y, x).unwrap().fgcolor()) + .collect() +} + +#[test] +fn sidebar_status_letters_and_counts_reach_the_terminal_in_color() { + use vt100::Color::Rgb; + let (_dir, path) = repository_patch(); + let mut terminal = open(&path, &[]); + terminal.settled_grid(); + let dim = Rgb(115, 115, 115); + // Dark, then light: added, deleted, modified, renamed. + for (keys, a, d, m, r) in [ + ( + &b""[..], + Rgb(7, 196, 128), + Rgb(255, 46, 63), + Rgb(0, 159, 255), + Rgb(225, 48, 172), + ), + ( + b"t", + Rgb(24, 164, 108), + Rgb(213, 44, 54), + Rgb(26, 133, 212), + Rgb(189, 46, 144), + ), + ] { + input(&mut terminal, keys); + let screen = terminal.parser.screen(); + for (name, summary, expected) in [ + ("README.md", "A +1 −0", [a, dim, a, a, dim, dim, dim]), + ("removed.rs", "D +0 −1", [d, dim, dim, dim, dim, d, d]), + ("value.rs", "M +3 −1", [m, dim, a, a, dim, d, d]), + ("renamed.rs", "R +0 −0", [r, dim, dim, dim, dim, dim, dim]), + ("script.sh", "M +0 −0", [m, dim, dim, dim, dim, dim, dim]), + ("src/", "1 +3 −1", [dim, dim, a, a, dim, d, d]), + ] { + assert_eq!( + summary_colors(screen, name, summary), + expected, + "{name} after {keys:?}" + ); + } + assert_eq!( + summary_colors(screen, "icon.bin", "B binary"), + [dim; 8], + "binary after {keys:?}" + ); + } + terminal.finish(b"q", 0); +} + +#[test] +fn sidebar_no_color_keeps_the_same_text_without_colors() { + let (_dir, path) = repository_patch(); + let mut colored = open(&path, &[]); + colored.settled_grid(); + let mut command = CommandBuilder::new(viewer_binary()); + command.arg("patch"); + command.arg(&path); + let mut plain = Session::spawn_colored(command, false); + plain.settled_grid(); + let screen = plain.parser.screen(); + assert_eq!(tree_text(screen), tree_text(colored.parser.screen())); + assert!(tree_text(screen).contains("M +3 −1")); + for y in 1..screen.size().0 - 1 { + for x in 0..32 { + let cell = screen.cell(y, x).unwrap(); + assert_eq!( + (cell.fgcolor(), cell.bgcolor()), + (vt100::Color::Default, vt100::Color::Default), + "cell {x},{y}" + ); + } + } + colored.finish(b"q", 0); + plain.finish(b"q", 0); +} + #[test] fn sidebar_mouse_translation_wrap_and_resize_preserve_exact_text_anchor() { let line = format!(