diff --git a/CHANGELOG.md b/CHANGELOG.md index da47913..30203e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,15 @@ All notable changes to `diffs-rs` are recorded here. The forked crates in `crates/` keep their own changelogs. +## 0.2.1 - Unreleased + +- `Engine::set_file_marks` lets the host mark files in the Files sidebar, for example as + viewed. A `FileMark` names a file by path and carries an optional `Badge` of one or two + cells in a `BadgeColor` from the theme, and a `dimmed` flag that mutes the row. The badge + has its own column at the right of every row, so rows stay aligned, and a folder shows a + badge when every file under it has the same one. Hosts that never call it, and the `diffs` + viewer, look as before. + ## 0.2.0 - 2026-11-15 - `Options.chrome`: set it to `false` and the engine draws no label row, footer or help diff --git a/docs/design/SIDEBAR_SPEC.md b/docs/design/SIDEBAR_SPEC.md index dfb22d9..88a95e6 100644 --- a/docs/design/SIDEBAR_SPEC.md +++ b/docs/design/SIDEBAR_SPEC.md @@ -102,6 +102,9 @@ Each tree row occupies one terminal row. Long labels truncate visibly at grapheme boundaries without overwriting status or counts. Indentation preserves directory depth. Excessive indentation is clipped with a visible overflow cue. The focused row and current diff file have distinct indicators, not color alone. +An embedding host can mark files with `Engine::set_file_marks`: a badge of one or two cells in a three-cell column between the counts and the divider, and a dimmed row. +The column exists only once the host sets marks, so the standalone viewer's rows are unchanged. Labels truncate before the badge does. +A folder shows a badge when every file under it has the same one, and is dimmed when every file under it is dimmed. The footer changes its control hints with keyboard focus. Errors and incomplete-input status take precedence over ordinary hints. diff --git a/docs/embedding.md b/docs/embedding.md index c10a4e5..497c012 100644 --- a/docs/embedding.md +++ b/docs/embedding.md @@ -142,6 +142,33 @@ Markers for lines that are not displayed, or for files that have not arrived yet `set_markers` rejects the whole set, keeping the previous one, if any range belongs to another review or has `first` of 0 or greater than `last`. It also fails after `close()`. `replace()` and `close()` drop the markers. Set them again for the new review with its `review_id()`. +### File marks + +`set_file_marks(&[FileMark])` replaces every file mark with a new set. A `FileMark` decorates the Files sidebar row of a file: + +```rust +use diffs_rs::engine::{Badge, BadgeColor, FileMark}; + +engine.set_file_marks(&[FileMark { + path: "src/lib.rs", + badge: Some(Badge { text: "✓", color: BadgeColor::Added }), + dimmed: true, +}])?; +``` + +- `path` is the file's `file(index).path`: the new path, or the old path of a deleted file. Every file with that path gets the mark, so a path that appears twice in a `git log -p` patch is marked twice. +- `badge` is one or two terminal cells of printable text. `BadgeColor` names a theme color (`Text`, `Muted`, `Accent`, `Added`, `Deleted`, `Modified`, `Renamed`), so the badge follows the dark and light themes. +- `dimmed` draws the row's name, status and counts in the muted color. The badge keeps its color. + +From the first call, every row keeps a badge column of three cells (a gap and two badge cells) between its counts and the divider, so rows with and without a badge stay aligned. Long names are shortened to make room; the badge is never cut. +The column stays, even for an empty set, until `replace()` or `close()`. Call `set_file_marks(&[])` when the review opens if the first badge should not shift the rows. +A folder row shows a badge when every file under it has the same badge, text and color, and is dimmed when every file under it is dimmed. The engine computes this, collapsed folders included, because the host does not see the tree's folders. While a patch is loading, folders count the files that have arrived. + +Marks for paths that are not in the review draw nothing, and marks can be set before the first file arrives. Later marks for the same path win. +`set_file_marks` redraws the sidebar only; the diff does not reflow. It costs one hash of each path in the set plus one pass over the files already in the tree, so it can run on every toggle. +It rejects the whole set, keeping the previous one, if a badge is empty, wider than two cells or contains control characters. It also fails after `close()`. +`replace()` and `close()` drop the marks and the badge column. The standalone viewer never sets marks. + ### Source reading and search `source_read(SourceRange)` prepares an original-side range with inclusive source-line coordinates. @@ -216,6 +243,7 @@ Use full commit IDs to keep Git inputs fixed across repeated opens. A symbolic r The left pane belongs to the host. Tab switches outer focus; `r` opens the next review, `c` closes the review without exiting, `o` reopens it, and `q` exits the host. `m` marks the selection (Shift-click to make one) or the cursor line with a gutter marker, and `'` selects the last mark again with `select_range`. +`v` marks the cursor's file viewed, or unmarks it, with `set_file_marks`: a `✓` and a dimmed row in the Files sidebar, which `f` shows. `--no-chrome` turns off the viewer's label row, footer and help; the host then draws its own status row from `status()` below the viewer. These are example-host controls, not additional viewer bindings. The example uses the current terminal and does not open windows or change preferences. diff --git a/examples/embedded_viewer.rs b/examples/embedded_viewer.rs index bb8ba97..5c6013d 100644 --- a/examples/embedded_viewer.rs +++ b/examples/embedded_viewer.rs @@ -16,7 +16,9 @@ use crossterm::{ LeaveAlternateScreen, }, }; -use diffs_rs::engine::{Engine, Input, Layout, Marker, Options, Side, SidebarPreference}; +use diffs_rs::engine::{ + Badge, BadgeColor, Engine, FileMark, Input, Layout, Marker, Options, Side, SidebarPreference, +}; use diffs_rs::input::LocalInput; use diffs_rs::reading::SourceRange; use ratatui::{ @@ -191,7 +193,7 @@ fn host_text(engine: &Engine, review: usize, focus: bool) -> Result { Ok(format!( "Host pane\nFocus: {focus}\nReview: {}\nState: {state}\n\n{location}\n\n\ Tab switch focus\nr next review\no reopen review\nc close review\n\ - m mark selection\n' select last mark\nq exit host\n\n\ + m mark selection\n' select last mark\nv mark file viewed\nq exit host\n\n\ Viewer keys stay local.", review + 1 )) @@ -247,6 +249,35 @@ fn mark(engine: &mut Engine, marks: &mut Vec) -> Result<()> { engine.set_markers(marks) } +/// Marks the cursor's file viewed, or unmarks it: a tick in the Files sidebar and a dimmed row. +fn toggle_viewed(engine: &mut Engine, viewed: &mut Vec) -> Result<()> { + let Some(source) = engine.selected_source()? else { + return Ok(()); + }; + let Some(file) = engine.file(source.file) else { + return Ok(()); + }; + let path = file.path.to_string(); + match viewed.iter().position(|p| *p == path) { + Some(index) => { + viewed.remove(index); + } + None => viewed.push(path), + } + let marks: Vec> = viewed + .iter() + .map(|path| FileMark { + path, + badge: Some(Badge { + text: "✓", + color: BadgeColor::Added, + }), + dimmed: true, + }) + .collect(); + engine.set_file_marks(&marks) +} + fn run() -> Result<()> { let Arguments { inputs, chrome } = review_inputs()?; let (wake, ready) = mpsc::sync_channel(1); @@ -271,6 +302,7 @@ fn run() -> Result<()> { wake, )?; let mut marks = Vec::new(); + let mut viewed = Vec::new(); let mut focus = true; let mut dirty = true; let mut resized = false; @@ -343,6 +375,7 @@ fn run() -> Result<()> { KeyCode::Char('c') => { engine.close()?; marks.clear(); + viewed.clear(); dirty = true; continue; } @@ -352,6 +385,7 @@ fn run() -> Result<()> { } engine.replace(inputs[review].open())?; marks.clear(); + viewed.clear(); dirty = true; continue; } @@ -360,6 +394,11 @@ fn run() -> Result<()> { dirty = true; continue; } + KeyCode::Char('v') if !engine.status().closed => { + toggle_viewed(&mut engine, &mut viewed)?; + dirty = true; + continue; + } KeyCode::Char('\'') => { // A mark on revealed context leaves the diff if its source is // withdrawn; the error is recoverable, so drop that mark. diff --git a/src/app/sidebar.rs b/src/app/sidebar.rs index ce69465..49785a0 100644 --- a/src/app/sidebar.rs +++ b/src/app/sidebar.rs @@ -1,7 +1,10 @@ use ratatui::layout::Rect; use super::{App, Position}; -use crate::tree::{FileId, Kind, NodeId, Tree}; +use crate::{ + engine::file_marks::FileMarks, + tree::{FileId, Kind, NodeId, Tree}, +}; const TREE_WIDTH: u16 = 32; const MIN_WIDTH: u16 = TREE_WIDTH + 1 + 64; @@ -33,6 +36,8 @@ pub(crate) struct Sidebar { pub area: Rect, pub diff: Rect, pub notice: Option<&'static str>, + /// The host's badges and dimming for file rows. + pub marks: FileMarks, } impl Sidebar { @@ -117,6 +122,16 @@ impl App { self.sidebar.preference = preference; } + /// Replaces the host's file marks on the files already in the tree; later files take + /// theirs as they are added. + pub(crate) fn set_file_marks(&mut self, marks: FileMarks) { + let files = &self.doc.files; + self.sidebar + .tree + .mark_files(|id| marks.get(&files[id.0].path)); + self.sidebar.marks = marks; + } + /// The pane height that view movement reasons about. It always counts the label and /// footer rows, so without chrome the diff rows fill the whole supplied rectangle. pub(crate) fn layout_height(&self, screen: u16) -> u16 { @@ -129,7 +144,9 @@ impl App { pub(crate) fn prepare_view(&mut self, screen: Rect) -> anyhow::Result<()> { for file in &self.doc.files[self.sidebar.tree.len()..] { - self.sidebar.tree.append(file)?; + self.sidebar + .tree + .append(file, self.sidebar.marks.get(&file.path))?; } let current = self.row(self.cursor.row).map(|row| FileId(row.file)); if current != self.sidebar.current { diff --git a/src/engine.rs b/src/engine.rs index e2d2330..3828e0d 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -1,5 +1,6 @@ //! A review owns its workers and view state, but never the host terminal. +pub(crate) mod file_marks; pub(crate) mod markers; mod reading; mod selection; @@ -29,6 +30,7 @@ use crate::{ text::{safe_label, safe_text}, theme::Appearance, }; +pub use file_marks::{Badge, BadgeColor, FileMark}; pub use markers::Marker; pub enum Input { @@ -123,6 +125,8 @@ pub struct Engine { area: Rect, /// Markers set before the first file arrived; the viewer state takes them when created. markers: markers::Markers, + /// File marks set before the first file arrived, taken like `markers`. + file_marks: file_marks::FileMarks, } impl Engine { @@ -166,6 +170,7 @@ impl Engine { draw_pending: false, area: Rect::default(), markers: markers::Markers::default(), + file_marks: file_marks::FileMarks::default(), }) } @@ -317,6 +322,7 @@ impl Engine { app.numbers = self.options.line_numbers; app.chrome = self.options.chrome; app.markers = std::mem::take(&mut self.markers); + app.set_file_marks(std::mem::take(&mut self.file_marks)); if self.full_sources { app.sources = Some(Vec::new()); } @@ -612,6 +618,7 @@ impl Engine { let colors = self.app.as_mut().map(|app| app.worker.close()).transpose(); self.app = None; self.markers = markers::Markers::default(); + self.file_marks = file_marks::FileMarks::default(); self.loading = false; self.error = None; self.source_failed = false; diff --git a/src/engine/file_marks.rs b/src/engine/file_marks.rs new file mode 100644 index 0000000..1f1ff39 --- /dev/null +++ b/src/engine/file_marks.rs @@ -0,0 +1,186 @@ +use std::collections::HashMap; + +use anyhow::{Result, ensure}; +use unicode_width::UnicodeWidthStr; + +use super::{Engine, InputEffect}; +use crate::tree::Mark; + +/// A host decoration for the Files sidebar row of every file whose path is `path`. +/// +/// `path` is the file's [`FileMetadata::path`](crate::storage::FileMetadata::path): its new +/// path, or its old path when the file was deleted. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FileMark<'a> { + pub path: &'a str, + /// Drawn in a column of its own at the right edge of the row. + pub badge: Option>, + /// Draws the row's name, status and counts muted. + pub dimmed: bool, +} + +/// Text of one or two terminal cells, such as `✓`, in a theme color. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Badge<'a> { + pub text: &'a str, + pub color: BadgeColor, +} + +/// The theme color of a badge, so it follows the dark and light themes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum BadgeColor { + /// The ordinary text color. + Text, + /// The muted color of line numbers and zero counts. + Muted, + Accent, + Added, + Deleted, + Modified, + Renamed, +} + +/// The host's file marks by path, with each distinct badge stored once. +#[derive(Default)] +pub(crate) struct FileMarks { + /// The host has set marks, so the sidebar keeps a badge column. + pub(crate) column: bool, + paths: HashMap, Mark>, + badges: Vec<(Box, BadgeColor)>, +} + +impl FileMarks { + /// Later marks for the same path win. + pub(crate) fn new(marks: &[FileMark<'_>]) -> Self { + let mut ids: HashMap<(&str, BadgeColor), u32> = HashMap::new(); + let mut badges = Vec::new(); + let mut paths = HashMap::with_capacity(marks.len()); + for mark in marks { + let badge = mark.badge.map(|badge| { + *ids.entry((badge.text, badge.color)).or_insert_with(|| { + badges.push((Box::from(badge.text), badge.color)); + // Every mark has at most one badge, and `validate` bounds their number. + (badges.len() - 1) as u32 + }) + }); + paths.insert( + Box::from(mark.path), + Mark { + badge, + dimmed: mark.dimmed, + }, + ); + } + Self { + column: true, + paths, + badges, + } + } + + pub(crate) fn get(&self, path: &str) -> Mark { + self.paths.get(path).copied().unwrap_or_default() + } + + pub(crate) fn badge(&self, id: u32) -> Option<(&str, BadgeColor)> { + self.badges + .get(id as usize) + .map(|(text, color)| (&**text, *color)) + } +} + +fn validate(marks: &[FileMark<'_>]) -> Result<()> { + ensure!(u32::try_from(marks.len()).is_ok(), "Too many file marks"); + for badge in marks.iter().filter_map(|mark| mark.badge) { + ensure!( + matches!(badge.text.width(), 1 | 2) && !badge.text.chars().any(char::is_control), + "Badge {:?} must be one or two terminal cells of printable text", + badge.text + ); + } + Ok(()) +} + +impl Engine { + /// Replaces every file mark. Marks for paths that are not in the review draw nothing. The + /// Files sidebar keeps a badge column from the first call until `replace()` or `close()`, + /// even when the set is empty. + pub fn set_file_marks(&mut self, marks: &[FileMark<'_>]) -> Result<()> { + ensure!(self.input.is_some(), "The review is closed"); + validate(marks)?; + let marks = FileMarks::new(marks); + match &mut self.app { + Some(app) => app.set_file_marks(marks), + None => self.file_marks = marks, + } + self.changed(InputEffect::Redraw); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn mark<'a>(path: &'a str, text: &'a str, color: BadgeColor, dimmed: bool) -> FileMark<'a> { + FileMark { + path, + badge: Some(Badge { text, color }), + dimmed, + } + } + + #[test] + fn equal_badges_share_one_entry_and_later_paths_win() { + let marks = FileMarks::new(&[ + mark("a.rs", "✓", BadgeColor::Added, true), + mark("b.rs", "✓", BadgeColor::Added, false), + mark("c.rs", "✓", BadgeColor::Accent, false), + mark("a.rs", "!", BadgeColor::Deleted, false), + FileMark { + path: "d.rs", + badge: None, + dimmed: true, + }, + ]); + assert!(marks.column); + assert_eq!(marks.badges.len(), 3); + let a = marks.get("a.rs"); + assert_eq!( + marks.badge(a.badge.unwrap()), + Some(("!", BadgeColor::Deleted)) + ); + assert!(!a.dimmed); + let b = marks.get("b.rs"); + assert_eq!( + marks.badge(b.badge.unwrap()), + Some(("✓", BadgeColor::Added)) + ); + assert_ne!(marks.get("c.rs").badge, b.badge); + assert_eq!( + marks.get("d.rs"), + Mark { + badge: None, + dimmed: true + } + ); + assert_eq!(marks.get("e.rs"), Mark::default()); + assert!(!FileMarks::default().column); + } + + #[test] + fn badges_must_be_one_or_two_printable_cells() { + for text in ["✓", "ok", "日", "👀", "A"] { + assert!( + validate(&[mark("a", text, BadgeColor::Text, false)]).is_ok(), + "{text}" + ); + } + for text in ["", "abc", "日本", "\t", "\x1b", "a\n"] { + assert!( + validate(&[mark("a", text, BadgeColor::Text, false)]).is_err(), + "{text:?}" + ); + } + } +} diff --git a/src/lib.rs b/src/lib.rs index f5dd639..da9d6eb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -49,7 +49,8 @@ //! ``` //! //! The [embedding guide](https://github.com/plannotator/diffs-rs/blob/main/docs/embedding.md) -//! covers the host loop, focus, source coordinates, chrome, markers, reading tools, and shutdown. +//! covers the host loop, focus, source coordinates, chrome, markers, file marks, reading tools, +//! and shutdown. pub mod app; mod cleanup; diff --git a/src/render/sidebar.rs b/src/render/sidebar.rs index ecea463..b9c1cc1 100644 --- a/src/render/sidebar.rs +++ b/src/render/sidebar.rs @@ -1,8 +1,11 @@ -use ratatui::buffer::Buffer; +use ratatui::{buffer::Buffer, style::Color}; use unicode_width::UnicodeWidthStr; use super::{Summary, color_summary, digits, ellipsize, fill, label, status_color}; -use crate::{app::App, tree::Kind}; +use crate::{app::App, engine::BadgeColor, theme::Colors, tree::Kind}; + +/// The cells a host badge column takes at the right of each row: a gap, then two cells. +const BADGE_COLUMN: u16 = 3; 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"; @@ -106,8 +109,11 @@ pub(super) fn draw(buf: &mut Buffer, app: &App) { (node.label.clone(), summary, colors, suffix) } }; + // With host marks, a fixed badge column sits between the summary and the divider. + let badge_column = if state.marks.column { BADGE_COLUMN } else { 0 }; + let mark = node.mark; let summary_width = summary.width().min(16) as u16; - let name_width = area.width - summary_width - 3; + let name_width = area.width - summary_width - 3 - badge_column; let depth = row.depth.saturating_mul(2); let indent = depth.min(6); let prefix = format!( @@ -131,11 +137,11 @@ pub(super) fn draw(buf: &mut Buffer, app: &App) { y, name_width, &text, - c.fg, + if mark.dimmed { c.dim } else { c.fg }, bg, focused || current, ); - let summary_x = area.right() - summary_width - 1; + let summary_x = area.right() - summary_width - 1 - badge_column; label( buf, summary_x, @@ -146,7 +152,11 @@ pub(super) fn draw(buf: &mut Buffer, app: &App) { bg, false, ); - if let Some(colors) = colors { + if let Some((text, color)) = mark.badge.and_then(|id| state.marks.badge(id)) { + let x = area.right() - BADGE_COLUMN; + label(buf, x, y, 2, text, badge_color(c, color), bg, false); + } + if let Some(colors) = colors.filter(|_| !mark.dimmed) { // A truncated summary ends in a muted ellipsis. let visible = if summary.width() > usize::from(summary_width) { summary_width.saturating_sub(1) @@ -157,3 +167,15 @@ pub(super) fn draw(buf: &mut Buffer, app: &App) { } } } + +fn badge_color(c: &Colors, color: BadgeColor) -> Color { + match color { + BadgeColor::Text => c.fg, + BadgeColor::Muted => c.dim, + BadgeColor::Accent => c.accent, + BadgeColor::Added => c.added, + BadgeColor::Deleted => c.deleted, + BadgeColor::Modified => c.modified, + BadgeColor::Renamed => c.renamed, + } +} diff --git a/src/render/tests.rs b/src/render/tests.rs index 23c30c8..cf0adf4 100644 --- a/src/render/tests.rs +++ b/src/render/tests.rs @@ -424,3 +424,160 @@ fn truncated_summaries_keep_a_muted_ellipsis() { expected.extend([c.dim, c.deleted, c.dim]); assert_eq!(colors, expected); } + +fn tick(path: &str, dimmed: bool) -> crate::engine::FileMark<'_> { + crate::engine::FileMark { + path, + badge: Some(crate::engine::Badge { + text: "✓", + color: crate::engine::BadgeColor::Added, + }), + dimmed, + } +} + +fn set_marks(app: &mut App, marks: &[crate::engine::FileMark<'_>]) { + app.set_file_marks(crate::engine::file_marks::FileMarks::new(marks)); +} + +/// The first 33 cells of the sidebar rows: the tree and its divider. +fn tree_rows(buffer: &Buffer, rows: std::ops::Range) -> Vec { + let text = super::tests::rows(buffer); + text[rows] + .iter() + .map(|row| row.chars().take(33).collect()) + .collect() +} + +#[test] +fn file_marks_take_a_fixed_badge_column_and_dim_their_rows() { + let mut app = review(KINDS, "kinds.patch"); + let plain = draw_buffer(&mut app, 160, 24, None); + let diff = app.sidebar.diff; + set_marks( + &mut app, + &[ + tick("src/added.rs", true), + tick("src/modified.rs", true), + crate::engine::FileMark { + path: "src/deleted.rs", + badge: Some(crate::engine::Badge { + text: "!!", + color: crate::engine::BadgeColor::Deleted, + }), + dimmed: false, + }, + ], + ); + let buffer = draw_buffer(&mut app, 160, 24, None); + // Every row gives the badge column the same cells, so summaries stay aligned. + assert_eq!( + tree_rows(&buffer, 2..8), + [ + " ▾ src/ 5 +3 −3 │", + " * added.rs A +2 −0 ✓ │", + " copied.rs C +0 −0 │", + " deleted.rs D +0 −2 !! │", + " modified.rs M +1 −1 ✓ │", + " renamed.rs R +0 −0 │", + ] + ); + let c = app.colors.clone(); + let tree = app.sidebar.area; + // A dimmed row mutes its name, status and counts; its badge keeps its color. + assert!( + fg(&buffer, tree, "added.rs", "added.rs") + .iter() + .all(|fg| *fg == c.dim) + ); + assert_eq!(fg(&buffer, tree, "added.rs", "A +2 −0"), [c.dim; 7]); + assert_eq!(fg(&buffer, tree, "added.rs", "✓"), [c.added]); + // An undimmed row keeps its colors. + assert!( + fg(&buffer, tree, "deleted.rs", "deleted.rs") + .iter() + .all(|fg| *fg == c.fg) + ); + assert_eq!( + fg(&buffer, tree, "deleted.rs", "D +0 −2"), + [c.deleted, c.dim, c.dim, c.dim, c.dim, c.deleted, c.deleted] + ); + assert_eq!(fg(&buffer, tree, "deleted.rs", "!!"), [c.deleted; 2]); + // The badges stay in the sidebar: the diff is drawn exactly as before. + for y in diff.top()..diff.bottom() { + for x in diff.left()..diff.right() { + assert_eq!(buffer[(x, y)], plain[(x, y)], "diff cell {x},{y}"); + } + } + + // When every file under a folder has the same badge, the folder shows it, and it is + // dimmed when they all are. That holds when the folder is collapsed. + let all = ["added", "copied", "deleted", "modified", "renamed"].map(|n| format!("src/{n}.rs")); + let marks: Vec<_> = all.iter().map(|path| tick(path, true)).collect(); + set_marks(&mut app, &marks); + let buffer = draw_buffer(&mut app, 160, 24, None); + assert_eq!( + tree_rows(&buffer, 2..4), + [ + " ▾ src/ 5 +3 −3 ✓ │", + " * added.rs A +2 −0 ✓ │", + ] + ); + assert!( + fg(&buffer, tree, "src/", "src/") + .iter() + .all(|fg| *fg == c.dim) + ); + assert_eq!(fg(&buffer, tree, "src/", "5 +3 −3"), [c.dim; 7]); + app.files_command().unwrap(); + app.sidebar.left(); + app.sidebar.left(); + let buffer = draw_buffer(&mut app, 160, 24, None); + assert_eq!( + tree_rows(&buffer, 2..4), + [ + "> ▸ src/ 5 +3 −3 ✓ │", + " │", + ] + ); + // One file without the badge, or with another badge, and the folder shows none. + set_marks(&mut app, &marks[1..]); + let buffer = draw_buffer(&mut app, 160, 24, None); + assert_eq!( + tree_rows(&buffer, 2..3), + ["> ▸ src/ 5 +3 −3 │"] + ); + + // An empty set clears the marks but keeps the column, so rows do not shift. + set_marks(&mut app, &[]); + let buffer = draw_buffer(&mut app, 160, 24, None); + assert_eq!( + tree_rows(&buffer, 2..3), + ["> ▸ src/ 5 +3 −3 │"] + ); +} + +#[test] +fn file_marks_truncate_long_names_but_never_the_badge() { + let added: String = (0..12345).map(|n| format!("+line {n}\n")).collect(); + let deep = "deeply/nested/directory/structure/a_very_long_file_name_for_the_sidebar.rs"; + let patch = format!( + "diff --git a/{deep} b/{deep}\nnew file mode 100644\n--- /dev/null\n+++ b/{deep}\n@@ -0,0 +1,12345 @@\n{added}{KINDS}" + ); + let mut app = review(&patch, "deep.patch"); + draw_buffer(&mut app, 160, 30, None); + set_marks(&mut app, &[tick(deep, false)]); + let buffer = draw_buffer(&mut app, 160, 30, None); + let rows = tree_rows(&buffer, 2..8); + assert_eq!( + rows, + [ + " ▾ deeply/ 1 +12345 −0 ✓ │", + " ▾ nested/ 1 +12345 −0 ✓ │", + " ▾ direct… 1 +12345 −0 ✓ │", + " ▾ stru… 1 +12345 −0 ✓ │", + " * …a_ver… A +12345 −0 ✓ │", + " ▾ src/ 5 +3 −3 │", + ] + ); +} diff --git a/src/tree.rs b/src/tree.rs index f3ea1c9..599a5ff 100644 --- a/src/tree.rs +++ b/src/tree.rs @@ -46,6 +46,29 @@ impl Totals { } } +/// A host mark on a file, or the part of it every file under a folder shares. +#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Mark { + /// An index into the host's distinct badges. + pub badge: Option, + pub dimmed: bool, +} + +impl Mark { + /// What this node and one more file under it have in common: the badge only when both + /// carry the same one, and dimming only when both are dimmed. + fn shared(self, other: Self) -> Self { + Self { + badge: if self.badge == other.badge { + self.badge + } else { + None + }, + dimmed: self.dimmed && other.dimmed, + } + } +} + pub(crate) enum Kind { Folder { children: BTreeMap, @@ -62,6 +85,8 @@ pub(crate) struct Node { pub label: String, pub kind: Kind, pub totals: Totals, + /// For a folder, what the marks of every file under it share. + pub mark: Mark, } impl Node { @@ -100,6 +125,7 @@ impl Default for Tree { expanded: true, }, totals: Totals::default(), + mark: Mark::default(), }], files: Vec::new(), rows: Vec::new(), @@ -130,7 +156,7 @@ impl Tree { (parent != ROOT).then_some(parent) } - pub fn append(&mut self, file: &FileIndex) -> Result<()> { + pub fn append(&mut self, file: &FileIndex, mark: Mark) -> Result<()> { ensure!( file.id == self.files.len(), "Tree file IDs must follow document order" @@ -183,6 +209,7 @@ impl Tree { parent, label: component_label(component), totals: Totals::default(), + mark: Mark::default(), kind: if is_file { Kind::File { id: FileId(file.id), @@ -206,7 +233,13 @@ impl Tree { } } loop { - self.nodes[parent.0].totals = self.nodes[parent.0].totals.add(totals)?; + let node = &mut self.nodes[parent.0]; + node.mark = if node.totals.files == 0 { + mark + } else { + node.mark.shared(mark) + }; + node.totals = node.totals.add(totals)?; if parent == ROOT { break; } @@ -216,6 +249,27 @@ impl Tree { Ok(()) } + /// Replaces every file's mark and recomputes what each folder's files share. + pub fn mark_files(&mut self, mark: impl Fn(FileId) -> Mark) { + let mut seen = vec![false; self.nodes.len()]; + for (index, &node) in self.files.iter().enumerate() { + let mark = mark(FileId(index)); + let mut id = node; + loop { + let node = &mut self.nodes[id.0]; + node.mark = if std::mem::replace(&mut seen[id.0], true) { + node.mark.shared(mark) + } else { + mark + }; + if id == ROOT { + break; + } + id = node.parent; + } + } + } + pub fn set_expanded(&mut self, id: NodeId, value: bool) { if let Kind::Folder { expanded, .. } = &mut self.nodes[id.0].kind { self.dirty |= *expanded != value; diff --git a/src/tree/tests.rs b/src/tree/tests.rs index 7420583..03f21a3 100644 --- a/src/tree/tests.rs +++ b/src/tree/tests.rs @@ -31,7 +31,7 @@ fn identity_order_totals_and_incremental_collapses_use_real_patch_metadata() { ); let mut tree = Tree::default(); for file in &files[..4] { - tree.append(file).unwrap(); + tree.append(file, Mark::default()).unwrap(); } tree.refresh(); let first = tree.file_node(FileId(1)).unwrap(); @@ -58,7 +58,7 @@ fn identity_order_totals_and_incremental_collapses_use_real_patch_metadata() { ); tree.set_expanded(lib, false); for file in &files[4..] { - tree.append(file).unwrap(); + tree.append(file, Mark::default()).unwrap(); } tree.refresh(); assert_eq!(tree.file_node(FileId(1)), Some(first)); @@ -108,7 +108,7 @@ fn raw_git_path_bytes_and_literal_escape_names_stay_distinct() { let files = parse(&input); let mut tree = Tree::default(); for file in &files { - tree.append(file).unwrap(); + tree.append(file, Mark::default()).unwrap(); } let labels: Vec<_> = (0..5) .map(|n| tree.node(tree.file_node(FileId(n)).unwrap()).label.as_str()) @@ -132,7 +132,7 @@ fn deep_paths_use_iterative_hierarchy_and_visibility() { let path = format!("{}leaf.rs", "directory/".repeat(2000)); let files = parse(&patch(&path)); let mut tree = Tree::default(); - tree.append(&files[0]).unwrap(); + tree.append(&files[0], Mark::default()).unwrap(); tree.refresh(); assert_eq!(tree.rows().len(), 2001); assert_eq!(tree.rows().last().unwrap().depth, 2000); @@ -144,3 +144,80 @@ fn deep_paths_use_iterative_hierarchy_and_visibility() { tree.refresh(); assert_eq!(tree.rows().len(), 2001); } + +#[test] +fn folders_share_a_mark_only_when_every_file_under_them_has_it() { + let files = parse( + &[ + patch("src/a.rs"), + patch("src/lib/b.rs"), + patch("src/lib/c.rs"), + patch("top.rs"), + ] + .concat(), + ); + let tick = Mark { + badge: Some(0), + dimmed: true, + }; + let other = Mark { + badge: Some(1), + dimmed: true, + }; + let mut tree = Tree::default(); + // Files arrive one by one with their marks; folders follow incrementally. + for (file, mark) in files.iter().zip([tick, tick, other, Mark::default()]) { + tree.append(file, mark).unwrap(); + } + fn mark(tree: &Tree, file: usize, up: usize) -> Mark { + let mut node = tree.file_node(FileId(file)).unwrap(); + for _ in 0..up { + node = tree.parent(node).unwrap(); + } + tree.node(node).mark + } + let (lib, src) = (mark(&tree, 1, 1), mark(&tree, 1, 2)); + // `lib` mixes two badges but every file is dimmed; `src` too. + assert_eq!( + (lib, src), + ( + Mark { + badge: None, + dimmed: true + }, + Mark { + badge: None, + dimmed: true + } + ) + ); + assert_eq!(mark(&tree, 3, 0), Mark::default()); + + // Replacing every mark recomputes the folders from scratch. + tree.mark_files(|id| if id.0 < 3 { tick } else { Mark::default() }); + assert_eq!( + (mark(&tree, 1, 1), mark(&tree, 1, 2), mark(&tree, 0, 0)), + (tick, tick, tick) + ); + assert_eq!(mark(&tree, 3, 0), Mark::default()); + tree.mark_files(|id| { + if id.0 == 2 { + Mark { + badge: Some(0), + dimmed: false, + } + } else { + tick + } + }); + let shared = Mark { + badge: Some(0), + dimmed: false, + }; + assert_eq!((mark(&tree, 1, 1), mark(&tree, 1, 2)), (shared, shared)); + tree.mark_files(|_| Mark::default()); + assert_eq!( + (mark(&tree, 1, 1), mark(&tree, 1, 2)), + (Mark::default(), Mark::default()) + ); +} diff --git a/tests/engine.rs b/tests/engine.rs index 2546bab..5e05251 100644 --- a/tests/engine.rs +++ b/tests/engine.rs @@ -9,7 +9,8 @@ use crossterm::event::{ }; use diffs_rs::{ engine::{ - Command, Engine, Input, InputEffect, Layout, Marker, Options, Side, SidebarPreference, + Badge, BadgeColor, Command, Engine, FileMark, Input, InputEffect, Layout, Marker, Options, + Side, SidebarPreference, }, reading::SourceRange, }; @@ -706,3 +707,78 @@ fn reveal_reaches_checked_context_only_once_it_is_revealed() { assert_eq!(String::from_utf8(bytes).unwrap(), expected); host.engine.close().unwrap(); } + +/// The sidebar row naming `name`, up to the divider. +fn tree_row(buffer: &Buffer, area: Rect, name: &str) -> String { + (area.y..area.bottom()) + .map(|y| line(buffer, y, area.x, area.x + 33)) + .find(|row| row.contains(name)) + .unwrap_or_else(|| panic!("missing {name:?} in {buffer:?}")) +} + +#[test] +fn file_marks_badge_and_dim_sidebar_rows_without_moving_the_diff() { + let mut host = Host::new(); + let viewed = |path| FileMark { + path, + badge: Some(Badge { + text: "✓", + color: BadgeColor::Added, + }), + dimmed: true, + }; + // Marks can be set before the first file arrives. + host.engine.set_file_marks(&[viewed("script.sh")]).unwrap(); + host.settle(); + host.engine.execute(Command::Files).unwrap(); + host.engine.execute(Command::Back).unwrap(); + let before = host.settle(); + let area = host.area; + assert_eq!( + tree_row(&before, area, "script.sh"), + " script.sh M +0 −0 ✓ │" + ); + assert_eq!( + tree_row(&before, area, "review.rs"), + " * review.rs M +3 −2 │" + ); + + // Replacing the set redraws the sidebar only; the diff keeps its layout. + host.engine + .set_file_marks(&[viewed("src/review.rs"), viewed("script.sh")]) + .unwrap(); + assert!(host.engine.needs_draw()); + let after = host.settle(); + assert_eq!( + tree_row(&after, area, "src/"), + " ▾ src/ 1 +3 −2 ✓ │" + ); + for y in area.top()..area.bottom() { + assert_eq!( + line(&after, y, area.x + 33, area.right()), + line(&before, y, area.x + 33, area.right()) + ); + } + + // An invalid badge rejects the whole set and keeps the previous one. + let wide = FileMark { + badge: Some(Badge { + text: "abc", + color: BadgeColor::Accent, + }), + ..viewed("script.sh") + }; + assert!(host.engine.set_file_marks(&[wide]).is_err()); + assert!(tree_row(&host.settle(), area, "script.sh").ends_with("✓ │")); + + // Replacement drops the marks and the badge column; close rejects new ones. + let path = host.directory.path().join("review.patch"); + host.engine.replace(Input::Patch(path)).unwrap(); + let buffer = host.settle(); + assert_eq!( + tree_row(&buffer, area, "script.sh"), + " script.sh M +0 −0 │" + ); + host.engine.close().unwrap(); + assert!(host.engine.set_file_marks(&[]).is_err()); +} diff --git a/tests/process/README.md b/tests/process/README.md index df13d11..0052665 100644 --- a/tests/process/README.md +++ b/tests/process/README.md @@ -6,7 +6,7 @@ Git generates patches from retained before/after strings with fixed diff setting ## Coverage -`engine_host_contract.rs` runs the generic embedding example in an actual PTY. Six opt-in checks cover ordered patch/file-pair/pinned-Git reviews, close/reopen, replacement during input or coloring, checked-context expansion, source coordinates across resizing, idle progress without viewer focus, missing lazy sources, FIFO cancellation and Git-child reaping. The shared harness checks terminal restoration. These checks do not qualify persistent-host memory or physical screen behavior. +`engine_host_contract.rs` runs the generic embedding example in an actual PTY. Seven opt-in checks cover ordered patch/file-pair/pinned-Git reviews, close/reopen, replacement during input or coloring, checked-context expansion, source coordinates across resizing, idle progress without viewer focus, missing lazy sources, FIFO cancellation, Git-child reaping, and file marks in the Files sidebar. The shared harness checks terminal restoration. These checks do not qualify persistent-host memory or physical screen behavior. Build and select the exact example explicitly: diff --git a/tests/process/engine_host_contract.rs b/tests/process/engine_host_contract.rs index 6b35575..e4e77fb 100644 --- a/tests/process/engine_host_contract.rs +++ b/tests/process/engine_host_contract.rs @@ -412,3 +412,89 @@ fn embedded_host_replaces_loading_files_and_reaps_the_git_child() { session.finish(b"q", 0); assert_eq!(fs::read_dir(&scratch).unwrap().count(), 0); } + +#[test] +#[ignore = "requires NATIVE_DIFF_HOST_BINARY pointing to a freshly built embedded_viewer example"] +fn embedded_host_marks_viewed_files_in_the_sidebar() { + let directory = tempfile::tempdir().unwrap(); + let patch = directory.path().join("five.patch"); + let files = [ + "docs/readme.md", + "src/a.rs", + "src/lib/b.rs", + "src/lib/c.rs", + "top.txt", + ]; + let text: String = files + .iter() + .map(|path| { + format!( + "diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -1,3 +1,4 @@\n one\n-two\n+TWO\n three\n+four\n" + ) + }) + .collect(); + fs::write(&patch, text).unwrap(); + let mut launch = command(); + launch.arg(&patch); + let mut session = Session::spawn(launch); + ready(&mut session, "src/lib/b.rs"); + // Each file: `n` reaches its header, `jj` its first line, and `v` marks it viewed. The + // first file needs no `n`. + for (index, keys) in [&b"jj"[..], b"njj", b"njj", b"njj"].into_iter().enumerate() { + session.keys(keys); + let file = format!("File: {index}"); + session.wait(|s| s.contents().contains(&file) && s.contents().contains("Old: Some(1)")); + session.keys(b"v"); + } + session.keys(b"f"); + let tree = |screen: &vt100::Screen| -> Vec { + (2..9) + .map(|row| { + (28..61) + .map(|column| screen.cell(row, column).unwrap().contents()) + .collect() + }) + .collect() + }; + session.wait(|s| tree(s)[0].contains('✓') && tree(s)[2].contains('✓')); + assert_eq!( + tree(session.parser.screen()), + [ + " ▾ docs/ 1 +2 −1 ✓ │", + " readme.md M +2 −1 ✓ │", + " ▾ src/ 3 +6 −3 ✓ │", + " ▾ lib/ 2 +4 −2 ✓ │", + " b.rs M +2 −1 ✓ │", + ">* c.rs M +2 −1 ✓ │", + " a.rs M +2 −1 ✓ │", + ] + ); + // Dimmed rows mute their names; the tick keeps its own color. + let screen = session.parser.screen(); + let (name, tick) = (screen.cell(3, 32).unwrap(), screen.cell(3, 57).unwrap()); + assert_eq!((name.contents(), tick.contents()), ("r", "✓")); + assert_ne!(name.fgcolor(), tick.fgcolor()); + session.capture("embedded-viewed-marks"); + + // Unmarking one file takes the tick off its folders; the column stays. + session.keys(b"\tv"); + session.wait(|s| !tree(s)[3].contains('✓')); + assert_eq!( + tree(session.parser.screen())[2..6], + [ + " ▾ src/ 3 +6 −3 │", + " ▾ lib/ 2 +4 −2 │", + " b.rs M +2 −1 ✓ │", + ">* c.rs M +2 −1 │", + ] + ); + // Reopening drops the marks and the column. + session.keys(b"o"); + ready(&mut session, "src/lib/b.rs"); + session.wait(|s| tree(s)[0].contains("1 +2 −1 │")); + assert_eq!( + tree(session.parser.screen())[0], + " ▾ docs/ 1 +2 −1 │" + ); + session.finish(b"q", 0); +}