diff: Update viewer and pager

8274aafc2664797e09cd9fd1a5be263e1e3a3aa5
Adds file navigation, sticky headers, footer chrome, and interactive pager
controls for rustik-diff.
Alexis Sellier committed ago 1 parent c1c9a66a
crates/diff/src/bin/rustik-diff.rs +126 -24
1 1
//! Binary entry point for the `rustik-diff` pager.
2 2
3 3
use std::env;
4 4
use std::ffi::OsString;
5 5
use std::io::{self, IsTerminal as _, Read as _, Write as _};
6 -
use std::path::Path;
6 +
use std::path::{Path, PathBuf};
7 7
use std::process::{Command, ExitCode, Output};
8 8
use std::sync::mpsc;
9 9
use std::thread;
10 10
11 11
use rustik_diff::{
21 21
22 22
/// Default static render width for non-terminal output.
23 23
const STATIC_COLS: usize = 100;
24 24
/// Maximum static render rows for non-terminal output.
25 25
const STATIC_MAX_ROWS: usize = 10_000;
26 +
/// Number of body rows moved by line-scroll inputs.
27 +
const LINE_SCROLL_ROWS: isize = 3;
28 +
/// Number of rows reserved for the top header when possible.
29 +
const HEADER_ROWS: usize = 1;
30 +
/// Number of rows reserved for the bottom footer when possible.
31 +
const FOOTER_ROWS: usize = 1;
32 +
/// Foreground color for dim footer text.
33 +
const FOOTER_FG: Color = Color::Fixed(240);
34 +
/// Background color for the footer row.
35 +
const FOOTER_BG: Color = Color::Fixed(233);
26 36
27 37
/// Terminal backend used by the interactive viewer.
28 38
type DiffTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::StdoutScreen>>;
29 39
30 40
/// Program entry point.
38 48
    }
39 49
}
40 50
41 51
/// Runs the binary with forwarded Git arguments.
42 52
fn run(args: Vec<OsString>) -> Result<(), Error> {
53 +
    let cwd = env::current_dir()?;
43 54
    if io::stdin().is_terminal() {
44 -
        let output = git_diff_in(&args, Path::new("."))?;
55 +
        let output = git_diff_in(&args, &cwd)?;
45 56
        if !output.status.success() {
46 57
            io::stderr().write_all(&output.stderr)?;
47 58
            return Err(Error::Git(output.status.code().unwrap_or(1)));
48 59
        }
49 -
        return run_or_forward(&output.stdout);
60 +
        return run_or_forward(&output.stdout, Header::git_diff(cwd, &args));
50 61
    }
51 62
    let mut input = Vec::new();
52 63
    io::stdin().read_to_end(&mut input)?;
53 64
54 -
    run_or_forward(&input)
65 +
    run_or_forward(&input, Header::stdin(cwd))
55 66
}
56 67
57 68
/// Renders diff input or passes non-diff data through unchanged.
58 -
fn run_or_forward(input: &[u8]) -> Result<(), Error> {
69 +
fn run_or_forward(input: &[u8], header: Header) -> Result<(), Error> {
59 70
    if !contains_diff(input) {
60 71
        io::stdout().write_all(input)?;
61 72
        return Ok(());
62 73
    }
63 74
    let text = std::str::from_utf8(input).map_err(|error| Error::Input(error.to_string()))?;
64 75
    let document = DiffDocument::decode_str(text)?;
65 76
66 77
    if !io::stdout().is_terminal() {
67 -
        let viewer = DiffViewer::new(document, DiffOptions::default());
78 +
        let mut viewer = DiffViewer::new(document, DiffOptions::default());
68 79
        let rows = viewer.content_rows(STATIC_COLS).min(STATIC_MAX_ROWS);
69 80
        let constraints = tui::Constraint::max(tui::Size::new(STATIC_COLS, rows));
70 81
71 -
        tui_termion::term::write_to_stdout(&viewer, constraints)?;
82 +
        tui_termion::term::write_to_stdout(&mut viewer, constraints)?;
72 83
        return Ok(());
73 84
    }
74 85
    let backend = tui_termion::term::screen()?;
75 86
    let mut terminal = Terminal::new(backend)?;
76 87
    let mut viewer = DiffViewer::new(document, DiffOptions::default());
77 88
78 89
    terminal.clear()?;
79 90
    terminal.set_cursor_visible(false)?;
80 91
81 -
    let result = terminal_loop(&mut terminal, &mut viewer);
92 +
    let result = terminal_loop(&mut terminal, &mut viewer, header);
82 93
    let cursor = terminal.set_cursor_visible(true);
83 94
84 95
    result.and(cursor).map_err(Error::Io)
85 96
}
86 97
87 98
/// Runs the terminal event loop.
88 -
fn terminal_loop(terminal: &mut DiffTerminal, viewer: &mut DiffViewer) -> io::Result<()> {
99 +
fn terminal_loop(
100 +
    terminal: &mut DiffTerminal,
101 +
    viewer: &mut DiffViewer,
102 +
    header: Header,
103 +
) -> io::Result<()> {
89 104
    let (events_tx, events_rx) = mpsc::channel();
90 105
    TerminalEvent::spawn_input_worker(events_tx.clone());
91 106
92 107
    let highlights_tx = TerminalEvent::spawn_highlight_worker(events_tx);
93 108
    let mut session = TerminalSession {
94 109
        terminal,
95 110
        viewer,
96 111
        highlights_tx,
112 +
        header,
97 113
    };
98 114
    session.redraw()?;
99 115
100 116
    while let Ok(event) = events_rx.recv() {
101 117
        match event {
102 118
            TerminalEvent::Input(event) => {
103 119
                let event = event?;
104 -
                let area = body_area(session.terminal.area());
120 +
                let area = viewer_area(session.terminal.area());
105 121
                match handle_input(event, session.viewer, area) {
106 122
                    Control::Quit => break,
107 123
                    Control::Redraw => session.redraw()?,
108 124
                    Control::Continue | Control::Wait => {}
109 125
                }
124 140
    terminal: &'a mut DiffTerminal,
125 141
    /// Diff viewer state.
126 142
    viewer: &'a mut DiffViewer,
127 143
    /// Visible-row highlight request channel.
128 144
    highlights_tx: mpsc::Sender<Vec<HighlightRequest>>,
145 +
    /// Top chrome describing the current diff session.
146 +
    header: Header,
129 147
}
130 148
131 149
impl TerminalSession<'_> {
132 150
    /// Draws a frame and requests highlights for visible rows.
133 151
    fn redraw(&mut self) -> io::Result<()> {
136 154
        Ok(())
137 155
    }
138 156
139 157
    /// Requests highlight work for currently visible rows.
140 158
    fn request_visible_highlights(&mut self) {
141 -
        let area = body_area(self.terminal.area());
159 +
        let area = viewer_area(self.terminal.area());
142 160
        let requests = self.viewer.visible_highlight_requests(area);
143 161
        if !requests.is_empty() {
144 162
            let _ = self.highlights_tx.send(requests);
145 163
        }
146 164
    }
147 165
148 166
    /// Draws one terminal frame without scheduling highlight work.
149 167
    fn draw_frame(&mut self) -> io::Result<()> {
150 168
        self.terminal.draw(|frame| {
151 -
            let body = body_area(frame.area);
152 -
            frame.render_widget(&*self.viewer, body);
169 +
            let body = viewer_area(frame.area);
170 +
            draw_header(frame, &self.header);
171 +
            frame.render_widget(&mut *self.viewer, body);
153 172
            draw_status(frame);
154 173
        })
155 174
    }
156 175
}
157 176
177 +
/// Top header metadata for an interactive diff session.
178 +
#[derive(Clone, Debug, Eq, PartialEq)]
179 +
struct Header {
180 +
    /// Current working directory.
181 +
    cwd: PathBuf,
182 +
    /// Human-readable action being displayed.
183 +
    action: String,
184 +
}
185 +
186 +
impl Header {
187 +
    /// Returns metadata for a direct `git diff` invocation.
188 +
    fn git_diff(cwd: PathBuf, args: &[OsString]) -> Self {
189 +
        let mut action = String::from("git diff");
190 +
        for arg in args {
191 +
            action.push(' ');
192 +
            action.push_str(&arg.to_string_lossy());
193 +
        }
194 +
195 +
        Self { cwd, action }
196 +
    }
197 +
198 +
    /// Returns metadata for diff input read from standard input.
199 +
    fn stdin(cwd: PathBuf) -> Self {
200 +
        Self {
201 +
            cwd,
202 +
            action: String::from("stdin diff"),
203 +
        }
204 +
    }
205 +
}
206 +
158 207
/// Event delivered to the terminal loop.
159 208
enum TerminalEvent {
160 209
    /// Terminal input event.
161 210
    Input(io::Result<Event<()>>),
162 211
    /// Background highlight results.
192 241
        });
193 242
        requests_tx
194 243
    }
195 244
}
196 245
197 -
/// Returns the body area, leaving one row for status when possible.
198 -
fn body_area(area: Rect) -> Rect {
199 -
    Rect::new(area.x, area.y, area.cols, area.rows.saturating_sub(1))
246 +
/// Returns the viewer area between header and footer chrome.
247 +
fn viewer_area(area: Rect) -> Rect {
248 +
    let header_rows = HEADER_ROWS.min(area.rows);
249 +
    let footer_rows = FOOTER_ROWS.min(area.rows.saturating_sub(header_rows));
250 +
251 +
    Rect::new(
252 +
        area.x,
253 +
        area.y + header_rows,
254 +
        area.cols,
255 +
        area.rows.saturating_sub(header_rows + footer_rows),
256 +
    )
257 +
}
258 +
259 +
/// Draws the top header row.
260 +
fn draw_header(frame: &mut tui::Frame<'_>, header: &Header) {
261 +
    let area = frame.area;
262 +
    if area.rows == 0 {
263 +
        return;
264 +
    }
265 +
    let row = Rect::new(area.x, area.y, area.cols, 1);
266 +
267 +
    frame.render_widget(header_line(header, area.cols), row);
268 +
}
269 +
270 +
/// Returns the padded top header line.
271 +
fn header_line(header: &Header, cols: usize) -> Line {
272 +
    let folder = Label::new(&header.cwd.display().to_string()).style(header_path_style());
273 +
    let action = Label::new(&header.action).fg(FOOTER_FG);
274 +
    let occupied = Line::from(vec![folder.clone(), action.clone()]).width();
275 +
    let spacer = cols.saturating_sub(occupied);
276 +
    let mut line = Line::new(folder);
277 +
278 +
    line.push(Label::new(&" ".repeat(spacer)));
279 +
    line.push(action);
280 +
    line.style(Style::default().bg(FOOTER_BG)).padded(cols)
281 +
}
282 +
283 +
/// Returns the style for the current path in the top header.
284 +
fn header_path_style() -> Style {
285 +
    Style::new(FOOTER_FG).bg(FOOTER_BG).bold()
200 286
}
201 287
202 288
/// Draws the bottom status row.
203 289
fn draw_status(frame: &mut tui::Frame<'_>) {
204 290
    let area = frame.area;
205 -
    if area.rows == 0 {
291 +
    if area.rows <= HEADER_ROWS {
206 292
        return;
207 293
    }
208 -
    let status = Line::new(Label::new("rustik-diff").fg(Color::Fixed(244)))
209 -
        .style(Style::default().bg(Color::Fixed(236)));
210 294
    let row = Rect::new(area.x, area.bottom().saturating_sub(1), area.cols, 1);
211 295
212 -
    frame.render_widget(status, row);
296 +
    frame.render_widget(status_line(area.cols), row);
297 +
}
298 +
299 +
/// Returns the padded bottom status line.
300 +
fn status_line(cols: usize) -> Line {
301 +
    Line::new(Label::new("rustik-diff").fg(FOOTER_FG))
302 +
        .style(Style::default().bg(FOOTER_BG))
303 +
        .padded(cols)
213 304
}
214 305
215 306
/// Applies one input event to the viewer.
216 307
fn handle_input(event: Event<()>, viewer: &mut DiffViewer, area: Rect) -> Control {
217 308
    let action = match event {
220 311
            if viewer.apply(DiffAction::CollapseFocusedFile, area) == ViewChange::Changed {
221 312
                return Control::Redraw;
222 313
            }
223 314
            return Control::Quit;
224 315
        }
225 -
        Event::Key(Key::Char('j') | Key::Down) => DiffAction::Scroll(Scroll::Lines(1)),
226 -
        Event::Key(Key::Char('k') | Key::Up) => DiffAction::Scroll(Scroll::Lines(-1)),
316 +
        Event::Key(Key::Char('j') | Key::Down) => {
317 +
            DiffAction::Scroll(Scroll::Lines(LINE_SCROLL_ROWS))
318 +
        }
319 +
        Event::Key(Key::Char('k') | Key::Up) => {
320 +
            DiffAction::Scroll(Scroll::Lines(-LINE_SCROLL_ROWS))
321 +
        }
322 +
        Event::Key(Key::Char(' ')) => DiffAction::NextHunk,
227 323
        Event::Key(Key::PageDown) => DiffAction::Scroll(Scroll::Pages(1)),
228 324
        Event::Key(Key::PageUp) => DiffAction::Scroll(Scroll::Pages(-1)),
325 +
        Event::Key(Key::Ctrl('d')) => {
326 +
            DiffAction::Scroll(Scroll::Lines((area.rows / 2).max(1) as isize))
327 +
        }
328 +
        Event::Key(Key::Ctrl('u')) => {
329 +
            DiffAction::Scroll(Scroll::Lines(-((area.rows / 2).max(1) as isize)))
330 +
        }
229 331
        Event::Key(Key::Char('g') | Key::Home) => DiffAction::Scroll(Scroll::Top),
230 332
        Event::Key(Key::Char('G') | Key::End) => DiffAction::Scroll(Scroll::Bottom),
231 333
        Event::Key(Key::Char('n')) => DiffAction::FocusNext,
232 334
        Event::Key(Key::Char('p')) => DiffAction::FocusPrevious,
233 335
        Event::Key(Key::Enter) => DiffAction::ToggleFocusedFile,
234 336
        Event::Mouse(Mouse::Press {
235 337
            button: MouseButton::WheelDown,
236 338
            ..
237 -
        }) => DiffAction::Scroll(Scroll::Lines(3)),
339 +
        }) => DiffAction::Scroll(Scroll::Lines(LINE_SCROLL_ROWS)),
238 340
        Event::Mouse(Mouse::Press {
239 341
            button: MouseButton::WheelUp,
240 342
            ..
241 -
        }) => DiffAction::Scroll(Scroll::Lines(-3)),
343 +
        }) => DiffAction::Scroll(Scroll::Lines(-LINE_SCROLL_ROWS)),
242 344
        Event::Resize(_) => DiffAction::Resize,
243 345
        _ => return Control::Continue,
244 346
    };
245 347
    viewer.apply(action, area);
246 348
    Control::Redraw
+0 -0
+0 -0
a.rs +0 -0
crates/diff/src/renderer.rs +490 -186
4 4
use std::path::PathBuf;
5 5
6 6
use rustik_tui as tui;
7 7
use tui::{
8 8
    Buffer, Cell, Color, Constraint, HStack, Label, Line, Placement, Rect, Scroll, ScrollView,
9 -
    ScrollbarStyle, Size, Style, Table, TableOptions, VStack, View, Viewport, Widget, colors,
9 +
    Scrollbar, ScrollbarStyle, Size, Style, Text, View, Viewport, Widget, colors,
10 10
};
11 11
12 12
use crate::highlight::{HighlightKeyInput, HighlightResult};
13 13
use crate::{
14 14
    DiffDocument, DiffLine, DiffLineKind, DiffSide, FileDiff, FileId, FileKind, HighlightKey,
23 23
const MARKER_WIDTH: usize = 3;
24 24
/// Scrollbar track glyph (distinct from box-drawing borders so the column reads as a track).
25 25
const SCROLLBAR_TRACK: &str = "๐Ÿฎ˜";
26 26
/// Scrollbar thumb glyph.
27 27
const SCROLLBAR_THUMB: &str = "โ–“";
28 +
/// Scrollbar thumb color, one fixed-color shade darker than dim chrome.
29 +
const SCROLLBAR_THUMB_COLOR: Color = Color::Fixed(238);
28 30
/// File-card divider glyph (used between header/hunks and between hunks).
29 31
const DIVIDER: &str = "โ”€";
30 32
/// Sticky file-header divider glyph.
31 33
const STICKY_DIVIDER: &str = "โ•ด";
32 34
/// Pending file marker.
33 35
const FILE_MARKER: &str = "โ—‹";
34 36
/// Rename arrow.
35 37
const RENAME_ARROW: &str = "->";
36 38
/// Missing trailing newline marker.
37 39
const NO_NEWLINE_MARKER: &str = "\\ No newline at end of file";
40 +
/// Marker cell shown between hunks in the diff marker column.
41 +
const HUNK_GAP_MARKER_CELL: &str = " โ‹ฎ ";
38 42
/// Default highlight lookahead after the visible viewport.
39 43
const DEFAULT_HIGHLIGHT_LOOKAHEAD: usize = 4;
40 44
/// Default syntax theme name stored in highlight keys.
41 45
const DEFAULT_THEME: &str = "rustik";
46 +
/// Number of rows in a sticky file header.
47 +
const STICKY_HEADER_ROWS: usize = 3;
42 48
43 49
/// Mutable read-only diff viewport state.
44 50
#[derive(Clone, Debug, Default, Eq, PartialEq)]
45 51
pub struct DiffState {
46 52
    /// First visible row in the rendered document.
112 118
    state: DiffState,
113 119
    /// Highlighted row cache.
114 120
    highlights: BTreeMap<HighlightKey, Line>,
115 121
    /// Requests already handed to a worker.
116 122
    pending_highlights: BTreeSet<HighlightKey>,
123 +
    /// Cached full render rows keyed by render body width.
124 +
    rows_cache: BTreeMap<usize, Vec<RenderRow>>,
117 125
}
118 126
119 127
/// One rendered row before viewport projection.
120 128
#[derive(Clone, Debug)]
121 129
struct RenderRow {
182 190
            document,
183 191
            options,
184 192
            state: DiffState::default(),
185 193
            highlights: BTreeMap::new(),
186 194
            pending_highlights: BTreeSet::new(),
195 +
            rows_cache: BTreeMap::new(),
187 196
        }
188 197
    }
189 198
190 199
    /// Returns the viewed document.
191 200
    pub const fn document(&self) -> &DiffDocument {
195 204
    /// Returns the viewer state.
196 205
    pub const fn state(&self) -> &DiffState {
197 206
        &self.state
198 207
    }
199 208
200 -
    /// Returns the viewer state mutably.
201 -
    pub fn state_mut(&mut self) -> &mut DiffState {
202 -
        &mut self.state
209 +
    /// Replaces the viewer state.
210 +
    pub fn set_state(&mut self, state: DiffState) {
211 +
        if self.state.collapsed_files != state.collapsed_files {
212 +
            self.invalidate_rows();
213 +
        }
214 +
        self.state = state;
215 +
    }
216 +
217 +
    /// Sets the first visible rendered row.
218 +
    pub fn set_scroll(&mut self, scroll: usize) {
219 +
        self.state.scroll = scroll;
220 +
    }
221 +
222 +
    /// Sets the focused file or hunk.
223 +
    pub fn set_focus(&mut self, focus: Option<DiffFocus>) {
224 +
        self.state.focus = focus;
225 +
    }
226 +
227 +
    /// Sets the collapsed file sections.
228 +
    pub fn set_collapsed_files(&mut self, collapsed_files: BTreeSet<FileId>) {
229 +
        if self.state.collapsed_files != collapsed_files {
230 +
            self.invalidate_rows();
231 +
        }
232 +
        self.state.collapsed_files = collapsed_files;
203 233
    }
204 234
205 235
    /// Renders the current frame into `buf`.
206 -
    pub fn render(&self, area: Rect, buf: &mut Buffer) {
236 +
    pub fn render(&mut self, area: Rect, buf: &mut Buffer) {
207 237
        if area.is_empty() {
208 238
            return;
209 239
        }
210 240
        let body_cols = ScrollView::body_cols(area);
211 -
        let rows = self.render_rows(body_cols);
212 -
        let sticky =
213 -
            Self::sticky_rows(&rows, self.state.scroll, area.rows, body_cols).collect::<Vec<_>>();
214 -
        let lines = rows.into_iter().map(|row| row.line);
241 +
        self.ensure_rows(body_cols);
242 +
        let Some(rows) = self.cached_rows(body_cols) else {
243 +
            return;
244 +
        };
245 +
        let sticky = Self::sticky_rows(rows, self.state.scroll, area.rows, body_cols);
215 246
216 -
        ScrollView::from_lines(lines)
217 -
            .offset(self.state.scroll)
218 -
            .sticky(sticky)
219 -
            .scrollbar(Self::scrollbar_style())
220 -
            .render(area, buf);
247 +
        Self::render_visible_rows(rows, self.state.scroll, sticky, area, buf);
221 248
    }
222 249
223 250
    /// Returns the number of rendered rows at a given terminal width.
224 251
    pub fn content_rows(&self, cols: usize) -> usize {
225 -
        self.render_rows(ScrollView::body_cols(Rect::new(0, 0, cols, 1)))
226 -
            .len()
252 +
        let _ = cols;
253 +
        self.row_count()
227 254
    }
228 255
229 256
    /// Applies an action to the viewer state.
230 257
    pub fn apply(&mut self, action: DiffAction, area: Rect) -> ViewChange {
231 258
        let before = self.state.clone();
232 259
        let body_cols = ScrollView::body_cols(area);
233 -
        let rows = self.render_rows(body_cols);
234 -
        let body_rows = self.body_rows(&rows, self.state.scroll, area.rows);
235 260
236 261
        match action {
237 262
            DiffAction::Scroll(scroll) => {
263 +
                let content_rows = self.row_count();
238 264
                let mut viewport = Viewport::from_offset(self.state.scroll);
239 -
                viewport.scroll(scroll, rows.len(), body_rows);
265 +
                viewport.scroll(scroll, content_rows, area.rows);
240 266
                self.state.scroll = viewport.offset;
241 267
            }
242 268
            DiffAction::Resize => {
269 +
                let content_rows = self.row_count();
243 270
                let mut viewport = Viewport::from_offset(self.state.scroll);
244 -
                viewport.clamp(rows.len(), body_rows);
271 +
                viewport.clamp(content_rows, area.rows);
245 272
                self.state.scroll = viewport.offset;
246 273
            }
247 -
            DiffAction::FocusNext => self.focus_relative(&rows, body_rows, 1, FocusFilter::Any),
248 -
            DiffAction::FocusPrevious => {
249 -
                self.focus_relative(&rows, body_rows, -1, FocusFilter::Any)
274 +
            DiffAction::FocusNext => self.focus(body_cols, area.rows, 1, FocusFilter::File),
275 +
            DiffAction::FocusPrevious => self.focus(body_cols, area.rows, -1, FocusFilter::File),
276 +
            DiffAction::NextHunk => self.focus(body_cols, area.rows, 1, FocusFilter::Hunk),
277 +
            DiffAction::PreviousHunk => self.focus(body_cols, area.rows, -1, FocusFilter::Hunk),
278 +
            DiffAction::ToggleFocusedFile => {
279 +
                self.toggle_focused_file();
250 280
            }
251 -
            DiffAction::NextHunk => self.focus_relative(&rows, body_rows, 1, FocusFilter::Hunk),
252 -
            DiffAction::PreviousHunk => {
253 -
                self.focus_relative(&rows, body_rows, -1, FocusFilter::Hunk)
281 +
            DiffAction::CollapseFocusedFile => {
282 +
                self.collapse_focused_file();
254 283
            }
255 -
            DiffAction::ToggleFocusedFile => self.toggle_focused_file(),
256 -
            DiffAction::CollapseFocusedFile => self.collapse_focused_file(),
257 284
        }
258 -
        let body_rows = self.body_rows(&rows, self.state.scroll, area.rows);
259 -
        self.state.scroll = View::new(self.state.scroll, rows.len(), body_rows).offset;
260 285
286 +
        if self.state.collapsed_files != before.collapsed_files {
287 +
            let changed = self
288 +
                .state
289 +
                .collapsed_files
290 +
                .symmetric_difference(&before.collapsed_files)
291 +
                .copied()
292 +
                .collect::<BTreeSet<_>>();
293 +
            self.refresh_cached_files(&changed);
294 +
            self.clamp_scroll(area);
295 +
        }
261 296
        if self.state == before {
262 297
            ViewChange::Unchanged
263 298
        } else {
264 299
            ViewChange::Changed
265 300
        }
266 301
    }
267 302
268 -
    /// Returns the body height visible after subtracting any sticky header rows.
269 -
    fn body_rows(&self, rows: &[RenderRow], scroll: usize, area_rows: usize) -> usize {
270 -
        area_rows.saturating_sub(Self::sticky_row_count(rows, scroll, area_rows))
271 -
    }
272 -
273 303
    /// Returns highlight requests for visible source rows plus configured lookahead.
274 304
    pub fn visible_highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
275 -
        let rows = self.render_rows(ScrollView::body_cols(area));
276 -
        let view = View::new(self.state.scroll, rows.len(), area.rows);
305 +
        self.ensure_rows(ScrollView::body_cols(area));
277 306
        let take = area.rows.saturating_add(self.options.highlight_lookahead);
278 -
        let mut requests = Vec::new();
279 -
280 -
        for row in rows.iter().skip(view.offset).take(take) {
281 -
            let RowMeta::DiffLine(meta) = &row.meta else {
282 -
                continue;
307 +
        let visible = {
308 +
            let body_cols = ScrollView::body_cols(area);
309 +
            let Some(rows) = self.cached_rows(body_cols) else {
310 +
                return Vec::new();
283 311
            };
312 +
            let view = View::new(self.state.scroll, rows.len(), area.rows);
313 +
            let start =
314 +
                view.offset
315 +
                    .saturating_add(Self::sticky_row_count(rows, view.offset, area.rows));
316 +
317 +
            rows.iter()
318 +
                .skip(start)
319 +
                .take(take)
320 +
                .filter_map(|row| match &row.meta {
321 +
                    RowMeta::DiffLine(meta) => Some(meta.clone()),
322 +
                    _ => None,
323 +
                })
324 +
                .collect::<Vec<_>>()
325 +
        };
326 +
327 +
        let mut requests = Vec::new();
328 +
        for meta in visible {
284 329
            let key = HighlightKey::new(HighlightKeyInput {
285 330
                file: meta.file,
286 331
                hunk: meta.hunk,
287 332
                row: meta.row,
288 333
                side: meta.side,
295 340
                continue;
296 341
            }
297 342
            self.pending_highlights.insert(key.clone());
298 343
            requests.push(HighlightRequest {
299 344
                key,
300 -
                path: meta.path.clone(),
301 -
                text: meta.text.clone(),
345 +
                path: meta.path,
346 +
                text: meta.text,
302 347
            });
303 348
        }
304 349
        requests
305 350
    }
306 351
307 352
    /// Merges highlighted rows and returns whether a redraw is needed.
308 353
    pub fn apply_highlights(&mut self, results: impl IntoIterator<Item = HighlightResult>) -> bool {
309 354
        let mut changed = false;
355 +
        let mut files = BTreeSet::new();
310 356
        for result in results {
311 357
            self.pending_highlights.remove(&result.key);
358 +
            files.insert(result.key.file);
312 359
            self.highlights.insert(result.key, result.line);
313 360
            changed = true;
314 361
        }
362 +
        if changed {
363 +
            self.refresh_cached_files(&files);
364 +
        }
315 365
        changed
316 366
    }
317 367
368 +
    /// Ensures rendered rows are cached for a width.
369 +
    fn ensure_rows(&mut self, cols: usize) {
370 +
        let cols = cols.max(MIN_RENDER_COLS);
371 +
        if !self.rows_cache.contains_key(&cols) {
372 +
            self.rows_cache.insert(cols, self.render_rows(cols));
373 +
        }
374 +
    }
375 +
376 +
    /// Returns cached render rows for a width.
377 +
    fn cached_rows(&self, cols: usize) -> Option<&[RenderRow]> {
378 +
        self.rows_cache
379 +
            .get(&cols.max(MIN_RENDER_COLS))
380 +
            .map(Vec::as_slice)
381 +
    }
382 +
383 +
    /// Clears cached rendered rows.
384 +
    fn invalidate_rows(&mut self) {
385 +
        self.rows_cache.clear();
386 +
    }
387 +
388 +
    /// Borrows cached rows and dispatches a focus walk against the live state.
389 +
    fn focus(&mut self, body_cols: usize, area_rows: usize, delta: isize, filter: FocusFilter) {
390 +
        let body_cols = body_cols.max(MIN_RENDER_COLS);
391 +
        self.ensure_rows(body_cols);
392 +
        let Some(rows) = self.rows_cache.remove(&body_cols) else {
393 +
            return;
394 +
        };
395 +
        Self::focus_relative(&mut self.state, &rows, area_rows, delta, filter);
396 +
        self.rows_cache.insert(body_cols, rows);
397 +
    }
398 +
399 +
    /// Returns the content row count without building render rows.
400 +
    fn row_count(&self) -> usize {
401 +
        self.document.preamble.len()
402 +
            + self
403 +
                .document
404 +
                .files
405 +
                .iter()
406 +
                .map(|file| self.file_row_count(file))
407 +
                .sum::<usize>()
408 +
    }
409 +
410 +
    /// Returns the row count for one file card.
411 +
    fn file_row_count(&self, file: &FileDiff) -> usize {
412 +
        let collapsed = self.state.collapsed_files.contains(&file.id);
413 +
        let base_rows = 3;
414 +
        if collapsed || file.hunks.is_empty() {
415 +
            return base_rows;
416 +
        }
417 +
        base_rows
418 +
            + 1
419 +
            + file.hunks.len()
420 +
            + file
421 +
                .hunks
422 +
                .iter()
423 +
                .map(|hunk| hunk.lines.len())
424 +
                .sum::<usize>()
425 +
            + file.hunks.len().saturating_sub(1)
426 +
    }
427 +
428 +
    /// Clamps scroll after a row-count-changing action.
429 +
    fn clamp_scroll(&mut self, area: Rect) {
430 +
        let content_rows = self.row_count();
431 +
        self.state.scroll = View::new(self.state.scroll, content_rows, area.rows).offset;
432 +
    }
433 +
434 +
    /// Refreshes cached rows for files whose highlighted lines changed.
435 +
    fn refresh_cached_files(&mut self, files: &BTreeSet<FileId>) {
436 +
        if self.rows_cache.is_empty() {
437 +
            return;
438 +
        }
439 +
        let cols = self.rows_cache.keys().copied().collect::<Vec<_>>();
440 +
        let replacements = cols
441 +
            .iter()
442 +
            .copied()
443 +
            .map(|cols| {
444 +
                let files = files
445 +
                    .iter()
446 +
                    .filter_map(|file| {
447 +
                        let document_file =
448 +
                            self.document.files.iter().find(|item| item.id == *file)?;
449 +
                        let mut rows = Vec::new();
450 +
                        self.push_file_rows(document_file, cols, &mut rows);
451 +
                        Some((*file, rows))
452 +
                    })
453 +
                    .collect::<Vec<_>>();
454 +
                (cols, files)
455 +
            })
456 +
            .collect::<Vec<_>>();
457 +
458 +
        for (cols, files) in replacements {
459 +
            let Some(cache) = self.rows_cache.get_mut(&cols) else {
460 +
                continue;
461 +
            };
462 +
            for (file, rows) in files {
463 +
                let Some(start) = cache
464 +
                    .iter()
465 +
                    .position(|row| row.meta == RowMeta::FileTop(file))
466 +
                else {
467 +
                    continue;
468 +
                };
469 +
                let end = cache
470 +
                    .iter()
471 +
                    .enumerate()
472 +
                    .skip(start + 1)
473 +
                    .find_map(|(row, candidate)| match candidate.meta {
474 +
                        RowMeta::FileBottom(candidate) if candidate == file => Some(row + 1),
475 +
                        _ => None,
476 +
                    })
477 +
                    .unwrap_or(start + 1);
478 +
479 +
                cache.splice(start..end, rows);
480 +
            }
481 +
        }
482 +
    }
483 +
318 484
    /// Builds all render rows for a width.
319 485
    fn render_rows(&self, cols: usize) -> Vec<RenderRow> {
320 486
        let cols = cols.max(MIN_RENDER_COLS);
321 487
        let mut rows = Vec::new();
322 488
332 498
        rows
333 499
    }
334 500
335 501
    /// Adds one file card to render rows.
336 502
    fn push_file_rows(&self, file: &FileDiff, cols: usize, rows: &mut Vec<RenderRow>) {
337 -
        let border = Self::file_border(self.state.focus == Some(DiffFocus::File(file.id)));
503 +
        let border = Self::file_border();
338 504
        let collapsed = self.state.collapsed_files.contains(&file.id);
339 505
        let child_cols = cols.saturating_sub(4);
340 -
        let mut stack = VStack::default().border(Some(border)).padding(1);
341 -
        let mut metas = Vec::new();
342 506
343 -
        metas.push(RowMeta::FileTop(file.id));
344 -
        stack.push(file.header_line(child_cols));
345 -
        metas.push(RowMeta::FileHeader(file.id));
507 +
        rows.push(RenderRow {
508 +
            line: border.top(cols.saturating_sub(2)),
509 +
            meta: RowMeta::FileTop(file.id),
510 +
        });
511 +
        rows.push(RenderRow {
512 +
            line: Self::file_child_line(file.header_line(child_cols), child_cols, border),
513 +
            meta: RowMeta::FileHeader(file.id),
514 +
        });
346 515
        if !collapsed && !file.hunks.is_empty() {
347 -
            stack = stack.divider_cell(Cell::new(DIVIDER, border.style));
348 -
            metas.push(RowMeta::FileDivider(file.id));
516 +
            rows.push(RenderRow {
517 +
                line: border.divider(cols.saturating_sub(2), DIVIDER),
518 +
                meta: RowMeta::FileDivider(file.id),
519 +
            });
349 520
            for (index, hunk) in file.hunks.iter().enumerate() {
350 521
                if index > 0 {
351 -
                    stack = stack.divider_cell(Cell::new(DIVIDER, border.style));
352 -
                    metas.push(RowMeta::HunkDivider(file.id));
522 +
                    rows.push(RenderRow {
523 +
                        line: Self::file_child_line(Self::hunk_gap_line(), child_cols, border),
524 +
                        meta: RowMeta::HunkDivider(file.id),
525 +
                    });
353 526
                }
354 -
                stack.push(hunk.header_line());
355 -
                metas.push(RowMeta::HunkHeader(file.id, hunk.id));
527 +
                rows.push(RenderRow {
528 +
                    line: Self::file_child_line(hunk.header_line(), child_cols, border),
529 +
                    meta: RowMeta::HunkHeader(file.id, hunk.id),
530 +
                });
356 531
                for row in self.hunk_rows(file, hunk, child_cols) {
357 -
                    stack.push(row.line);
358 -
                    metas.push(row.meta);
532 +
                    rows.push(RenderRow {
533 +
                        line: Self::file_child_line(row.line, child_cols, border),
534 +
                        meta: row.meta,
535 +
                    });
359 536
                }
360 537
            }
361 538
        }
362 -
        metas.push(RowMeta::FileBottom(file.id));
539 +
        rows.push(RenderRow {
540 +
            line: border.bottom(cols.saturating_sub(2)),
541 +
            meta: RowMeta::FileBottom(file.id),
542 +
        });
543 +
    }
363 544
364 -
        rows.extend(
365 -
            stack
366 -
                .lines(Constraint::tight(cols))
367 -
                .into_iter()
368 -
                .zip(metas)
369 -
                .map(|(line, meta)| RenderRow { line, meta }),
370 -
        );
545 +
    /// Wraps one file-card child row with padding and borders.
546 +
    fn file_child_line(mut line: Line, child_cols: usize, border: tui::Border) -> Line {
547 +
        Line::truncate(&mut line, child_cols, "โ€ฆ");
548 +
        Line::pad(&mut line, child_cols);
549 +
        Line::new(border.left(1)).extend(line).item(border.right(1))
371 550
    }
372 551
373 552
    /// Returns sticky file-header rows for the current offset.
374 -
    fn sticky_rows<'a>(
375 -
        rows: &'a [RenderRow],
553 +
    fn sticky_rows(
554 +
        rows: &[RenderRow],
376 555
        scroll: usize,
377 556
        visible_rows: usize,
378 557
        cols: usize,
379 -
    ) -> impl Iterator<Item = Line> + 'a {
380 -
        Self::sticky_row_start(rows, scroll, visible_rows)
381 -
            .into_iter()
382 -
            .flat_map(move |start| {
558 +
    ) -> Vec<Line> {
559 +
        Self::sticky_start(rows, scroll, visible_rows)
560 +
            .map(|start| {
383 561
                rows.iter()
384 562
                    .skip(start)
385 -
                    .take(3)
563 +
                    .take(STICKY_HEADER_ROWS)
386 564
                    .enumerate()
387 -
                    .map(move |(index, row)| {
388 -
                        if index == 2 {
565 +
                    .map(|(index, row)| {
566 +
                        if index == STICKY_HEADER_ROWS - 1 {
389 567
                            Self::sticky_divider(cols)
390 568
                        } else {
391 569
                            row.line.clone()
392 570
                        }
393 571
                    })
572 +
                    .collect()
394 573
            })
574 +
            .unwrap_or_default()
395 575
    }
396 576
397 577
    /// Returns the number of sticky rows for the current offset.
398 578
    fn sticky_row_count(rows: &[RenderRow], scroll: usize, visible_rows: usize) -> usize {
399 -
        Self::sticky_row_start(rows, scroll, visible_rows).map_or(0, |_| 3)
579 +
        Self::sticky_start(rows, scroll, visible_rows).map_or(0, |_| STICKY_HEADER_ROWS)
400 580
    }
401 581
402 -
    /// Returns the first sticky row index for the current offset.
403 -
    fn sticky_row_start(rows: &[RenderRow], scroll: usize, visible_rows: usize) -> Option<usize> {
582 +
    /// Returns the source row for the sticky header at the current offset.
583 +
    fn sticky_start(rows: &[RenderRow], scroll: usize, visible_rows: usize) -> Option<usize> {
404 584
        let scroll = scroll.min(rows.len().saturating_sub(visible_rows));
405 585
        if scroll == 0 {
406 586
            return None;
407 587
        }
408 588
        let file = rows.get(scroll).and_then(|row| row.meta.file())?;
409 589
        let start = rows
410 590
            .iter()
411 591
            .position(|row| row.meta == RowMeta::FileTop(file))?;
412 -
        if scroll <= start.saturating_add(2) {
592 +
        if scroll <= start {
593 +
            return None;
594 +
        }
595 +
        let file_bottom = rows
596 +
            .iter()
597 +
            .enumerate()
598 +
            .skip(start + 1)
599 +
            .find_map(|(row, candidate)| match candidate.meta {
600 +
                RowMeta::FileBottom(candidate) if candidate == file => Some(row),
601 +
                _ => None,
602 +
            })
603 +
            .unwrap_or(rows.len());
604 +
        if file_bottom < scroll.saturating_add(visible_rows) {
413 605
            return None;
414 606
        }
415 607
        Some(start)
416 608
    }
417 609
418 610
    /// Focuses a target relative to the current focus.
419 611
    fn focus_relative(
420 -
        &mut self,
612 +
        state: &mut DiffState,
421 613
        rows: &[RenderRow],
422 614
        visible_rows: usize,
423 615
        delta: isize,
424 616
        filter: FocusFilter,
425 617
    ) {
426 -
        let target_count = filter.targets(rows).count();
427 -
        if target_count == 0 {
618 +
        let targets = filter.targets(rows);
619 +
        if targets.is_empty() {
428 620
            return;
429 621
        }
430 -
        let current = self.state.focus.and_then(|focus| {
431 -
            filter
432 -
                .targets(rows)
433 -
                .position(|target| target.focus == focus)
434 -
        });
622 +
        let current = state
623 +
            .focus
624 +
            .and_then(|focus| targets.iter().position(|target| target.focus == focus));
435 625
        let next = match (current, delta.is_negative()) {
436 626
            (Some(index), true) => index.saturating_sub(1),
437 -
            (Some(index), false) => index.saturating_add(1).min(target_count - 1),
438 -
            (None, true) => target_count - 1,
627 +
            (Some(index), false) => index.saturating_add(1).min(targets.len() - 1),
628 +
            (None, true) => targets.len() - 1,
439 629
            (None, false) => 0,
440 630
        };
441 -
        let Some(target) = filter.targets(rows).nth(next) else {
631 +
        let Some(target) = targets.get(next) else {
442 632
            return;
443 633
        };
444 634
445 -
        self.state.focus = Some(target.focus);
446 -
        let mut viewport = Viewport::from_offset(self.state.scroll);
635 +
        state.focus = Some(target.focus);
636 +
        if filter == FocusFilter::File {
637 +
            state.scroll = View::new(target.row, rows.len(), visible_rows).offset;
638 +
            return;
639 +
        }
447 640
448 -
        viewport.scroll_to_row(target.row, rows.len(), visible_rows, Placement::Minimal);
449 -
        self.state.scroll = viewport.offset;
641 +
        let mut viewport = Viewport::from_offset(state.scroll);
642 +
        let margin = visible_rows / 4;
643 +
        viewport.scroll_to_row(
644 +
            target.row,
645 +
            rows.len(),
646 +
            visible_rows,
647 +
            Placement::Margin {
648 +
                before: margin.max(Self::sticky_row_count(rows, state.scroll, visible_rows)),
649 +
                after: margin,
650 +
            },
651 +
        );
652 +
        state.scroll = viewport.offset;
450 653
    }
451 654
452 655
    /// Toggles the file containing the current focus.
453 656
    fn toggle_focused_file(&mut self) {
454 657
        let Some(file) = self.focused_file() else {
481 684
                .map(|file| file.id),
482 685
        }
483 686
    }
484 687
485 688
    /// Returns hunk table rows.
486 -
    fn hunk_rows(
487 -
        &self,
488 -
        file: &FileDiff,
489 -
        hunk: &crate::Hunk,
490 -
        inner: usize,
491 -
    ) -> impl Iterator<Item = RenderRow> {
492 -
        let mut table = Table::new(TableOptions {
493 -
            spacing: 0,
494 -
            ..TableOptions::default()
495 -
        });
496 -
        let mut metas = Vec::with_capacity(hunk.lines.len());
689 +
    fn hunk_rows(&self, file: &FileDiff, hunk: &crate::Hunk, inner: usize) -> Vec<RenderRow> {
690 +
        let mut rows = Vec::with_capacity(hunk.lines.len());
497 691
        let mut old_line = hunk.header.old_line_no;
498 692
        let mut new_line = hunk.header.new_line_no;
693 +
        let source_cols = inner.saturating_sub(LINE_NUMBER_WIDTH * 2 + MARKER_WIDTH);
499 694
500 695
        for line in &hunk.lines {
501 -
            let meta = self.push_hunk_row(
502 -
                &mut table,
696 +
            rows.push(self.hunk_row(
503 697
                file,
504 698
                hunk.id,
505 699
                line,
506 700
                &mut old_line,
507 701
                &mut new_line,
508 -
            );
509 -
            metas.push(meta);
702 +
                source_cols,
703 +
            ));
510 704
        }
511 705
512 -
        table
513 -
            .lines(Constraint::tight(inner))
514 -
            .into_iter()
515 -
            .zip(metas)
516 -
            .map(|(line, meta)| RenderRow { line, meta })
706 +
        rows
517 707
    }
518 708
519 -
    /// Pushes a single hunk row onto the table and returns its metadata.
520 -
    fn push_hunk_row(
709 +
    /// Returns one rendered hunk row.
710 +
    fn hunk_row(
521 711
        &self,
522 -
        table: &mut Table<4, Line>,
523 712
        file: &FileDiff,
524 713
        hunk: HunkId,
525 714
        line: &DiffLine,
526 715
        old_line: &mut u32,
527 716
        new_line: &mut u32,
528 -
    ) -> RowMeta {
717 +
        source_cols: usize,
718 +
    ) -> RenderRow {
529 719
        match line.kind {
530 720
            DiffLineKind::Addition => {
531 721
                let source_line = *new_line;
532 722
                let meta = DiffLineMeta::new(file, hunk, line, DiffSide::New, source_line);
533 -
                let row = [
534 -
                    Self::blank_number(colors::rgb::POSITIVE),
535 -
                    Self::number_cell(
536 -
                        source_line,
537 -
                        colors::rgb::POSITIVE_LIGHT,
538 -
                        colors::rgb::POSITIVE,
539 -
                    ),
540 -
                    Self::marker_cell(" + ", colors::rgb::POSITIVE_LIGHT),
541 -
                    self.highlighted_or_plain(&meta),
542 -
                ];
543 -
                table.push_styled(row, Style::default().bg(colors::rgb::POSITIVE_DARK));
723 +
                let rendered = self.hunk_line(
724 +
                    [
725 +
                        Self::blank_number(colors::rgb::POSITIVE),
726 +
                        Self::number_cell(
727 +
                            source_line,
728 +
                            colors::rgb::POSITIVE_LIGHT,
729 +
                            colors::rgb::POSITIVE,
730 +
                        ),
731 +
                        Self::marker_cell(" + ", colors::rgb::POSITIVE_LIGHT),
732 +
                    ],
733 +
                    self.highlighted_or_plain(&meta, source_cols),
734 +
                    source_cols,
735 +
                    Style::default().bg(colors::rgb::POSITIVE_DARK),
736 +
                );
544 737
                *new_line = new_line.saturating_add(1);
545 -
                RowMeta::DiffLine(meta)
738 +
                RenderRow {
739 +
                    line: rendered,
740 +
                    meta: RowMeta::DiffLine(meta),
741 +
                }
546 742
            }
547 743
            DiffLineKind::Deletion => {
548 744
                let source_line = *old_line;
549 745
                let meta = DiffLineMeta::new(file, hunk, line, DiffSide::Old, source_line);
550 -
                let row = [
551 -
                    Self::number_cell(
552 -
                        source_line,
553 -
                        colors::rgb::NEGATIVE_LIGHT,
554 -
                        colors::rgb::NEGATIVE,
555 -
                    ),
556 -
                    Self::blank_number(colors::rgb::NEGATIVE),
557 -
                    Self::marker_cell(" - ", colors::rgb::NEGATIVE_LIGHT),
558 -
                    self.highlighted_or_plain(&meta),
559 -
                ];
560 -
                table.push_styled(row, Style::default().bg(colors::rgb::NEGATIVE_DARK).dim());
746 +
                let rendered = self.hunk_line(
747 +
                    [
748 +
                        Self::number_cell(
749 +
                            source_line,
750 +
                            colors::rgb::NEGATIVE_LIGHT,
751 +
                            colors::rgb::NEGATIVE,
752 +
                        ),
753 +
                        Self::blank_number(colors::rgb::NEGATIVE),
754 +
                        Self::marker_cell(" - ", colors::rgb::NEGATIVE_LIGHT),
755 +
                    ],
756 +
                    self.highlighted_or_plain(&meta, source_cols),
757 +
                    source_cols,
758 +
                    Style::default().bg(colors::rgb::NEGATIVE_DARK).dim(),
759 +
                );
561 760
                *old_line = old_line.saturating_add(1);
562 -
                RowMeta::DiffLine(meta)
761 +
                RenderRow {
762 +
                    line: rendered,
763 +
                    meta: RowMeta::DiffLine(meta),
764 +
                }
563 765
            }
564 766
            DiffLineKind::Context => {
565 767
                let source_line = *new_line;
566 768
                let meta = DiffLineMeta::new(file, hunk, line, DiffSide::New, source_line);
567 -
                let row = [
568 -
                    Self::number_cell(*old_line, colors::rgb::DIM, colors::rgb::FAINT),
569 -
                    Self::number_cell(source_line, colors::rgb::DIM, colors::rgb::FAINT),
570 -
                    Self::marker_cell("   ", Color::Unset),
571 -
                    self.highlighted_or_plain(&meta),
572 -
                ];
573 -
                table.push(row);
769 +
                let rendered = self.hunk_line(
770 +
                    [
771 +
                        Self::number_cell(*old_line, colors::rgb::DIM, colors::rgb::FAINT),
772 +
                        Self::number_cell(source_line, colors::rgb::DIM, colors::rgb::FAINT),
773 +
                        Self::marker_cell("   ", Color::Unset),
774 +
                    ],
775 +
                    self.highlighted_or_plain(&meta, source_cols),
776 +
                    source_cols,
777 +
                    Style::default(),
778 +
                );
574 779
                *old_line = old_line.saturating_add(1);
575 780
                *new_line = new_line.saturating_add(1);
576 -
                RowMeta::DiffLine(meta)
781 +
                RenderRow {
782 +
                    line: rendered,
783 +
                    meta: RowMeta::DiffLine(meta),
784 +
                }
577 785
            }
578 786
            DiffLineKind::NoNewline => {
579 -
                let row = [
580 -
                    Line::blank().padded(LINE_NUMBER_WIDTH),
581 -
                    Line::blank().padded(LINE_NUMBER_WIDTH),
582 -
                    Self::marker_cell("   ", Color::Unset),
583 -
                    Line::new(NO_NEWLINE_MARKER).style(Style::default().fg(colors::rgb::DIM)),
584 -
                ];
585 -
                table.push(row);
586 -
                RowMeta::DiffLine(DiffLineMeta::new(
587 -
                    file,
588 -
                    hunk,
589 -
                    line,
590 -
                    DiffSide::New,
591 -
                    *new_line,
592 -
                ))
787 +
                let meta = DiffLineMeta::new(file, hunk, line, DiffSide::New, *new_line);
788 +
                RenderRow {
789 +
                    line: self.hunk_line(
790 +
                        [
791 +
                            Line::blank().padded(LINE_NUMBER_WIDTH),
792 +
                            Line::blank().padded(LINE_NUMBER_WIDTH),
793 +
                            Self::marker_cell("   ", Color::Unset),
794 +
                        ],
795 +
                        Line::new(NO_NEWLINE_MARKER).style(Style::default().fg(colors::rgb::DIM)),
796 +
                        source_cols,
797 +
                        Style::default(),
798 +
                    ),
799 +
                    meta: RowMeta::DiffLine(meta),
800 +
                }
593 801
            }
594 802
        }
595 803
    }
596 804
805 +
    /// Returns a fixed-column hunk row line.
806 +
    fn hunk_line(
807 +
        &self,
808 +
        cells: [Line; 3],
809 +
        mut source: Line,
810 +
        source_cols: usize,
811 +
        style: Style,
812 +
    ) -> Line {
813 +
        let inner = source_cols.saturating_add(LINE_NUMBER_WIDTH * 2 + MARKER_WIDTH);
814 +
        Line::truncate(&mut source, source_cols, "โ€ฆ");
815 +
        Line::pad(&mut source, source_cols);
816 +
        let mut line = Line::blank()
817 +
            .extend(cells[0].clone())
818 +
            .extend(cells[1].clone())
819 +
            .extend(cells[2].clone())
820 +
            .extend(source);
821 +
        Line::pad(&mut line, inner);
822 +
        Line::truncate(&mut line, inner, "โ€ฆ");
823 +
        line.style(style)
824 +
    }
825 +
597 826
    /// Returns a highlighted line from cache or plain text when no result has arrived.
598 -
    fn highlighted_or_plain(&self, meta: &DiffLineMeta) -> Line {
827 +
    fn highlighted_or_plain(&self, meta: &DiffLineMeta, cols: usize) -> Line {
599 828
        let key = HighlightKey::new(HighlightKeyInput {
600 829
            file: meta.file,
601 830
            hunk: meta.hunk,
602 831
            row: meta.row,
603 832
            side: meta.side,
607 836
            theme: &self.options.theme,
608 837
        });
609 838
        self.highlights
610 839
            .get(&key)
611 840
            .cloned()
612 -
            .unwrap_or_else(|| Line::new(meta.text.clone()))
841 +
            .unwrap_or_else(|| Line::new(Text::truncate(meta.text.as_str(), cols, "โ€ฆ")))
613 842
    }
614 843
615 844
    /// Returns a line-number cell.
616 845
    fn number_cell(value: u32, foreground: Color, background: Color) -> Line {
617 846
        Line::new(Label::new(&value.to_string()).fg(foreground).bg(background))
627 856
    fn marker_cell(marker: &str, foreground: Color) -> Line {
628 857
        Line::new(Label::new(marker).fg(foreground)).padded(MARKER_WIDTH)
629 858
    }
630 859
631 860
    /// Returns the border for a file card.
632 -
    fn file_border(focused: bool) -> tui::Border {
633 -
        if focused {
634 -
            tui::Border::new(colors::fixed::DIM)
635 -
        } else {
636 -
            tui::Border::new(colors::FAINT)
637 -
        }
861 +
    fn file_border() -> tui::Border {
862 +
        tui::Border::new(colors::FAINT)
863 +
    }
864 +
865 +
    /// Returns the compact marker row between hunks in one file.
866 +
    fn hunk_gap_line() -> Line {
867 +
        Line::blank()
868 +
            .extend(Line::blank().padded(LINE_NUMBER_WIDTH))
869 +
            .extend(Line::blank().padded(LINE_NUMBER_WIDTH))
870 +
            .extend(Self::marker_cell(HUNK_GAP_MARKER_CELL, colors::rgb::DIM))
638 871
    }
639 872
640 873
    /// Returns a sticky divider line that matches a bordered file card's width.
641 874
    fn sticky_divider(cols: usize) -> Line {
642 -
        tui::Border::new(colors::FAINT).divider(cols.saturating_sub(2), STICKY_DIVIDER)
875 +
        Self::file_border().divider(cols.saturating_sub(2), STICKY_DIVIDER)
643 876
    }
644 877
645 878
    /// Returns the diff scrollbar style.
646 879
    fn scrollbar_style() -> ScrollbarStyle {
647 880
        ScrollbarStyle::new(
648 881
            Cell::new(SCROLLBAR_TRACK, Style::default().fg(colors::FAINT)),
649 -
            Cell::new(SCROLLBAR_THUMB, Style::default().fg(colors::fixed::DIM)),
882 +
            Cell::new(SCROLLBAR_THUMB, Style::default().fg(SCROLLBAR_THUMB_COLOR)),
650 883
        )
651 884
    }
885 +
886 +
    /// Renders the visible viewport from cached full rows.
887 +
    fn render_visible_rows(
888 +
        rows: &[RenderRow],
889 +
        scroll: usize,
890 +
        sticky: Vec<Line>,
891 +
        area: Rect,
892 +
        buf: &mut Buffer,
893 +
    ) {
894 +
        let (text_area, scrollbar_area) = Self::viewport_areas(area);
895 +
        let sticky_rows = sticky.len().min(text_area.rows);
896 +
        let body_area = Rect::new(
897 +
            text_area.x,
898 +
            text_area.y + sticky_rows,
899 +
            text_area.cols,
900 +
            text_area.rows.saturating_sub(sticky_rows),
901 +
        );
902 +
        let view = View::new(scroll, rows.len(), text_area.rows);
903 +
        let body_offset = view.offset.saturating_add(sticky_rows);
904 +
905 +
        if sticky_rows > 0 {
906 +
            let sticky_area = Rect::new(text_area.x, text_area.y, text_area.cols, sticky_rows);
907 +
            Line::renders(sticky.into_iter().take(sticky_rows), sticky_area, buf);
908 +
        }
909 +
        Line::renders(
910 +
            rows.iter()
911 +
                .skip(body_offset)
912 +
                .take(body_area.rows)
913 +
                .map(|row| row.line.clone()),
914 +
            body_area,
915 +
            buf,
916 +
        );
917 +
918 +
        if let Some(area) = scrollbar_area {
919 +
            Scrollbar::new(view)
920 +
                .style(Self::scrollbar_style())
921 +
                .render(area, buf);
922 +
        }
923 +
    }
924 +
925 +
    /// Splits a viewport into body text and scrollbar areas.
926 +
    fn viewport_areas(area: Rect) -> (Rect, Option<Rect>) {
927 +
        if area.cols > 2 {
928 +
            (
929 +
                Rect::new(area.x, area.y, area.cols - 1, area.rows),
930 +
                Some(Rect::new(area.right() - 1, area.y, 1, area.rows)),
931 +
            )
932 +
        } else {
933 +
            (area, None)
934 +
        }
935 +
    }
652 936
}
653 937
654 938
impl Widget for DiffViewer {
655 939
    fn size(&self, parent: Constraint) -> Size {
656 940
        let cols = if parent.max.cols == usize::MAX {
657 941
            MIN_RENDER_COLS
658 942
        } else {
659 943
            parent.max.cols
660 944
        };
661 -
662 945
        Size::new(cols, self.content_rows(cols)).constrain(parent)
663 946
    }
664 947
665 948
    fn render(&mut self, area: Rect, buf: &mut Buffer) {
666 -
        Self::render(self, area, buf);
949 +
        if area.is_empty() {
950 +
            return;
951 +
        }
952 +
        let body_cols = ScrollView::body_cols(area);
953 +
        self.ensure_rows(body_cols);
954 +
        let Some(rows) = self.cached_rows(body_cols) else {
955 +
            return;
956 +
        };
957 +
        let sticky = Self::sticky_rows(rows, self.state.scroll, area.rows, body_cols);
958 +
959 +
        Self::render_visible_rows(rows, self.state.scroll, sticky, area, buf);
960 +
    }
961 +
962 +
    fn to_buffer(&mut self, constraints: Constraint) -> Buffer {
963 +
        let size = self.size(constraints);
964 +
        let area = Rect::from_size(size);
965 +
        let mut buffer = Buffer::empty(area);
966 +
        let body_cols = ScrollView::body_cols(area);
967 +
        let rows = self.render_rows(body_cols);
968 +
        let sticky = Self::sticky_rows(&rows, self.state.scroll, area.rows, body_cols);
969 +
970 +
        Self::render_visible_rows(&rows, self.state.scroll, sticky, area, &mut buffer);
971 +
972 +
        buffer
667 973
    }
668 974
}
669 975
670 976
impl RowMeta {
671 977
    /// Returns the containing file for row kinds that belong to a file card.
693 999
}
694 1000
695 1001
/// Focus target filter.
696 1002
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
697 1003
enum FocusFilter {
698 -
    /// File and hunk targets.
699 -
    Any,
1004 +
    /// File targets only.
1005 +
    File,
700 1006
    /// Hunk targets only.
701 1007
    Hunk,
702 1008
}
703 1009
704 1010
impl FocusFilter {
705 1011
    /// Returns focusable targets from render rows.
706 -
    fn targets<'a>(self, rows: &'a [RenderRow]) -> impl Iterator<Item = FocusTarget> + 'a {
1012 +
    fn targets(self, rows: &[RenderRow]) -> Vec<FocusTarget> {
707 1013
        rows.iter()
708 1014
            .enumerate()
709 1015
            .filter_map(move |(row, render_row)| match render_row.meta {
710 -
                RowMeta::FileHeader(file) if self == Self::Any => Some(FocusTarget {
1016 +
                RowMeta::FileTop(file) if self == Self::File => Some(FocusTarget {
711 1017
                    focus: DiffFocus::File(file),
712 1018
                    row,
713 1019
                }),
714 -
                RowMeta::HunkHeader(_, hunk) => Some(FocusTarget {
1020 +
                RowMeta::HunkHeader(_, hunk) if self == Self::Hunk => Some(FocusTarget {
715 1021
                    focus: DiffFocus::Hunk(hunk),
716 1022
                    row,
717 1023
                }),
718 1024
                _ => None,
719 1025
            })
1026 +
            .collect()
720 1027
    }
721 1028
}
722 1029
723 1030
impl FileDiff {
724 1031
    /// Returns the source path for a file side.
830 1137
}
831 1138
832 1139
impl crate::Hunk {
833 1140
    /// Returns a hunk header line.
834 1141
    fn header_line(&self) -> Line {
835 -
        Line::spaced([
836 -
            Label::new(&format!("hunk {}", *self.id + 1)).fg(colors::fixed::DIM),
837 -
            Label::new(&self.header_text()).fg(colors::fixed::FAINT),
838 -
        ])
1142 +
        Line::new(Label::new(&self.header_text()).fg(colors::fixed::FAINT))
839 1143
    }
840 1144
841 1145
    /// Returns the stable hunk header prefix and trailing text.
842 1146
    fn header_text(&self) -> String {
843 1147
        let header = &self.header;
873 1177
        }
874 1178
    }
875 1179
}
876 1180
877 1181
#[cfg(test)]
878 -
#[allow(clippy::expect_used)]
1182 +
#[allow(clippy::expect_used, clippy::unwrap_used)]
879 1183
mod tests {
880 1184
    use super::*;
881 1185
    use crate::Decode;
882 1186
    use crate::DiffDocument;
883 1187
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs +0 -0