diff: Add file tree pane

dfff0ae2cb31b737153292bc8a2110153de40eb1
Adds optional file-tree navigation and filtering to rustik-diff.
Alexis Sellier committed ago 1 parent df53163a
crates/diff/src/bin/rustik-diff.rs +24 -72
1 1
//! Binary entry point for the `rustik-diff` pager.
2 2
3 -
use std::env;
4 3
use std::ffi::OsString;
5 4
use std::io::{self, IsTerminal as _, Read as _, Write as _};
6 5
use std::path::Path;
7 6
use std::process::{Command, ExitCode, Output};
8 7
use std::sync::mpsc;
9 8
use std::thread;
9 +
use std::{env, str};
10 10
11 11
use rustik_diff::{
12 -
    BuiltinHighlighter, Decode, DecodeError, DiffAction, DiffDocument, DiffOptions, DiffViewer,
13 -
    ViewChange,
12 +
    BuiltinHighlighter, Decode, DecodeError, DiffDocument, DiffOptions, DiffViewer, FileTreeMode,
14 13
};
15 14
use rustik_diff::{HighlightRequest, HighlightResult};
16 15
use rustik_highlight as syntax;
17 16
use rustik_tui as tui;
18 -
use rustik_tui::{
19 -
    Color, Control, Event, Key, Label, Line, Mouse, MouseButton, Rect, Scroll, Style, Terminal,
20 -
};
17 +
use rustik_tui::{Color, Control, Event, Label, Line, Rect, Style, Terminal};
21 18
use rustik_tui_termion as tui_termion;
22 19
23 20
/// Default static render width for non-terminal output.
24 21
const STATIC_COLS: usize = 100;
25 22
/// Maximum static render rows for non-terminal output.
26 23
const STATIC_MAX_ROWS: usize = 10_000;
27 -
/// Number of body rows moved by line-scroll inputs.
28 -
const LINE_SCROLL_ROWS: isize = 3;
29 24
/// Number of rows reserved for the bottom footer when possible.
30 25
const FOOTER_ROWS: usize = 1;
31 26
/// Foreground color for dim footer text.
32 27
const FOOTER_FG: Color = Color::Fixed(240);
33 28
/// Background color for the footer row.
110 105
111 106
/// Runs the binary with forwarded Git arguments.
112 107
fn run(args: Vec<OsString>) -> Result<(), Error> {
113 108
    if io::stdin().is_terminal() {
114 109
        let cwd = env::current_dir()?;
115 -
        let output = git_diff_in(&args, &cwd)?;
110 +
        let output = git_diff(&args, &cwd)?;
116 111
        if !output.status.success() {
117 112
            io::stderr().write_all(&output.stderr)?;
118 113
            return Err(Error::Git(output.status.code().unwrap_or(1)));
119 114
        }
120 115
        return run_or_forward(&output.stdout);
125 120
    run_or_forward(&input)
126 121
}
127 122
128 123
/// Renders diff input or passes non-diff data through unchanged.
129 124
fn run_or_forward(input: &[u8]) -> Result<(), Error> {
130 -
    let text = match std::str::from_utf8(input) {
131 -
        Ok(text) => text,
132 -
        Err(_) if !contains_diff(input) => {
125 +
    let document = match DiffDocument::decode_bytes(input) {
126 +
        Ok(document) if !document.is_empty() => document,
127 +
        Ok(_) => {
133 128
            io::stdout().write_all(input)?;
134 129
            return Ok(());
135 130
        }
136 -
        Err(error) => return Err(Error::Input(error.to_string())),
131 +
        Err(error) => return Err(Error::Parse(error)),
137 132
    };
138 -
    let text = tui::ansi::strip(text);
139 -
140 -
    if !contains_diff(text.as_bytes()) {
141 -
        io::stdout().write_all(input)?;
142 -
        return Ok(());
143 -
    }
144 -
    let document = DiffDocument::decode_str(text.as_ref())?;
145 133
    let raw_theme = BUILTIN_THEME.parse::<syntax::RawTheme>()?;
146 -
    let options = DiffOptions {
134 +
    let interactive = io::stdout().is_terminal();
135 +
    let mut options = DiffOptions {
147 136
        diff_palette: (&raw_theme).into(),
148 137
        ..DiffOptions::default()
149 138
    };
150 -
151 -
    if !io::stdout().is_terminal() {
139 +
    if interactive {
140 +
        let cwd = env::current_dir()?;
141 +
        let root = cwd
142 +
            .file_name()
143 +
            .and_then(|name| name.to_str())
144 +
            .filter(|name| !name.is_empty())
145 +
            .map(str::to_owned)
146 +
            .unwrap_or_else(|| cwd.display().to_string());
147 +
148 +
        options.file_tree = FileTreeMode::Auto;
149 +
        options.file_tree_root = root;
150 +
    } else {
152 151
        let mut viewer = DiffViewer::new(document, options);
153 152
        let rows = viewer.row_count().min(STATIC_MAX_ROWS);
154 153
        let constraints = tui::Constraint::max(tui::Size::new(STATIC_COLS, rows));
155 154
156 155
        tui_termion::term::print_constrained(&mut viewer, constraints)?;
158 157
    }
159 158
    let backend = tui_termion::term::screen()?;
160 159
    let mut terminal = Terminal::new(backend)?;
161 160
    let mut registry = syntax::Registry::default();
162 161
    let theme = syntax::Theme::compile(&raw_theme);
162 +
163 163
    registry.add_theme(theme);
164 164
165 165
    for syntax in COMMON_SYNTAXES
166 166
        .iter()
167 167
        .filter(|syntax| syntax.matches_document(&document))
200 200
    while let Ok(event) = events_rx.recv() {
201 201
        match event {
202 202
            TerminalEvent::Input(event) => {
203 203
                let event = event?;
204 204
                let area = viewer_area(session.terminal.area());
205 -
                match handle_input(event, session.viewer, area) {
205 +
                match session.viewer.handle_input(event, area) {
206 206
                    Control::Quit => break,
207 207
                    Control::Redraw => session.redraw()?,
208 208
                    Control::Continue | Control::Wait => {}
209 209
                }
210 210
            }
324 324
    Line::new(Label::new("rustik-diff").fg(FOOTER_FG))
325 325
        .style(Style::default().bg(FOOTER_BG))
326 326
        .padded(cols)
327 327
}
328 328
329 -
/// Applies one input event to the viewer.
330 -
fn handle_input(event: Event<()>, viewer: &mut DiffViewer, area: Rect) -> Control {
331 -
    let action = match event {
332 -
        Event::Key(Key::Char('q')) => return Control::Quit,
333 -
        Event::Key(Key::Esc) => {
334 -
            if viewer.apply(DiffAction::CollapseFocusedFile, area) == ViewChange::Changed {
335 -
                return Control::Redraw;
336 -
            }
337 -
            return Control::Quit;
338 -
        }
339 -
        Event::Key(Key::Char('j') | Key::Down) => {
340 -
            DiffAction::Scroll(Scroll::Lines(LINE_SCROLL_ROWS))
341 -
        }
342 -
        Event::Key(Key::Char('k') | Key::Up) => {
343 -
            DiffAction::Scroll(Scroll::Lines(-LINE_SCROLL_ROWS))
344 -
        }
345 -
        Event::Key(Key::Char(' ') | Key::PageDown) => DiffAction::Scroll(Scroll::Pages(1)),
346 -
        Event::Key(Key::PageUp) => DiffAction::Scroll(Scroll::Pages(-1)),
347 -
        Event::Key(Key::Ctrl('d')) => {
348 -
            DiffAction::Scroll(Scroll::Lines((area.rows / 2).max(1) as isize))
349 -
        }
350 -
        Event::Key(Key::Ctrl('u')) => {
351 -
            DiffAction::Scroll(Scroll::Lines(-((area.rows / 2).max(1) as isize)))
352 -
        }
353 -
        Event::Key(Key::Char('g') | Key::Home) => DiffAction::Scroll(Scroll::Top),
354 -
        Event::Key(Key::Char('G') | Key::End) => DiffAction::Scroll(Scroll::Bottom),
355 -
        Event::Key(Key::Char('n')) => DiffAction::FocusNext,
356 -
        Event::Key(Key::Char('p')) => DiffAction::FocusPrevious,
357 -
        Event::Key(Key::Enter) => DiffAction::ToggleFocusedFile,
358 -
        Event::Mouse(Mouse::Press {
359 -
            button: MouseButton::WheelDown,
360 -
            ..
361 -
        }) => DiffAction::Scroll(Scroll::Lines(LINE_SCROLL_ROWS)),
362 -
        Event::Mouse(Mouse::Press {
363 -
            button: MouseButton::WheelUp,
364 -
            ..
365 -
        }) => DiffAction::Scroll(Scroll::Lines(-LINE_SCROLL_ROWS)),
366 -
        Event::Resize(_) => DiffAction::Resize,
367 -
        _ => return Control::Continue,
368 -
    };
369 -
    viewer.apply(action, area);
370 -
    Control::Redraw
371 -
}
372 -
373 -
/// Returns whether byte input contains a Git patch.
374 -
fn contains_diff(input: &[u8]) -> bool {
375 -
    input
376 -
        .windows(b"
+0 -0
+0 -0
a.rs +2 -30
1 -
+++ b/a.rs
2 -
@@ -1,20 +1,20 @@ fn main
3 -
 line 01
4 -
 line 02
5 -
 line 03
6 -
 line 04
7 -
 line 05
8 -
 line 06
9 -
 line 07
10 -
 line 08
11 -
 line 09
12 -
 line 10
13 -
 line 11
14 -
 line 12
15 -
 line 13
16 -
 line 14
17 -
 line 15
18 -
 line 16
19 -
 line 17
20 -
 line 18
21 -
 line 19
22 -
 line 20
23 -
",
24 -
        )
25 -
        .unwrap();
26 -
27 -
        DiffViewer::new(document, DiffOptions::default())
28 -
    }
29 1
30 2
    #[test]
31 -
    fn ansi_colored_git_pager_input_decodes_after_strip() {
32 -
        let input = "\
3 +
    fn ansi_colored_git_pager_input_decodes() {
4 +
        let input = b"\
33 5
\x1b[33m
a.rs\x1b[m +0 -0
crates/diff/src/decode.rs +12 -0
92 92
impl Decode for DiffDocument {
93 93
    /// Reads a full diff document from the input stream.
94 94
    fn decode(input: &mut impl BufRead) -> Result<Self, DecodeError> {
95 95
        Stream::new(input).decode_document()
96 96
    }
97 +
98 +
    /// Decodes a diff document from raw bytes.
99 +
    ///
100 +
    /// Non-UTF-8 bytes are replaced with U+FFFD and ANSI escape sequences are
101 +
    /// stripped before parsing, so output from colored Git pipes round-trips
102 +
    /// without caller-side preprocessing.
103 +
    fn decode_bytes(input: &[u8]) -> Result<Self, DecodeError> {
104 +
        let text = String::from_utf8_lossy(input);
105 +
        let stripped = rustik_tui::ansi::strip(&text);
106 +
        let mut reader = io::BufReader::new(stripped.as_bytes());
107 +
        Self::decode(&mut reader)
108 +
    }
97 109
}
98 110
99 111
/// Streaming decoder over a buffered input stream.
100 112
///
101 113
/// Stores the reader, a line counter, and per-document ID counters used while
{ +0 -0
+0 -0
=> break, +0 -0
a.rs +0 -0
new.rs +0 -0
old.rs +0 -0
to.rs +0 -0
copy2.rs +0 -0
mode.sh +0 -0
image.png +0 -0
a +0 -0
a +0 -0
a +0 -0
a.rs +0 -0
b.rs +0 -0
crates/diff/src/document.rs +16 -0
86 86
87 87
impl std::error::Error for OidError {}
88 88
89 89
impl std::ops::Deref for FileId {
90 90
    type Target = usize;
91 +
91 92
    fn deref(&self) -> &usize {
92 93
        &self.0
93 94
    }
94 95
}
95 96
96 97
impl std::ops::Deref for HunkId {
97 98
    type Target = usize;
99 +
98 100
    fn deref(&self) -> &usize {
99 101
        &self.0
100 102
    }
101 103
}
102 104
103 105
impl std::ops::Deref for RowId {
104 106
    type Target = usize;
107 +
105 108
    fn deref(&self) -> &usize {
106 109
        &self.0
107 110
    }
108 111
}
109 112
182 185
    ModeChanged,
183 186
    /// File contains binary patch data or a binary comparison marker.
184 187
    Binary,
185 188
}
186 189
190 +
impl FileKind {
191 +
    /// Returns the compact marker used by diff chrome.
192 +
    pub const fn marker(self) -> char {
193 +
        match self {
194 +
            Self::Added => '⊕',
195 +
            Self::Deleted => '⊖',
196 +
            Self::Renamed => '↦',
197 +
            Self::Copied => '⇉',
198 +
            Self::Modified | Self::ModeChanged | Self::Binary => '⊙',
199 +
        }
200 +
    }
201 +
}
202 +
187 203
/// Aggregate statistics for one [`FileDiff`].
188 204
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
189 205
pub struct FileStats {
190 206
    /// Total addition lines across all hunks in the file.
191 207
    pub additions: usize,
a.txt +0 -0
a +0 -0
crates/diff/src/highlight.rs +16 -1
135 135
        }
136 136
    }
137 137
138 138
    /// Returns the zero-based source-text line index for a source line.
139 139
    pub fn line_index(&self, source_line: u32) -> Option<usize> {
140 -
        (source_line >= self.head).then_some((source_line - self.head) as usize)
140 +
        source_line.checked_sub(self.head).map(|line| line as usize)
141 141
    }
142 142
143 143
    /// Returns one source line without its trailing line terminator.
144 144
    pub fn line(&self, source_line: u32) -> Option<&str> {
145 145
        self.line_index(source_line)
351 351
            out = out.strikethrough();
352 352
        }
353 353
        out
354 354
    }
355 355
}
356 +
357 +
#[cfg(test)]
358 +
mod tests {
359 +
    use super::*;
360 +
361 +
    #[test]
362 +
    fn source_lines_before_head_are_absent() {
363 +
        let source = HighlightSource::new("two\nthree\n", 2);
364 +
365 +
        assert_eq!(source.line_index(1), None);
366 +
        assert_eq!(source.line(1), None);
367 +
        assert_eq!(source.line_index(2), Some(0));
368 +
        assert_eq!(source.line(2), Some("two"));
369 +
    }
370 +
}
crates/diff/src/lib.rs +2 -1
26 26
pub use highlight::{
27 27
    BuiltinHighlighter, DiffSide, HighlightKey, HighlightKeyInput, HighlightRequest,
28 28
    HighlightResult, HighlightSource,
29 29
};
30 30
pub use renderer::{
31 -
    DiffAction, DiffFocus, DiffOptions, DiffPalette, DiffState, DiffViewer, ViewChange,
31 +
    DiffAction, DiffFocus, DiffOptions, DiffPalette, DiffPane, DiffState, DiffViewer,
32 +
    FileSelection, FileTreeMode, FileTreeTarget, ViewChange,
32 33
};
crates/diff/src/renderer.rs +257 -17
4 4
use std::path::PathBuf;
5 5
6 6
use rustik_highlight as syntax;
7 7
use rustik_tui as tui;
8 8
use tui::{
9 -
    Buffer, Cell, Color, Constraint, HStack, Label, Line, Placement, Rect, Scroll, ScrollView,
10 -
    ScrollbarStyle, Size, Style, Table, TableOptions, Text, VStack, View, Viewport, Widget, colors,
9 +
    Buffer, Cell, Color, Constraint, Control, Event, HStack, Key, Label, Line, Mouse, MouseButton,
10 +
    Placement, Rect, Scroll, ScrollView, ScrollbarStyle, Size, Style, Table, TableOptions, Text,
11 +
    VStack, View, Viewport, Widget, colors,
11 12
};
12 13
13 14
use crate::highlight::{HighlightKeyInput, HighlightResult};
14 15
use crate::{
15 16
    Commit, DiffDocument, DiffLine, DiffLineKind, DiffSide, FileDiff, FileId, FileKind,
16 17
    HighlightKey, HighlightRequest, HighlightSource, Hunk, HunkId, RowId,
17 18
};
18 19
20 +
mod tree;
21 +
22 +
pub use tree::{FileSelection, FileTreeMode, FileTreeTarget};
23 +
19 24
/// Minimum width before the renderer attempts table-style diff rows.
20 25
const MIN_RENDER_COLS: usize = 12;
21 26
/// Width of old and new line number cells.
22 27
const LINE_NUMBER_WIDTH: usize = 5;
23 28
/// Foreground color used by old and new line number cells.
32 37
const SCROLLBAR_THUMB_COLOR: Color = Color::Fixed(238);
33 38
/// File-card divider glyph (used between header/hunks and between hunks).
34 39
const DIVIDER: char = '─';
35 40
/// Sticky file-header divider glyph.
36 41
const STICKY_DIVIDER: char = '╴';
37 -
/// Pending file marker.
38 -
const FILE_MARKER: char = '○';
39 42
/// Rename arrow.
40 43
const RENAME_ARROW: &str = "->";
41 44
/// Missing trailing newline marker.
42 45
const NO_NEWLINE_MARKER: &str = "\\ No newline at end of file";
43 46
/// Marker cell shown between hunks in the diff marker column.
46 49
const DEFAULT_HIGHLIGHT_LOOKAHEAD: usize = 4;
47 50
/// Default syntax theme selection stored in highlight keys.
48 51
const DEFAULT_THEME: &str = "auto";
49 52
/// Number of rows in a sticky file header.
50 53
const STICKY_HEADER_ROWS: usize = 3;
54 +
/// Number of body rows moved by line-scroll inputs.
55 +
const LINE_SCROLL_ROWS: isize = 3;
51 56
52 57
/// Mutable read-only diff viewport state.
53 58
#[derive(Clone, Debug, Default, Eq, PartialEq)]
54 59
pub struct DiffState {
55 60
    /// First visible row in the rendered document.
56 61
    pub scroll: usize,
57 62
    /// Currently focused file or hunk.
58 63
    pub focus: Option<DiffFocus>,
59 64
    /// Collapsed file sections.
60 65
    pub collapsed_files: BTreeSet<FileId>,
66 +
    /// Active pane in the interactive viewer.
67 +
    pub pane: DiffPane,
68 +
    /// File selection shown in the main diff pane.
69 +
    pub file_selection: FileSelection,
61 70
}
62 71
63 72
/// Focus target inside a diff document.
64 73
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
65 74
pub enum DiffFocus {
67 76
    File(FileId),
68 77
    /// Focus a hunk header.
69 78
    Hunk(HunkId),
70 79
}
71 80
81 +
/// Active pane in the diff viewer.
82 +
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
83 +
pub enum DiffPane {
84 +
    /// The main diff pane owns input.
85 +
    #[default]
86 +
    Main,
87 +
    /// The file tree owns input.
88 +
    FileTree,
89 +
}
90 +
72 91
/// Viewer action accepted by [`DiffViewer::apply`].
73 92
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
74 93
pub enum DiffAction {
75 94
    /// Scroll the viewport.
76 95
    Scroll(Scroll),
86 105
    PreviousHunk,
87 106
    /// Toggle the focused file between collapsed and expanded states.
88 107
    ToggleFocusedFile,
89 108
    /// Collapse the focused file, or report no change if it is already collapsed.
90 109
    CollapseFocusedFile,
110 +
    /// Move focus from the main diff into the file tree.
111 +
    EnterFileTree,
112 +
    /// Move focus from the file tree back to the main diff without changing selection.
113 +
    LeaveFileTree,
114 +
    /// Move the file-tree cursor by visible file rows.
115 +
    MoveFileTree(isize),
116 +
    /// Extend the selected file range from the current anchor.
117 +
    ExtendFileTreeSelection(isize),
118 +
    /// Activate the current file-tree target.
119 +
    ActivateFileTreeTarget,
120 +
    /// Toggle the current file-tree target in the main diff pane.
121 +
    ToggleFileTreeTarget,
122 +
    /// Collapse the focused file-tree folder.
123 +
    CollapseFileTreeFolder,
124 +
    /// Expand the focused file-tree folder.
125 +
    ExpandFileTreeFolder,
91 126
}
92 127
93 128
/// Result of applying a viewer action.
94 129
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
95 130
pub enum ViewChange {
108 143
    pub syntax: Option<String>,
109 144
    /// Theme name stored in highlight requests.
110 145
    pub theme: String,
111 146
    /// Positive and negative colors used for diff chrome.
112 147
    pub diff_palette: DiffPalette,
148 +
    /// Whether the file tree may be rendered beside the diff.
149 +
    pub file_tree: FileTreeMode,
150 +
    /// Folder name shown as the file tree root.
151 +
    pub file_tree_root: String,
113 152
}
114 153
115 154
/// Positive and negative colors used for diff chrome.
116 155
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
117 156
pub struct DiffPalette {
138 177
    highlights: BTreeMap<HighlightKey, Line>,
139 178
    /// Requests already handed to a worker.
140 179
    pending_highlights: BTreeSet<HighlightKey>,
141 180
    /// Rendered commit-preamble rows for the most recent body width.
142 181
    preamble: Vec<Line>,
182 +
    /// File-tree pane state and model.
183 +
    file_tree: tree::FileTreeViewer,
143 184
}
144 185
145 186
/// One rendered row before viewport projection.
146 187
#[derive(Clone, Debug)]
147 188
struct RenderRow {
181 222
    text: String,
182 223
    /// Source path.
183 224
    path: Option<PathBuf>,
184 225
}
185 226
227 +
/// Main viewer layout for the current viewport.
228 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
229 +
struct DiffLayout {
230 +
    /// Main diff rectangle.
231 +
    diff: Rect,
232 +
    /// File tree rectangle, when the tree is visible.
233 +
    tree: Option<Rect>,
234 +
}
235 +
186 236
impl Default for DiffOptions {
187 237
    fn default() -> Self {
188 238
        Self {
189 239
            highlight_lookahead: DEFAULT_HIGHLIGHT_LOOKAHEAD,
190 240
            syntax: None,
191 241
            theme: DEFAULT_THEME.to_owned(),
192 242
            diff_palette: DiffPalette::default(),
243 +
            file_tree: FileTreeMode::default(),
244 +
            file_tree_root: ".".to_owned(),
193 245
        }
194 246
    }
195 247
}
196 248
197 249
impl Default for DiffPalette {
239 291
240 292
impl DiffViewer {
241 293
    /// Creates a viewer with plain initial rendering state.
242 294
    pub fn new(document: DiffDocument, options: DiffOptions) -> Self {
243 295
        let preamble = Self::preamble(document.commit.as_ref(), MIN_RENDER_COLS);
296 +
        let file_tree = tree::FileTreeViewer::new(&document, options.file_tree_root.clone());
297 +
        let state = DiffState::default();
244 298
245 299
        Self {
246 300
            document,
247 301
            options,
248 -
            state: DiffState::default(),
302 +
            state,
249 303
            highlights: BTreeMap::new(),
250 304
            pending_highlights: BTreeSet::new(),
251 305
            preamble,
306 +
            file_tree,
252 307
        }
253 308
    }
254 309
255 310
    /// Returns the viewed document.
256 311
    pub const fn document(&self) -> &DiffDocument {
285 340
    /// Renders the current frame into `buf`.
286 341
    pub fn render(&mut self, area: Rect, buf: &mut Buffer) {
287 342
        if area.is_empty() {
288 343
            return;
289 344
        }
345 +
        let layout = self.layout(area);
346 +
        if let Some(tree) = layout.tree {
347 +
            self.render_file_tree(tree, buf);
348 +
        }
349 +
        self.render_diff(layout.diff, buf);
350 +
    }
351 +
352 +
    /// Returns the viewport layout for `area`.
353 +
    fn layout(&self, area: Rect) -> DiffLayout {
354 +
        if self.options.file_tree != FileTreeMode::Auto
355 +
            || area.cols <= tree::MIN_VIEW_COLS
356 +
            || self.document.files.is_empty()
357 +
        {
358 +
            return DiffLayout {
359 +
                diff: area,
360 +
                tree: None,
361 +
            };
362 +
        }
363 +
364 +
        let [tree, _, diff] = tui::layout::Layout::new(tui::Direction::Horizontal)
365 +
            .child(tui::Length::Fixed(self.file_tree.cols(area.cols)))
366 +
            .child(tui::Length::Fixed(tree::GAP_COLS))
367 +
            .child(tui::Length::Fill(1))
368 +
            .areas(area);
369 +
370 +
        DiffLayout {
371 +
            diff,
372 +
            tree: Some(tree),
373 +
        }
374 +
    }
375 +
376 +
    /// Returns the file-tree target under the cursor.
377 +
    pub fn file_tree_target(&self) -> Option<FileTreeTarget> {
378 +
        self.file_tree.target()
379 +
    }
380 +
381 +
    /// Renders the file tree pane.
382 +
    fn render_file_tree(&mut self, area: Rect, buf: &mut Buffer) {
383 +
        let active = self.state.pane == DiffPane::FileTree;
384 +
        self.file_tree.render(
385 +
            &self.state.file_selection,
386 +
            self.options.diff_palette,
387 +
            active,
388 +
            area,
389 +
            buf,
390 +
        );
391 +
    }
392 +
393 +
    /// Renders the main diff pane into `buf`.
394 +
    fn render_diff(&mut self, area: Rect, buf: &mut Buffer) {
290 395
        let body_cols = ScrollView::body_cols(area);
291 396
        self.preamble = Self::preamble(self.document.commit.as_ref(), body_cols);
292 397
293 398
        let scroll = self.state.scroll;
294 399
        let content_rows = self.row_count();
308 413
    }
309 414
310 415
    /// Applies an action to the viewer state.
311 416
    pub fn apply(&mut self, action: DiffAction, area: Rect) -> ViewChange {
312 417
        let before = self.state.clone();
418 +
        let layout = self.layout(area);
419 +
        let diff = layout.diff;
313 420
314 421
        match action {
315 422
            DiffAction::Scroll(scroll) => {
316 423
                let content_rows = self.row_count();
317 424
                let mut viewport = Viewport::from_offset(self.state.scroll);
318 -
                viewport.scroll(scroll, content_rows, area.rows);
425 +
                viewport.scroll(scroll, content_rows, diff.rows);
319 426
                self.state.scroll = viewport.offset;
320 427
            }
321 428
            DiffAction::Resize => {
322 429
                let content_rows = self.row_count();
323 430
                let mut viewport = Viewport::from_offset(self.state.scroll);
324 -
                viewport.clamp(content_rows, area.rows);
431 +
                viewport.clamp(content_rows, diff.rows);
325 432
                self.state.scroll = viewport.offset;
433 +
                if layout.tree.is_none() {
434 +
                    self.state.pane = DiffPane::Main;
435 +
                }
326 436
            }
327 437
            DiffAction::FocusNext => {
328 -
                self.focus(area.rows, 1, FocusFilter::File);
438 +
                self.focus(diff.rows, 1, FocusFilter::File);
329 439
            }
330 440
            DiffAction::FocusPrevious => {
331 -
                self.focus(area.rows, -1, FocusFilter::File);
441 +
                self.focus(diff.rows, -1, FocusFilter::File);
332 442
            }
333 443
            DiffAction::NextHunk => {
334 -
                self.focus(area.rows, 1, FocusFilter::Hunk);
444 +
                self.focus(diff.rows, 1, FocusFilter::Hunk);
335 445
            }
336 446
            DiffAction::PreviousHunk => {
337 -
                self.focus(area.rows, -1, FocusFilter::Hunk);
447 +
                self.focus(diff.rows, -1, FocusFilter::Hunk);
338 448
            }
339 449
            DiffAction::ToggleFocusedFile => {
340 450
                self.toggle_focused_file();
341 451
            }
342 452
            DiffAction::CollapseFocusedFile => {
343 453
                self.collapse_focused_file();
344 454
            }
455 +
            DiffAction::EnterFileTree => {
456 +
                if layout.tree.is_some() {
457 +
                    let focused_file = self.focused_file();
458 +
                    self.state.pane = DiffPane::FileTree;
459 +
                    self.file_tree
460 +
                        .enter(&self.state.file_selection, focused_file);
461 +
                }
462 +
            }
463 +
            DiffAction::LeaveFileTree => {
464 +
                self.state.pane = DiffPane::Main;
465 +
            }
466 +
            DiffAction::MoveFileTree(delta) => {
467 +
                self.file_tree.select(delta);
468 +
            }
469 +
            DiffAction::ExtendFileTreeSelection(delta) => {
470 +
                self.state.file_selection = self.file_tree.extend_selection(delta);
471 +
            }
472 +
            DiffAction::ActivateFileTreeTarget => {
473 +
                self.file_tree.activate_target(&mut self.state);
474 +
            }
475 +
            DiffAction::ToggleFileTreeTarget => {
476 +
                self.file_tree.toggle_target(&mut self.state);
477 +
            }
478 +
            DiffAction::CollapseFileTreeFolder => {
479 +
                self.file_tree.collapse_folder();
480 +
            }
481 +
            DiffAction::ExpandFileTreeFolder => {
482 +
                self.file_tree.expand_folder();
483 +
            }
345 484
        }
346 485
347 -
        if self.state.collapsed_files != before.collapsed_files {
348 -
            self.state.scroll = View::new(self.state.scroll, self.row_count(), area.rows).offset;
486 +
        if self.state.collapsed_files != before.collapsed_files
487 +
            || self.state.file_selection != before.file_selection
488 +
        {
489 +
            self.state.scroll = View::new(self.state.scroll, self.row_count(), diff.rows).offset;
349 490
        }
350 491
        if self.state == before {
351 492
            ViewChange::Unchanged
352 493
        } else {
353 494
            ViewChange::Changed
354 495
        }
355 496
    }
356 497
498 +
    /// Applies one input event to the viewer.
499 +
    pub fn handle_input(&mut self, event: Event<()>, area: Rect) -> Control {
500 +
        let action = match event {
501 +
            Event::Key(Key::Char('q')) => return Control::Quit,
502 +
            Event::Resize(_) => DiffAction::Resize,
503 +
            Event::Mouse(Mouse::Press {
504 +
                button: MouseButton::WheelDown,
505 +
                ..
506 +
            }) => DiffAction::Scroll(Scroll::Lines(LINE_SCROLL_ROWS)),
507 +
            Event::Mouse(Mouse::Press {
508 +
                button: MouseButton::WheelUp,
509 +
                ..
510 +
            }) => DiffAction::Scroll(Scroll::Lines(-LINE_SCROLL_ROWS)),
511 +
            _ => match self.state.pane {
512 +
                DiffPane::FileTree => return self.handle_file_tree_key(event, area),
513 +
                DiffPane::Main => return self.handle_main_key(event, area),
514 +
            },
515 +
        };
516 +
        self.apply(action, area);
517 +
518 +
        Control::Redraw
519 +
    }
520 +
521 +
    /// Applies a key event while the main diff owns input.
522 +
    fn handle_main_key(&mut self, event: Event<()>, area: Rect) -> Control {
523 +
        let action = match event {
524 +
            Event::Key(Key::Char('h')) => DiffAction::EnterFileTree,
525 +
            Event::Key(Key::Esc) => {
526 +
                if self.apply(DiffAction::EnterFileTree, area) == ViewChange::Changed {
527 +
                    return Control::Redraw;
528 +
                }
529 +
                if self.apply(DiffAction::CollapseFocusedFile, area) == ViewChange::Changed {
530 +
                    return Control::Redraw;
531 +
                }
532 +
                return Control::Quit;
533 +
            }
534 +
            Event::Key(Key::Char('j') | Key::Down) => {
535 +
                DiffAction::Scroll(Scroll::Lines(LINE_SCROLL_ROWS))
536 +
            }
537 +
            Event::Key(Key::Char('k') | Key::Up) => {
538 +
                DiffAction::Scroll(Scroll::Lines(-LINE_SCROLL_ROWS))
539 +
            }
540 +
            Event::Key(Key::Char(' ') | Key::PageDown) => DiffAction::Scroll(Scroll::Pages(1)),
541 +
            Event::Key(Key::PageUp) => DiffAction::Scroll(Scroll::Pages(-1)),
542 +
            Event::Key(Key::Ctrl('d')) => {
543 +
                DiffAction::Scroll(Scroll::Lines((area.rows / 2).max(1) as isize))
544 +
            }
545 +
            Event::Key(Key::Ctrl('u')) => {
546 +
                DiffAction::Scroll(Scroll::Lines(-((area.rows / 2).max(1) as isize)))
547 +
            }
548 +
            Event::Key(Key::Char('g') | Key::Home) => DiffAction::Scroll(Scroll::Top),
549 +
            Event::Key(Key::Char('G') | Key::End) => DiffAction::Scroll(Scroll::Bottom),
550 +
            Event::Key(Key::Char('n')) => DiffAction::FocusNext,
551 +
            Event::Key(Key::Char('p')) => DiffAction::FocusPrevious,
552 +
            Event::Key(Key::Enter) => DiffAction::ToggleFocusedFile,
553 +
            _ => return Control::Continue,
554 +
        };
555 +
        self.apply(action, area);
556 +
557 +
        Control::Redraw
558 +
    }
559 +
560 +
    /// Applies a key event while the file tree owns input.
561 +
    fn handle_file_tree_key(&mut self, event: Event<()>, area: Rect) -> Control {
562 +
        let action = match event {
563 +
            Event::Key(Key::Esc | Key::Char('l')) => DiffAction::LeaveFileTree,
564 +
            Event::Key(Key::Enter) => DiffAction::ActivateFileTreeTarget,
565 +
            Event::Key(Key::Char(' ')) => DiffAction::ToggleFileTreeTarget,
566 +
            Event::Key(Key::Char('j') | Key::Down) => DiffAction::MoveFileTree(1),
567 +
            Event::Key(Key::Char('k') | Key::Up) => DiffAction::MoveFileTree(-1),
568 +
            Event::Key(Key::Right) => DiffAction::ExpandFileTreeFolder,
569 +
            Event::Key(Key::Left) => DiffAction::CollapseFileTreeFolder,
570 +
            Event::Key(Key::Char('J')) => DiffAction::ExtendFileTreeSelection(1),
571 +
            Event::Key(Key::Char('K')) => DiffAction::ExtendFileTreeSelection(-1),
572 +
            _ => return Control::Continue,
573 +
        };
574 +
        self.apply(action, area);
575 +
576 +
        Control::Redraw
577 +
    }
578 +
357 579
    /// Returns highlight requests for visible source rows plus configured lookahead.
358 580
    pub fn highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
359 -
        let take = area.rows.saturating_add(self.options.highlight_lookahead);
360 -
        let view = View::new(self.state.scroll, self.row_count(), area.rows);
581 +
        let diff = self.layout(area).diff;
582 +
        let take = diff.rows.saturating_add(self.options.highlight_lookahead);
583 +
        let view = View::new(self.state.scroll, self.row_count(), diff.rows);
361 584
        let start = view
362 585
            .offset
363 -
            .saturating_add(self.sticky_row_count(view.offset, area.rows));
586 +
            .saturating_add(self.sticky_row_count(view.offset, diff.rows));
364 587
        let mut requests = Vec::new();
365 588
        let mut sources = BTreeMap::new();
366 589
367 590
        for row in start..start.saturating_add(take) {
368 591
            let Some(meta) = self.diff_meta_at(row) else {
411 634
        self.preamble.len()
412 635
            + self
413 636
                .document
414 637
                .files
415 638
                .iter()
639 +
                .filter(|file| self.file_visible(file.id))
416 640
                .map(|file| self.file_rows(file))
417 641
                .sum::<usize>()
418 642
    }
419 643
644 +
    /// Returns whether `file` is shown in the main diff pane.
645 +
    fn file_visible(&self, file: FileId) -> bool {
646 +
        self.state.file_selection.contains(file)
647 +
    }
648 +
420 649
    /// Returns the row count for one file card.
421 650
    fn file_rows(&self, file: &FileDiff) -> usize {
422 651
        file.rendered_rows(self.state.collapsed_files.contains(&file.id))
423 652
    }
424 653
529 758
530 759
    /// Returns the file location for a global rendered row.
531 760
    fn file_row_location(&self, row: usize) -> Option<FileRowLocation<'_>> {
532 761
        let mut start = self.preamble.len();
533 762
        for file in &self.document.files {
763 +
            if !self.file_visible(file.id) {
764 +
                continue;
765 +
            }
534 766
            let end = start + self.file_rows(file);
535 767
            if (start..end).contains(&row) {
536 768
                return Some(FileRowLocation {
537 769
                    file,
538 770
                    start,
736 968
    fn focus_targets(&self, filter: FocusFilter) -> Vec<FocusTarget> {
737 969
        let mut targets = Vec::new();
738 970
        let mut row = self.preamble.len();
739 971
740 972
        for file in &self.document.files {
973 +
            if !self.file_visible(file.id) {
974 +
                continue;
975 +
            }
741 976
            let collapsed = self.state.collapsed_files.contains(&file.id);
742 977
            if filter == FocusFilter::File {
743 978
                targets.push(FocusTarget {
744 979
                    focus: DiffFocus::File(file.id),
745 980
                    row,
1104 1339
    }
1105 1340
1106 1341
    /// Returns a file header line.
1107 1342
    fn header_line(&self, cols: usize, palette: DiffPalette) -> Line {
1108 1343
        let mut left = Line::blank();
1109 -
        left.push(Label::from_char(FILE_MARKER).fg(colors::fixed::DIM));
1344 +
        left.push(Label::from_char(self.header.kind.marker()).fg(LINE_NUMBER_FG));
1110 1345
        left.push(Label::space());
1111 1346
        left = left.extend(self.path_line());
1112 1347
1113 1348
        if let Some(badge) = self.badge(palette) {
1114 1349
            left.push(Label::space());
1243 1478
}
1244 1479
1245 1480
#[cfg(test)]
1246 1481
#[allow(clippy::unwrap_used)]
1247 1482
mod tests {
1483 +
    use std::collections::BTreeSet;
1484 +
    use std::path::PathBuf;
1485 +
1248 1486
    use super::*;
1487 +
1249 1488
    use crate::Decode;
1250 1489
    use crate::DiffDocument;
1490 +
    use rustik_tui::Point;
1251 1491
1252 1492
    fn sample_viewer() -> DiffViewer {
1253 1493
        let document = DiffDocument::decode_str(
1254 1494
            "\
1255 1495
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
src/a.rs +0 -0
src/b.rs +0 -0
README.md +0 -0
crates/diff/src/renderer/tree.rs added +624 -0
1 +
//! File-tree model, rendering, and navigation for the diff viewer.
2 +
3 +
use std::collections::BTreeSet;
4 +
use std::path::PathBuf;
5 +
6 +
use rustik_tui as tui;
7 +
use tui::{
8 +
    Buffer, Color, Label, Placement, Rect, Style, Tree, TreeModel, TreeNodeKind, TreeRow,
9 +
    TreeState, TreeStyle, View,
10 +
};
11 +
12 +
use super::{DiffFocus, DiffPalette, DiffState, MIN_RENDER_COLS};
13 +
use crate::{DiffDocument, FileId, FileKind};
14 +
15 +
/// Minimum columns reserved for the file tree when it is visible.
16 +
const DEFAULT_COLS: usize = 28;
17 +
/// Blank rows above the file tree list.
18 +
const TOP_PADDING_ROWS: usize = 1;
19 +
/// Background color for the current file-tree cursor row.
20 +
const CURSOR_BG: Color = Color::Fixed(235);
21 +
/// Background color for selected file-tree rows.
22 +
const SELECTED_BG: Color = Color::Fixed(234);
23 +
/// Foreground color for selected file-tree row labels.
24 +
const SELECTED_FG: Color = Color::Fixed(252);
25 +
/// Foreground color for folder labels in the file tree.
26 +
const FOLDER_FG: Color = Color::Fixed(245);
27 +
/// Foreground color for collapsed folders containing selected files.
28 +
const SELECTED_FOLDER_FG: Color = Color::Fixed(246);
29 +
/// Selected-row styling for the file tree.
30 +
const FILE_TREE_STYLE: TreeStyle = TreeStyle::new(
31 +
    Style::new(SELECTED_FG).bg(CURSOR_BG),
32 +
    Style::new(Color::Unset),
33 +
);
34 +
/// Style for file rows selected into the main diff pane.
35 +
const SELECTED_STYLE: Style = Style::new(SELECTED_FG).bg(SELECTED_BG);
36 +
/// Style for folder rows selected into the main diff pane.
37 +
const SELECTED_FOLDER_STYLE: Style = Style::new(SELECTED_FOLDER_FG).bg(SELECTED_BG);
38 +
39 +
/// Blank columns between the file tree and the diff body.
40 +
pub(super) const GAP_COLS: usize = 1;
41 +
/// Minimum viewport width that can show the file tree beside the diff.
42 +
pub(super) const MIN_VIEW_COLS: usize = 80;
43 +
44 +
/// File selection shown in the main diff pane.
45 +
#[derive(Clone, Debug, Default, Eq, PartialEq)]
46 +
pub enum FileSelection {
47 +
    /// Every file in the diff is visible.
48 +
    #[default]
49 +
    All,
50 +
    /// Only the listed files are visible.
51 +
    Files(BTreeSet<FileId>),
52 +
}
53 +
54 +
/// Selectable target in the file tree.
55 +
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
56 +
pub enum FileTreeTarget {
57 +
    /// Root row for the current working directory.
58 +
    Root,
59 +
    /// Directory row containing changed files.
60 +
    Directory(PathBuf),
61 +
    /// File row from the diff document.
62 +
    File(FileId),
63 +
}
64 +
65 +
/// File-tree rendering policy.
66 +
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
67 +
pub enum FileTreeMode {
68 +
    /// Never render the file tree.
69 +
    #[default]
70 +
    Hidden,
71 +
    /// Render the file tree when the viewport is wide enough.
72 +
    Auto,
73 +
}
74 +
75 +
/// One node in the rendered file tree.
76 +
#[derive(Clone, Debug, Eq, PartialEq)]
77 +
struct FileTreeNode {
78 +
    /// Display name for this path segment.
79 +
    name: String,
80 +
    /// Child node ids.
81 +
    children: Vec<usize>,
82 +
    /// Diff file data when this node is a file leaf.
83 +
    file: Option<FileTreeFile>,
84 +
    /// Stable tree target represented by this node.
85 +
    target: FileTreeTarget,
86 +
}
87 +
88 +
/// Diff file metadata stored in a file-tree leaf node.
89 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
90 +
struct FileTreeFile {
91 +
    /// Stable file identifier.
92 +
    id: FileId,
93 +
    /// Kind of file-level change.
94 +
    kind: FileKind,
95 +
}
96 +
97 +
impl FileSelection {
98 +
    /// Returns whether `file` is included in this selection.
99 +
    pub fn contains(&self, file: FileId) -> bool {
100 +
        match self {
101 +
            Self::All => true,
102 +
            Self::Files(files) => files.contains(&file),
103 +
        }
104 +
    }
105 +
}
106 +
107 +
/// Stateful file-tree pane owned by the diff viewer.
108 +
#[derive(Clone, Debug, Eq, PartialEq)]
109 +
pub(super) struct FileTreeViewer {
110 +
    /// Path tree rendered in the file-tree pane.
111 +
    model: FileTreeModel,
112 +
    /// Expansion, cursor, and anchor state for the file-tree pane.
113 +
    state: TreeState<usize>,
114 +
}
115 +
116 +
impl FileTreeViewer {
117 +
    /// Creates a file-tree viewer from `document`.
118 +
    pub(super) fn new(document: &DiffDocument, root: String) -> Self {
119 +
        let model = FileTreeModel::new(document, root);
120 +
        let state = model.initial_state();
121 +
122 +
        Self { model, state }
123 +
    }
124 +
125 +
    /// Returns the file-tree target under the cursor.
126 +
    pub(super) fn target(&self) -> Option<FileTreeTarget> {
127 +
        self.state
128 +
            .selected()
129 +
            .and_then(|id| self.model.target_for(id))
130 +
    }
131 +
132 +
    /// Returns the file tree width for a viewport.
133 +
    pub(super) fn cols(&self, view_cols: usize) -> usize {
134 +
        let available = view_cols.saturating_sub(GAP_COLS + MIN_RENDER_COLS);
135 +
136 +
        Tree::new(&self.model, &self.state)
137 +
            .content_cols(DEFAULT_COLS)
138 +
            .min(available)
139 +
    }
140 +
141 +
    /// Renders the file tree pane.
142 +
    pub(super) fn render(
143 +
        &mut self,
144 +
        selection: &FileSelection,
145 +
        palette: DiffPalette,
146 +
        active: bool,
147 +
        area: Rect,
148 +
        buf: &mut Buffer,
149 +
    ) {
150 +
        if area.is_empty() {
151 +
            return;
152 +
        }
153 +
        let area = Rect::new(
154 +
            area.x,
155 +
            area.y.saturating_add(TOP_PADDING_ROWS),
156 +
            area.cols,
157 +
            area.rows.saturating_sub(TOP_PADDING_ROWS),
158 +
        );
159 +
        if area.is_empty() {
160 +
            return;
161 +
        }
162 +
        let collapsed = self
163 +
            .model
164 +
            .branch_ids()
165 +
            .filter(|id| !self.state.is_expanded(*id))
166 +
            .collect();
167 +
        let styled = StyledFileTree {
168 +
            model: &self.model,
169 +
            selection,
170 +
            collapsed,
171 +
            palette,
172 +
        };
173 +
        let tree = Tree::new(&styled, &self.state)
174 +
            .active(active)
175 +
            .style(FILE_TREE_STYLE);
176 +
        let rows = tree.visible_rows();
177 +
        let row = tree.selected_row(&rows).unwrap_or_default();
178 +
        let view = View::new(0, rows.len(), area.rows).with_row_visible(row, Placement::Minimal);
179 +
180 +
        view.render_rows(area, buf, |row, cols| tree.render_row(rows[row], cols));
181 +
    }
182 +
183 +
    /// Enters the file tree when it is visible.
184 +
    pub(super) fn enter(&mut self, selection: &FileSelection, focused_file: Option<FileId>) {
185 +
        if self.state.selected().is_none() {
186 +
            let chosen = focused_file
187 +
                .and_then(|file| self.model.id_for(&FileTreeTarget::File(file)))
188 +
                .or_else(|| self.first_selected_node(selection))
189 +
                .or_else(|| self.first_visible_node());
190 +
            if let Some(id) = chosen {
191 +
                self.state.select(id);
192 +
            }
193 +
        }
194 +
    }
195 +
196 +
    /// Moves the file-tree cursor by `delta` visible rows.
197 +
    pub(super) fn select(&mut self, delta: isize) {
198 +
        self.state.select_next(&self.model, delta);
199 +
    }
200 +
201 +
    /// Extends file selection from the current anchor by `delta` rows.
202 +
    pub(super) fn extend_selection(&mut self, delta: isize) -> FileSelection {
203 +
        let range = self.state.extend_selection(&self.model, delta);
204 +
        let mut files = BTreeSet::new();
205 +
206 +
        for id in range {
207 +
            files.extend(self.model.files_for(id));
208 +
        }
209 +
        if files.is_empty() {
210 +
            FileSelection::All
211 +
        } else {
212 +
            FileSelection::Files(files)
213 +
        }
214 +
    }
215 +
216 +
    /// Activates the current file-tree cursor.
217 +
    pub(super) fn activate_target(&mut self, state: &mut DiffState) {
218 +
        let Some(id) = self.state.selected() else {
219 +
            return;
220 +
        };
221 +
        match self.model.kind(id) {
222 +
            TreeNodeKind::Branch => {
223 +
                self.state.toggle(&self.model, id);
224 +
            }
225 +
            TreeNodeKind::Leaf => {
226 +
                if let Some(FileTreeTarget::File(file)) = self.model.target_for(id) {
227 +
                    state.file_selection = FileSelection::Files(BTreeSet::from([file]));
228 +
                    state.focus = Some(DiffFocus::File(file));
229 +
                }
230 +
            }
231 +
        }
232 +
        self.state.set_anchor(Some(id));
233 +
    }
234 +
235 +
    /// Toggles the current file-tree cursor files in the main diff pane.
236 +
    pub(super) fn toggle_target(&mut self, state: &mut DiffState) {
237 +
        let Some(id) = self.state.selected() else {
238 +
            return;
239 +
        };
240 +
        let target_files = self.model.files_for(id);
241 +
242 +
        if target_files.is_empty() {
243 +
            return;
244 +
        }
245 +
        let all_files = self.model.all_files();
246 +
        let target_selected = target_files
247 +
            .iter()
248 +
            .all(|file| state.file_selection.contains(*file));
249 +
        let mut files = match &state.file_selection {
250 +
            FileSelection::All => all_files.clone(),
251 +
            FileSelection::Files(files) => files.clone(),
252 +
        };
253 +
254 +
        if target_selected {
255 +
            for file in target_files {
256 +
                files.remove(&file);
257 +
            }
258 +
        } else {
259 +
            files.extend(target_files);
260 +
        }
261 +
        state.file_selection = if files.len() == all_files.len() {
262 +
            FileSelection::All
263 +
        } else {
264 +
            FileSelection::Files(files)
265 +
        };
266 +
        self.state.set_anchor(Some(id));
267 +
268 +
        state.focus = all_files
269 +
            .into_iter()
270 +
            .find(|file| state.file_selection.contains(*file))
271 +
            .map(DiffFocus::File);
272 +
    }
273 +
274 +
    /// Collapses the focused file-tree folder.
275 +
    pub(super) fn collapse_folder(&mut self) {
276 +
        let Some(id) = self.state.selected() else {
277 +
            return;
278 +
        };
279 +
        if self.model.kind(id) == TreeNodeKind::Branch {
280 +
            self.state.collapse(id);
281 +
        }
282 +
    }
283 +
284 +
    /// Expands the focused file-tree folder.
285 +
    pub(super) fn expand_folder(&mut self) {
286 +
        let Some(id) = self.state.selected() else {
287 +
            return;
288 +
        };
289 +
        if self.model.kind(id) == TreeNodeKind::Branch {
290 +
            self.state.expand(id);
291 +
        }
292 +
    }
293 +
294 +
    /// Returns the first visible tree row that contains a currently selected file.
295 +
    fn first_selected_node(&self, selection: &FileSelection) -> Option<usize> {
296 +
        Tree::new(&self.model, &self.state)
297 +
            .visible_rows()
298 +
            .into_iter()
299 +
            .find(|row| match selection {
300 +
                FileSelection::All => true,
301 +
                FileSelection::Files(files) => self
302 +
                    .model
303 +
                    .files_for(row.id)
304 +
                    .iter()
305 +
                    .any(|file| files.contains(file)),
306 +
            })
307 +
            .map(|row| row.id)
308 +
    }
309 +
310 +
    /// Returns the first visible tree row.
311 +
    fn first_visible_node(&self) -> Option<usize> {
312 +
        Tree::new(&self.model, &self.state)
313 +
            .visible_rows()
314 +
            .into_iter()
315 +
            .next()
316 +
            .map(|row| row.id)
317 +
    }
318 +
}
319 +
320 +
/// Path tree built once from a diff document. Immutable after construction.
321 +
#[derive(Clone, Debug, Eq, PartialEq)]
322 +
pub(super) struct FileTreeModel {
323 +
    /// Root node ids.
324 +
    roots: Vec<usize>,
325 +
    /// Tree nodes indexed by id.
326 +
    nodes: Vec<FileTreeNode>,
327 +
}
328 +
329 +
impl FileTreeModel {
330 +
    /// Creates a path tree from the files in `document`.
331 +
    pub(super) fn new(document: &DiffDocument, root: String) -> Self {
332 +
        let mut model = Self {
333 +
            roots: Vec::new(),
334 +
            nodes: Vec::new(),
335 +
        };
336 +
        let root = model.push_node(None, root, None, FileTreeTarget::Root);
337 +
338 +
        for file in &document.files {
339 +
            model.insert_file(
340 +
                root,
341 +
                Self::path_parts(file.header.display_path()),
342 +
                file.id,
343 +
                file.header.kind,
344 +
            );
345 +
        }
346 +
        model
347 +
    }
348 +
349 +
    /// Returns every file id known to this tree, in document order.
350 +
    fn all_files(&self) -> BTreeSet<FileId> {
351 +
        self.nodes
352 +
            .iter()
353 +
            .filter_map(|node| node.file.map(|file| file.id))
354 +
            .collect()
355 +
    }
356 +
357 +
    /// Returns a tree state with every branch expanded.
358 +
    pub(super) fn initial_state(&self) -> TreeState<usize> {
359 +
        let mut state = TreeState::new();
360 +
361 +
        for id in self.branch_ids() {
362 +
            state.expand(id);
363 +
        }
364 +
        state
365 +
    }
366 +
367 +
    /// Returns the tree target represented by `id`.
368 +
    fn target_for(&self, id: usize) -> Option<FileTreeTarget> {
369 +
        self.nodes.get(id).map(|node| node.target.clone())
370 +
    }
371 +
372 +
    /// Returns the node id for `target`.
373 +
    fn id_for(&self, target: &FileTreeTarget) -> Option<usize> {
374 +
        self.nodes.iter().position(|node| node.target == *target)
375 +
    }
376 +
377 +
    /// Returns the ids of every branch (non-leaf) node.
378 +
    fn branch_ids(&self) -> impl Iterator<Item = usize> + '_ {
379 +
        self.nodes
380 +
            .iter()
381 +
            .enumerate()
382 +
            .filter_map(|(id, node)| (!node.children.is_empty()).then_some(id))
383 +
    }
384 +
385 +
    /// Returns the files included below `id`.
386 +
    fn files_for(&self, id: usize) -> BTreeSet<FileId> {
387 +
        let mut files = BTreeSet::new();
388 +
389 +
        if let Some(file) = self.nodes[id].file {
390 +
            files.insert(file.id);
391 +
        }
392 +
        for child in &self.nodes[id].children {
393 +
            files.extend(self.files_for(*child));
394 +
        }
395 +
        files
396 +
    }
397 +
398 +
    /// Returns display path components for a file header path.
399 +
    fn path_parts(path: Option<&PathBuf>) -> Vec<String> {
400 +
        let Some(path) = path else {
401 +
            return vec!["<unknown>".to_owned()];
402 +
        };
403 +
        let parts: Vec<String> = path
404 +
            .iter()
405 +
            .map(|part| part.to_string_lossy().into_owned())
406 +
            .filter(|part| !part.is_empty())
407 +
            .collect();
408 +
409 +
        if parts.is_empty() {
410 +
            vec!["<unknown>".to_owned()]
411 +
        } else {
412 +
            parts
413 +
        }
414 +
    }
415 +
416 +
    /// Inserts one file path into the model.
417 +
    fn insert_file(&mut self, root: usize, parts: Vec<String>, file: FileId, kind: FileKind) {
418 +
        let mut parent = Some(root);
419 +
        let mut path = PathBuf::new();
420 +
        let end = parts.len().saturating_sub(1);
421 +
422 +
        for (index, name) in parts.into_iter().enumerate() {
423 +
            path.push(&name);
424 +
            let is_file = index == end;
425 +
            let target = if is_file {
426 +
                FileTreeTarget::File(file)
427 +
            } else {
428 +
                FileTreeTarget::Directory(path.clone())
429 +
            };
430 +
            let existing = self.child(parent, &target);
431 +
            let node = existing.unwrap_or_else(|| {
432 +
                let file = is_file.then_some(FileTreeFile { id: file, kind });
433 +
                self.push_node(parent, name, file, target)
434 +
            });
435 +
            parent = Some(node);
436 +
        }
437 +
    }
438 +
439 +
    /// Returns a matching child node below `parent`.
440 +
    fn child(&self, parent: Option<usize>, target: &FileTreeTarget) -> Option<usize> {
441 +
        let children = parent.map_or(self.roots.as_slice(), |id| {
442 +
            self.nodes[id].children.as_slice()
443 +
        });
444 +
445 +
        children
446 +
            .iter()
447 +
            .copied()
448 +
            .find(|&child| self.nodes[child].target == *target)
449 +
    }
450 +
451 +
    /// Appends a node below `parent`.
452 +
    fn push_node(
453 +
        &mut self,
454 +
        parent: Option<usize>,
455 +
        name: String,
456 +
        file: Option<FileTreeFile>,
457 +
        target: FileTreeTarget,
458 +
    ) -> usize {
459 +
        let id = self.nodes.len();
460 +
461 +
        self.nodes.push(FileTreeNode {
462 +
            name,
463 +
            children: Vec::new(),
464 +
            file,
465 +
            target,
466 +
        });
467 +
        if let Some(parent) = parent {
468 +
            self.nodes[parent].children.push(id);
469 +
        } else {
470 +
            self.roots.push(id);
471 +
        }
472 +
        id
473 +
    }
474 +
475 +
    /// Returns a folder row (used by both structural and styled tree views).
476 +
    fn folder_row(&self, id: usize, fg: Color, style: Style) -> TreeRow {
477 +
        let node = &self.nodes[id];
478 +
        let label = if node.name == "/" {
479 +
            node.name.to_owned()
480 +
        } else {
481 +
            format!("{}/", node.name)
482 +
        };
483 +
        TreeRow::new(Label::from(label).fg(fg))
484 +
            .marker_style(Style::new(fg))
485 +
            .style(style)
486 +
    }
487 +
}
488 +
489 +
impl TreeModel for FileTreeModel {
490 +
    type Id = usize;
491 +
492 +
    fn roots(&self) -> &[Self::Id] {
493 +
        &self.roots
494 +
    }
495 +
496 +
    fn children(&self, id: Self::Id) -> &[Self::Id] {
497 +
        &self.nodes[id].children
498 +
    }
499 +
500 +
    fn kind(&self, id: Self::Id) -> TreeNodeKind {
501 +
        if self.nodes[id].file.is_some() {
502 +
            TreeNodeKind::Leaf
503 +
        } else {
504 +
            TreeNodeKind::Branch
505 +
        }
506 +
    }
507 +
508 +
    fn row(&self, id: Self::Id) -> TreeRow {
509 +
        let node = &self.nodes[id];
510 +
        let Some(file) = node.file else {
511 +
            return self.folder_row(id, FOLDER_FG, Style::default());
512 +
        };
513 +
        TreeRow::new(Label::new(&node.name).fg(Color::White))
514 +
            .marker(file.kind.marker())
515 +
            .marker_style(Style::new(Color::Unset))
516 +
    }
517 +
}
518 +
519 +
/// Render-time view over a [`FileTreeModel`] that applies selection-aware styling.
520 +
///
521 +
/// Built each frame; implements [`TreeModel`] so the tree widget renders styled rows
522 +
/// without forcing render-time state into the structural model.
523 +
struct StyledFileTree<'a> {
524 +
    /// Underlying structural tree.
525 +
    model: &'a FileTreeModel,
526 +
    /// File selection used to mark included rows.
527 +
    selection: &'a FileSelection,
528 +
    /// Branch ids that are currently collapsed.
529 +
    collapsed: BTreeSet<usize>,
530 +
    /// Positive and negative colors used for file details.
531 +
    palette: DiffPalette,
532 +
}
533 +
534 +
impl StyledFileTree<'_> {
535 +
    /// Returns whether `id` should render as included in the diff pane.
536 +
    fn highlighted(&self, id: usize) -> bool {
537 +
        let Some(node) = self.model.nodes.get(id) else {
538 +
            return false;
539 +
        };
540 +
        match &node.target {
541 +
            FileTreeTarget::File(file) => self.selection.contains(*file),
542 +
            FileTreeTarget::Root | FileTreeTarget::Directory(_) => {
543 +
                self.collapsed.contains(&id)
544 +
                    && self
545 +
                        .model
546 +
                        .files_for(id)
547 +
                        .iter()
548 +
                        .any(|file| self.selection.contains(*file))
549 +
            }
550 +
        }
551 +
    }
552 +
553 +
    /// Returns the full-row style for a highlighted tree target.
554 +
    fn row_style(&self, id: usize) -> Style {
555 +
        if !self.highlighted(id) {
556 +
            return Style::default();
557 +
        }
558 +
        match self.model.nodes[id].target {
559 +
            FileTreeTarget::Root | FileTreeTarget::Directory(_) => SELECTED_FOLDER_STYLE,
560 +
            FileTreeTarget::File(_) => SELECTED_STYLE,
561 +
        }
562 +
    }
563 +
}
564 +
565 +
impl TreeModel for StyledFileTree<'_> {
566 +
    type Id = usize;
567 +
568 +
    fn roots(&self) -> &[Self::Id] {
569 +
        self.model.roots()
570 +
    }
571 +
572 +
    fn children(&self, id: Self::Id) -> &[Self::Id] {
573 +
        self.model.children(id)
574 +
    }
575 +
576 +
    fn kind(&self, id: Self::Id) -> TreeNodeKind {
577 +
        self.model.kind(id)
578 +
    }
579 +
580 +
    fn row(&self, id: Self::Id) -> TreeRow {
581 +
        let node = &self.model.nodes[id];
582 +
        let Some(file) = node.file else {
583 +
            let fg = if self.highlighted(id) {
584 +
                SELECTED_FOLDER_FG
585 +
            } else {
586 +
                FOLDER_FG
587 +
            };
588 +
            return self.model.folder_row(id, fg, self.row_style(id));
589 +
        };
590 +
        let fg = if self.selection.contains(file.id) {
591 +
            SELECTED_FG
592 +
        } else {
593 +
            Color::White
594 +
        };
595 +
        let kind_fg = match file.kind {
596 +
            FileKind::Added => self.palette.positive_fg,
597 +
            FileKind::Deleted => self.palette.negative_fg,
598 +
            FileKind::Modified
599 +
            | FileKind::Renamed
600 +
            | FileKind::Copied
601 +
            | FileKind::ModeChanged
602 +
            | FileKind::Binary => Color::Yellow,
603 +
        };
604 +
605 +
        TreeRow::new(Label::new(&node.name).fg(fg))
606 +
            .marker(file.kind.marker())
607 +
            .marker_style(Style::new(kind_fg))
608 +
            .style(self.row_style(id))
609 +
    }
610 +
}
611 +
612 +
#[cfg(test)]
613 +
#[allow(clippy::unwrap_used)]
614 +
mod tests {
615 +
    use std::collections::BTreeSet;
616 +
617 +
    use crate::{Decode, DiffDocument, DiffOptions, DiffViewer};
618 +
619 +
    use super::*;
620 +
621 +
    fn two_file_viewer() -> DiffViewer {
622 +
        let document = DiffDocument::decode_str(
623 +
            "\
624 +
a.rs +0 -0
b.rs +0 -0
crates/diff/tests/golden.rs +36 -2
1 1
#![allow(clippy::unwrap_used)]
2 2
3 3
use std::collections::BTreeSet;
4 4
5 5
use rustik_diff::{
6 -
    Decode, DiffAction, DiffDocument, DiffOptions, DiffViewer, FileId, HighlightResult,
6 +
    Decode, DiffAction, DiffDocument, DiffOptions, DiffViewer, FileId, FileTreeMode,
7 +
    HighlightResult,
7 8
};
8 9
use rustik_tui::{Buffer, Color, Label, Line, Rect, Scroll};
9 10
10 11
#[test]
11 12
fn expanded_file_card_matches_golden_frame() {
159 160
        80,
160 161
        24,
161 162
    );
162 163
}
163 164
165 +
#[test]
166 +
fn wide_file_tree_matches_golden_frame() {
167 +
    assert_golden(
168 +
        "wide_file_tree_100x8.txt",
169 +
        include_str!("golden/wide_file_tree_100x8.txt"),
170 +
        two_file_tree_viewer(),
171 +
        100,
172 +
        8,
173 +
    );
174 +
}
175 +
176 +
#[test]
177 +
fn file_tree_is_hidden_at_eighty_columns() {
178 +
    let actual = render_frame(two_file_tree_viewer(), 80, 4);
179 +
180 +
    assert!(actual.starts_with('╭'));
181 +
}
182 +
164 183
#[test]
165 184
fn highlighted_source_matches_golden_frame() {
166 185
    let mut viewer = sample_viewer();
167 186
    let request = viewer
168 187
        .highlight_requests(Rect::new(0, 0, 64, 5))
206 225
207 226
fn two_file_viewer() -> DiffViewer {
208 227
    viewer_from_str(include_str!("golden/two_files.diff"))
209 228
}
210 229
230 +
fn two_file_tree_viewer() -> DiffViewer {
231 +
    viewer_from_str_with_options(
232 +
        include_str!("golden/two_files.diff"),
233 +
        DiffOptions {
234 +
            file_tree: FileTreeMode::Auto,
235 +
            file_tree_root: "rustik".to_owned(),
236 +
            ..DiffOptions::default()
237 +
        },
238 +
    )
239 +
}
240 +
211 241
fn two_hunk_viewer() -> DiffViewer {
212 242
    viewer_from_str(include_str!("golden/two_hunks.diff"))
213 243
}
214 244
215 245
fn preamble_no_newline_viewer() -> DiffViewer {
219 249
fn file_kinds_viewer() -> DiffViewer {
220 250
    viewer_from_str(include_str!("golden/file_kinds.diff"))
221 251
}
222 252
223 253
fn viewer_from_str(input: &str) -> DiffViewer {
254 +
    viewer_from_str_with_options(input, DiffOptions::default())
255 +
}
256 +
257 +
fn viewer_from_str_with_options(input: &str, options: DiffOptions) -> DiffViewer {
224 258
    let document = DiffDocument::decode_str(input).unwrap();
225 259
226 -
    DiffViewer::new(document, DiffOptions::default())
260 +
    DiffViewer::new(document, options)
227 261
}
crates/diff/tests/golden/bottom_of_file_64x5.txt +1 -1
1 1
╭─────────────────────────────────────────────────────────────╮🮘
2 -
│ ○ a.rs                                                +2 -1 │🮘
2 +
│ ⊙ a.rs                                                +2 -1 │🮘
3 3
├╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴┤🮘
4 4
│ 3    4       tail                                           │▓
5 5
╰─────────────────────────────────────────────────────────────╯▓
crates/diff/tests/golden/collapsed_file_64x6.txt +1 -1
1 1
╭─────────────────────────────────────────────────────────────╮🮘
2 -
│ ○ a.rs                                                +2 -1 │🮘
2 +
│ ⊙ a.rs                                                +2 -1 │🮘
3 3
╰─────────────────────────────────────────────────────────────╯🮘
4 4
                                                               🮘
5 5
                                                               🮘
6 6
                                                               🮘
crates/diff/tests/golden/expanded_file_card_64x9.txt +1 -1
1 1
╭─────────────────────────────────────────────────────────────╮🮘
2 -
│ ○ a.rs                                                +2 -1 │🮘
2 +
│ ⊙ a.rs                                                +2 -1 │🮘
3 3
├─────────────────────────────────────────────────────────────┤🮘
4 4
│ 1    1       context                                        │🮘
5 5
│ 2          - old                                            │🮘
6 6
│      2     + new                                            │🮘
7 7
│      3     + extra                                          │🮘
crates/diff/tests/golden/file_kinds_80x24.txt +6 -6
1 1
╭─────────────────────────────────────────────────────────────────────────────╮🮘
2 -
│ ○ new.rs  created                                                        +1 │🮘
2 +
│ ⊕ new.rs  created                                                        +1 │🮘
3 3
├─────────────────────────────────────────────────────────────────────────────┤🮘
4 4
│      1     + new                                                            │🮘
5 5
╰─────────────────────────────────────────────────────────────────────────────╯🮘
6 6
╭─────────────────────────────────────────────────────────────────────────────╮🮘
7 -
│ ○ old.rs  deleted                                                        -1 │🮘
7 +
│ ⊖ old.rs  deleted                                                        -1 │🮘
8 8
├─────────────────────────────────────────────────────────────────────────────┤🮘
9 9
│ 1          - old                                                            │🮘
10 10
╰─────────────────────────────────────────────────────────────────────────────╯🮘
11 11
╭─────────────────────────────────────────────────────────────────────────────╮🮘
12 -
│ ○ from.rs -> to.rs  moved                                                   │🮘
12 +
│ ↦ from.rs -> to.rs  moved                                                   │🮘
13 13
╰─────────────────────────────────────────────────────────────────────────────╯🮘
14 14
╭─────────────────────────────────────────────────────────────────────────────╮🮘
15 -
│ ○ copy.rs -> copy2.rs  copied                                               │🮘
15 +
│ ⇉ copy.rs -> copy2.rs  copied                                               │🮘
16 16
╰─────────────────────────────────────────────────────────────────────────────╯🮘
17 17
╭─────────────────────────────────────────────────────────────────────────────╮🮘
18 -
│ ○ mode.sh  mode changed                                                     │🮘
18 +
│ ⊙ mode.sh  mode changed                                                     │🮘
19 19
╰─────────────────────────────────────────────────────────────────────────────╯🮘
20 20
╭─────────────────────────────────────────────────────────────────────────────╮🮘
21 -
│ ○ image.png  binary                                                         │🮘
21 +
│ ⊙ image.png  binary                                                         │🮘
22 22
╰─────────────────────────────────────────────────────────────────────────────╯🮘
23 23
                                                                               🮘
24 24
                                                                               🮘
crates/diff/tests/golden/focused_second_file_64x6.txt +1 -1
1 1
╭─────────────────────────────────────────────────────────────╮🮘
2 -
│ ○ b.rs                                                +1 -1 │🮘
2 +
│ ⊙ b.rs                                                +1 -1 │🮘
3 3
├─────────────────────────────────────────────────────────────┤🮘
4 4
│ 1    1       keep                                           │▓
5 5
│ 2          - before                                         │▓
6 6
│      2     + after                                          │🮘
crates/diff/tests/golden/highlighted_source_64x5.txt +1 -1
1 1
╭─────────────────────────────────────────────────────────────╮▓
2 -
│ ○ a.rs                                                +2 -1 │▓
2 +
│ ⊙ a.rs                                                +2 -1 │▓
3 3
├─────────────────────────────────────────────────────────────┤🮘
4 4
│ 1    1       highlighted context                            │🮘
5 5
│ 2          - old                                            │🮘
crates/diff/tests/golden/multi_hunk_gap_64x12.txt +1 -1
1 1
╭─────────────────────────────────────────────────────────────╮🮘
2 -
│ ○ a.rs                                                +2 -2 │🮘
2 +
│ ⊙ a.rs                                                +2 -2 │🮘
3 3
├─────────────────────────────────────────────────────────────┤🮘
4 4
│ 1    1       keep                                           │🮘
5 5
│ 2          - old                                            │🮘
6 6
│      2     + new                                            │🮘
7 7
│            ⋮                                                │🮘
crates/diff/tests/golden/narrow_view_14x8.txt +1 -1
1 1
╭───────────╮▓
2 -
│ ○ a.rs +2 │▓
2 +
│ ⊙ a.rs +2 │▓
3 3
├───────────┤▓
4 4
│ 1    1    │▓
5 5
│ 2         │▓
6 6
│      2    │▓
7 7
│      3    │▓
crates/diff/tests/golden/preamble_and_no_newline_64x17.txt +1 -1
7 7
│                                                  │           🮘
8 8
│ Message body text 1.                             │           🮘
9 9
│ Message body text 2.                             │           🮘
10 10
╰──────────────────────────────────────────────────╯           🮘
11 11
╭─────────────────────────────────────────────────────────────╮🮘
12 -
│ ○ a.rs                                                +1 -1 │🮘
12 +
│ ⊙ a.rs                                                +1 -1 │🮘
13 13
├─────────────────────────────────────────────────────────────┤🮘
14 14
│ 1          - old                                            │🮘
15 15
│      1     + new                                            │🮘
16 16
│              \ No newline at end of file                    │🮘
17 17
╰─────────────────────────────────────────────────────────────╯🮘
crates/diff/tests/golden/sticky_header_before_next_file_64x5.txt +1 -1
1 1
╰─────────────────────────────────────────────────────────────╯🮘
2 2
╭─────────────────────────────────────────────────────────────╮🮘
3 -
│ ○ b.rs                                                +1 -1 │▓
3 +
│ ⊙ b.rs                                                +1 -1 │▓
4 4
├─────────────────────────────────────────────────────────────┤🮘
5 5
│ 1    1       keep                                           │🮘
crates/diff/tests/golden/sticky_header_inside_file_64x5.txt +1 -1
1 1
╭─────────────────────────────────────────────────────────────╮🮘
2 -
│ ○ a.rs                                                +2 -1 │🮘
2 +
│ ⊙ a.rs                                                +2 -1 │🮘
3 3
├╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴┤🮘
4 4
│ 3    4       tail                                           │▓
5 5
╰─────────────────────────────────────────────────────────────╯▓
crates/diff/tests/golden/sticky_header_replaces_chrome_64x5.txt +1 -1
1 1
╭─────────────────────────────────────────────────────────────╮🮘
2 -
│ ○ a.rs                                                +2 -1 │🮘
2 +
│ ⊙ a.rs                                                +2 -1 │🮘
3 3
├╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴┤▓
4 4
│      3     + extra                                          │▓
5 5
│ 3    4       tail                                           │🮘
crates/diff/tests/golden/sticky_header_starting_64x5.txt +1 -1
1 1
╭─────────────────────────────────────────────────────────────╮▓
2 -
│ ○ a.rs                                                +2 -1 │▓
2 +
│ ⊙ a.rs                                                +2 -1 │▓
3 3
├╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴┤🮘
4 4
│ 2          - old                                            │🮘
5 5
│      2     + new                                            │🮘
crates/diff/tests/golden/wide_file_tree_100x8.txt added +8 -0
1 +
                             ╭────────────────────────────────────────────────────────────────────╮▓
2 +
▿ rustik/                    │ ⊙ a.rs                                                       +2 -1 │▓
3 +
  ⊙ a.rs                     ├────────────────────────────────────────────────────────────────────┤▓
4 +
  ⊙ b.rs                     │ 1    1       context                                               │▓
5 +
                             │ 2          - old                                                   │🮘
6 +
                             │      2     + new                                                   │🮘
7 +
                             │      3     + extra                                                 │🮘
8 +
                             │ 3    4       tail                                                  │🮘