Skip to main content

rustik_diff/
viewer.rs

1//! Read-only diff viewer state and buffer rendering.
2
3mod tree;
4
5use std::collections::btree_map::Entry;
6use std::collections::{BTreeMap, BTreeSet};
7use std::convert::Infallible;
8use std::path::{Path, PathBuf};
9
10use rustik_highlight as syntax;
11use rustik_tui as tui;
12use tui::{
13    Buffer, Cell, Color, Constraint, Control, Event, HStack, Key, Label, Line, Mouse, MouseButton,
14    Placement, Rect, Scroll, ScrollView, ScrollbarStyle, Size, Style, Table, TableOptions, Text,
15    VStack, View, Viewport, Widget, colors,
16};
17
18use crate::context::{self, ContextChange, ContextState};
19use crate::highlight::{DiffHighlighter, HighlightKeyInput, HighlightResult};
20use crate::word;
21use crate::{
22    Commit, Decode, DecodeError, DiffDocument, DiffLine, DiffLineKind, DiffSide, FileDiff, FileId,
23    FileKind, HighlightKey, HighlightRequest, HighlightSource, Hunk, HunkId, RowId,
24};
25
26pub use tree::{FileTreeMode, FileTreeTarget};
27
28/// Minimum width before the viewer attempts table-style diff rows.
29const MIN_RENDER_COLS: usize = 12;
30/// Width of old and new line number cells.
31const LINE_NUMBER_WIDTH: usize = 5;
32/// Foreground color used by old and new line number cells.
33const LINE_NUMBER_FG: Color = colors::fixed::DIM;
34/// Width of the hunk marker cell.
35const MARKER_WIDTH: usize = 3;
36/// Scrollbar track glyph (distinct from box-drawing borders so the column reads as a track).
37const SCROLLBAR_TRACK: char = '🮘';
38/// Scrollbar thumb glyph.
39const SCROLLBAR_THUMB: char = '▐';
40/// Scrollbar thumb color, one fixed-color shade darker than dim chrome.
41const SCROLLBAR_THUMB_COLOR: Color = Color::Fixed(237);
42/// File-card divider glyph (used between header/hunks and between hunks).
43const DIVIDER: char = '─';
44/// Foreground color for neutral file-kind badges such as moved and copied.
45const FILE_KIND_BADGE_FG: Color = colors::rgb::PURPLE;
46/// Dim background for neutral file-kind badges.
47const FILE_KIND_BADGE_BG: Color = Color::RGB(32, 22, 42);
48/// Shared border style for all file cards.
49const FILE_BORDER: tui::Border = tui::Border::new(colors::FAINT);
50/// Sticky file-header divider glyph.
51const STICKY_DIVIDER: char = '╴';
52/// Rename arrow.
53const RENAME_ARROW: &str = "→";
54/// Missing trailing newline marker.
55const NO_NEWLINE_MARKER: &str = "\\ No newline at end of file";
56/// Marker cell shown between hunks in the diff marker column.
57const HUNK_GAP_MARKER_CELL: &str = " ⋮ ";
58/// Default highlight lookahead after the visible viewport.
59const DEFAULT_HIGHLIGHT_LOOKAHEAD: usize = 4;
60/// Default syntax theme selection stored in highlight keys.
61const DEFAULT_THEME: &str = "auto";
62/// Number of rows in a sticky file header.
63const STICKY_HEADER_ROWS: usize = 3;
64/// Number of body rows moved by keyboard line-scroll inputs.
65const LINE_SCROLL_ROWS: isize = 1;
66/// Number of body rows moved by mouse-wheel inputs.
67const WHEEL_SCROLL_ROWS: isize = 3;
68/// Local row of a file card's top border.
69const FILE_TOP_ROW: usize = 0;
70/// Local row of a file card's header.
71const FILE_HEADER_ROW: usize = 1;
72/// Local row of the divider between a file header and its hunk body.
73const FILE_DIVIDER_ROW: usize = 2;
74/// Local row of the first hunk body line after the fixed file-card chrome.
75const HUNK_BODY_START: usize = FILE_DIVIDER_ROW + 1;
76/// Total card height when the file has no visible body.
77const EMPTY_CARD_ROWS: usize = FILE_DIVIDER_ROW + 1;
78
79/// Mutable read-only diff viewport state.
80#[derive(Clone, Debug, Default, Eq, PartialEq)]
81pub struct DiffState {
82    /// First visible row in the rendered document.
83    pub scroll: usize,
84    /// Currently focused file or hunk.
85    pub focus: Option<DiffFocus>,
86    /// Collapsed file sections.
87    pub collapsed_files: BTreeSet<FileId>,
88}
89
90impl DiffState {
91    /// Returns whether replacing this state with `next` invalidates cached row positions.
92    fn invalidates_index(&self, next: &Self) -> bool {
93        self.collapsed_files != next.collapsed_files
94    }
95}
96
97/// Focus target inside a diff document.
98#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
99pub enum DiffFocus {
100    /// Focus a file header.
101    File(FileId),
102    /// Focus a hunk header.
103    Hunk(HunkId),
104}
105
106/// Viewer action accepted by [`DiffViewer::apply`].
107#[derive(Clone, Copy, Debug, Eq, PartialEq)]
108pub enum DiffAction {
109    /// Scroll the viewport.
110    Scroll(Scroll),
111    /// Clamp scroll after a terminal resize.
112    Resize,
113    /// Focus the next file or hunk target.
114    FocusNext,
115    /// Focus the previous file or hunk target.
116    FocusPrevious,
117    /// Focus the next hunk target.
118    NextHunk,
119    /// Focus the previous hunk target.
120    PreviousHunk,
121    /// Toggle the focused file between collapsed and expanded states.
122    ToggleFocusedFile,
123    /// Collapse the focused file, or report no change if it is already collapsed.
124    CollapseFocusedFile,
125    /// Toggle the file tree between automatic visibility and hidden.
126    ToggleFileTree,
127    /// Move the file-tree cursor by visible rows, jumping to files as they are selected.
128    MoveFileTree(isize),
129    /// Show the current file-tree target without changing folder expansion.
130    ShowFileTreeTarget,
131    /// Activate the current file-tree target.
132    ActivateFileTreeTarget,
133    /// Collapse the focused file-tree folder.
134    CollapseFileTreeFolder,
135    /// Expand the focused file-tree folder.
136    ExpandFileTreeFolder,
137}
138
139/// Result of applying a viewer action.
140#[derive(Clone, Copy, Debug, Eq, PartialEq)]
141pub enum ViewChange {
142    /// The action changed viewer state.
143    Changed,
144    /// The action left viewer state unchanged.
145    Unchanged,
146}
147
148/// Diff viewer options.
149#[derive(Clone, Debug)]
150pub struct DiffOptions {
151    /// Number of rows after the visible viewport to request for highlighting.
152    pub highlight_lookahead: usize,
153    /// Optional syntax override stored in highlight requests.
154    pub syntax: Option<String>,
155    /// Theme name stored in highlight requests.
156    pub theme: String,
157    /// Positive and negative colors used for diff chrome.
158    pub diff_palette: DiffPalette,
159    /// Whether the file tree may be rendered beside the diff.
160    pub file_tree: FileTreeMode,
161    /// Folder name shown as the file tree root.
162    pub file_tree_root: String,
163}
164
165/// Positive and negative colors used for diff chrome.
166#[derive(Clone, Copy, Debug, Eq, PartialEq)]
167pub struct DiffPalette {
168    /// Background color for removed source rows.
169    pub negative_row_bg: Color,
170    /// Background color for added source rows.
171    pub positive_row_bg: Color,
172    /// Background color for changed word spans inside removed rows.
173    pub negative_word_bg: Color,
174    /// Background color for changed word spans inside added rows.
175    pub positive_word_bg: Color,
176    /// Foreground color for removed stats, markers, and labels.
177    pub negative_fg: Color,
178    /// Foreground color for added stats, markers, and labels.
179    pub positive_fg: Color,
180}
181
182/// Repo refetch request prepared by the viewer for asynchronous context updates.
183#[derive(Clone, Debug)]
184pub struct ContextRequest {
185    /// Context state to install when the request completes.
186    next_context: ContextState,
187    /// File to focus after applying the fetched replacement.
188    active: Option<FileId>,
189    /// Paths and original file ids to replace.
190    files: Vec<(PathBuf, FileId)>,
191    /// Git context width to request.
192    context_lines: usize,
193    /// Next hunk and row ids used to remap fetched files.
194    next_ids: (usize, usize),
195}
196
197/// Decoded replacement files for an asynchronous context update.
198#[derive(Clone, Debug)]
199pub struct ContextUpdate {
200    /// Context state prepared when the request was started.
201    next_context: ContextState,
202    /// File to focus after applying the fetched replacement.
203    active: Option<FileId>,
204    /// Replacement file diffs with ids remapped to this viewer.
205    files: Vec<FileDiff>,
206}
207
208/// Pure diff viewer that renders into a caller-owned buffer.
209#[derive(Clone, Debug)]
210pub struct DiffViewer {
211    /// Diff document being viewed.
212    document: DiffDocument,
213    /// Viewer options.
214    options: DiffOptions,
215    /// Mutable viewport state.
216    state: DiffState,
217    /// Highlighted row cache.
218    highlights: BTreeMap<HighlightKey, Line>,
219    /// Requests already handed to a worker.
220    pending_highlights: BTreeSet<HighlightKey>,
221    /// Per-hunk source context reused across highlight-request batches.
222    hunk_highlight_sources: BTreeMap<(FileId, HunkId, DiffSide), HighlightSource>,
223    /// Cached intra-line word diffs, keyed by hunk.
224    word_diffs: BTreeMap<HunkId, word::WordChanges>,
225    /// Rendered commit-preamble rows for the most recent body width.
226    preamble: Vec<Line>,
227    /// File-tree state and model.
228    file_tree: tree::FileTreeViewer,
229    /// Interactive override for file-tree visibility.
230    file_tree_visibility: FileTreeVisibility,
231    /// Cached rendered row positions for visible files.
232    index: RowIndex,
233    /// Hunk-context expansion bookkeeping.
234    context: ContextState,
235}
236
237/// Cached rendered row positions for the current document visibility state.
238///
239/// Visible files tile the content region contiguously, so each file is stored
240/// by its first rendered row only; its last row is the next file's start (or
241/// [`RowIndex::rows`] for the final file).
242#[derive(Clone, Debug, Default)]
243struct RowIndex {
244    /// Visible files in rendered order, each at its first rendered row.
245    files: Vec<IndexedFileRows>,
246    /// Total number of rendered rows.
247    rows: usize,
248}
249
250/// The rendered position of one visible file.
251#[derive(Clone, Copy, Debug)]
252struct IndexedFileRows {
253    /// Index into the document file list.
254    file_index: usize,
255    /// First rendered row occupied by the file.
256    start: usize,
257}
258
259/// One rendered row before viewport projection.
260#[derive(Clone, Debug)]
261struct RenderRow {
262    /// Renderable line.
263    line: Line,
264    /// Source-row metadata when this is a diff source row.
265    diff: Option<DiffLineMeta>,
266}
267
268/// Render location of a row inside one file card.
269#[derive(Clone, Copy, Debug, Eq, PartialEq)]
270struct FileRowLocation<'a> {
271    /// File containing the row.
272    file: &'a FileDiff,
273    /// Global row where the file card starts.
274    start: usize,
275    /// Global row one past the end of the file card.
276    end: usize,
277    /// Row offset inside the file card.
278    local: usize,
279}
280
281/// Sticky file-header rows visible during a render pass.
282#[derive(Clone, Copy, Debug, Eq, PartialEq)]
283struct StickyHeaderRows {
284    /// Global source row where the full file header starts.
285    start: usize,
286    /// Number of header rows still pinned in the viewport.
287    rows: usize,
288}
289
290/// Metadata for one source row.
291#[derive(Clone, Debug, Eq, PartialEq)]
292struct DiffLineMeta {
293    /// File containing the row.
294    file: FileId,
295    /// Hunk containing the row.
296    hunk: HunkId,
297    /// Row identifier.
298    row: RowId,
299    /// Line role inside the hunk.
300    kind: DiffLineKind,
301    /// Source side used for highlighting.
302    side: DiffSide,
303    /// One-based source line number.
304    source_line: u32,
305    /// Source text.
306    text: String,
307    /// Source path.
308    path: Option<PathBuf>,
309}
310
311/// Main viewer layout for the current viewport.
312#[derive(Clone, Copy, Debug, Eq, PartialEq)]
313struct DiffLayout {
314    /// Main diff rectangle.
315    diff: Rect,
316    /// File tree rectangle, when the tree is visible.
317    tree: Option<Rect>,
318}
319
320/// Interactive override for the configured file-tree rendering policy.
321#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
322enum FileTreeVisibility {
323    /// Follow the configured file-tree rendering policy.
324    #[default]
325    Auto,
326    /// Hide the file tree until it is toggled back on.
327    Hidden,
328}
329
330impl Default for DiffOptions {
331    fn default() -> Self {
332        Self {
333            highlight_lookahead: DEFAULT_HIGHLIGHT_LOOKAHEAD,
334            syntax: None,
335            theme: DEFAULT_THEME.to_owned(),
336            diff_palette: DiffPalette::default(),
337            file_tree: FileTreeMode::default(),
338            file_tree_root: ".".to_owned(),
339        }
340    }
341}
342
343impl Default for DiffPalette {
344    fn default() -> Self {
345        Self {
346            negative_row_bg: colors::rgb::NEGATIVE_DARK,
347            positive_row_bg: colors::rgb::POSITIVE_DARK,
348            negative_word_bg: colors::rgb::NEGATIVE,
349            positive_word_bg: colors::rgb::POSITIVE,
350            negative_fg: colors::rgb::NEGATIVE_LIGHT,
351            positive_fg: colors::rgb::POSITIVE_LIGHT,
352        }
353    }
354}
355
356impl From<&syntax::RawTheme> for DiffPalette {
357    fn from(theme: &syntax::RawTheme) -> Self {
358        let mut palette = Self::default();
359        if theme.colors.is_empty() {
360            return palette;
361        };
362        palette.positive_fg =
363            Self::theme_color(&theme.colors, "gitDecoration.addedResourceForeground")
364                .or_else(|| Self::theme_color(&theme.colors, "editorGutter.addedBackground"))
365                .unwrap_or(palette.positive_fg);
366        palette.negative_fg =
367            Self::theme_color(&theme.colors, "gitDecoration.deletedResourceForeground")
368                .or_else(|| Self::theme_color(&theme.colors, "editorGutter.deletedBackground"))
369                .unwrap_or(palette.negative_fg);
370        palette.positive_row_bg =
371            Self::theme_color(&theme.colors, "diffEditor.insertedLineBackground")
372                .unwrap_or(palette.positive_row_bg);
373        palette.negative_row_bg =
374            Self::theme_color(&theme.colors, "diffEditor.removedLineBackground")
375                .unwrap_or(palette.negative_row_bg);
376        palette.positive_word_bg =
377            Self::theme_color(&theme.colors, "diffEditor.insertedTextBackground")
378                .unwrap_or(palette.positive_word_bg);
379        palette.negative_word_bg =
380            Self::theme_color(&theme.colors, "diffEditor.removedTextBackground")
381                .unwrap_or(palette.negative_word_bg);
382        palette
383    }
384}
385
386impl DiffPalette {
387    /// Returns one RGB color from a theme color map.
388    fn theme_color(colors: &BTreeMap<String, String>, key: &str) -> Option<Color> {
389        let color = colors.get(key)?.parse::<syntax::Rgb>().ok()?;
390        Some(Color::RGB(color.r, color.g, color.b))
391    }
392}
393
394impl ContextRequest {
395    /// Returns the Git context width to fetch.
396    pub const fn context_lines(&self) -> usize {
397        self.context_lines
398    }
399
400    /// Returns the paths that should be fetched from the repo.
401    pub fn paths(&self) -> impl Iterator<Item = &Path> {
402        self.files.iter().map(|(path, _)| path.as_path())
403    }
404
405    /// Decodes a repo patch into a viewer update.
406    pub fn decode(self, patch: &[u8]) -> Result<Option<ContextUpdate>, DecodeError> {
407        let document = DiffDocument::decode_bytes(patch)?;
408        let result: Result<Option<Vec<FileDiff>>, Infallible> =
409            context::rebuild(self.next_ids, &self.files, self.context_lines, |_, _| {
410                Ok(document.files)
411            });
412        let files = match result {
413            Ok(Some(files)) => files,
414            Ok(None) => return Ok(None),
415            Err(error) => match error {},
416        };
417
418        Ok(Some(ContextUpdate {
419            next_context: self.next_context,
420            active: self.active,
421            files,
422        }))
423    }
424}
425
426impl DiffViewer {
427    /// Creates a viewer with plain initial rendering state.
428    pub fn new(document: DiffDocument, options: DiffOptions) -> Self {
429        let preamble = Self::preamble(document.commit.as_ref(), MIN_RENDER_COLS);
430        let file_tree = tree::FileTreeViewer::new(&document, options.file_tree_root.clone());
431        let state = DiffState::default();
432
433        let mut viewer = Self {
434            document,
435            options,
436            state,
437            highlights: BTreeMap::new(),
438            pending_highlights: BTreeSet::new(),
439            hunk_highlight_sources: BTreeMap::new(),
440            word_diffs: BTreeMap::new(),
441            preamble,
442            file_tree,
443            file_tree_visibility: FileTreeVisibility::default(),
444            index: RowIndex::default(),
445            context: ContextState::new(),
446        };
447        viewer.rebuild_index();
448        viewer
449    }
450
451    /// Returns the viewed document.
452    pub const fn document(&self) -> &DiffDocument {
453        &self.document
454    }
455
456    /// Returns the viewer state.
457    pub const fn state(&self) -> &DiffState {
458        &self.state
459    }
460
461    /// Replaces the viewer state.
462    pub fn set_state(&mut self, state: DiffState) {
463        let rebuild = self.state.invalidates_index(&state);
464        self.state = state;
465
466        if rebuild {
467            self.rebuild_index();
468        }
469    }
470
471    /// Replaces existing file diffs in place, matching them by id.
472    pub fn replace_file_diffs(&mut self, files: impl IntoIterator<Item = FileDiff>) {
473        for replacement in files {
474            // File ids match list indices for the originally decoded document;
475            // fall back to a scan when a refetch has perturbed that.
476            let existing = match self.document.files.get_mut(*replacement.id) {
477                Some(existing) if existing.id == replacement.id => Some(existing),
478                _ => self
479                    .document
480                    .files
481                    .iter_mut()
482                    .find(|file| file.id == replacement.id),
483            };
484            if let Some(existing) = existing {
485                *existing = replacement;
486            }
487        }
488        self.pending_highlights.clear();
489        self.hunk_highlight_sources.clear();
490        self.word_diffs.clear();
491        self.rebuild_index();
492    }
493
494    /// Prepares a repo refetch request for an asynchronous context update.
495    pub fn context_request(&self, change: ContextChange) -> Option<ContextRequest> {
496        let active = self.active_context_file();
497        let file_ids = self.context_file_ids(active);
498        let plan = self.context.plan(change, &file_ids, &self.document)?;
499        if plan.files.is_empty() {
500            return None;
501        }
502
503        Some(ContextRequest {
504            next_context: plan.state,
505            active,
506            files: plan.files,
507            context_lines: plan.context_lines,
508            next_ids: context::next_ids(&self.document.files),
509        })
510    }
511
512    /// Applies a completed asynchronous context update.
513    pub fn apply_context_update(&mut self, update: ContextUpdate, area: Rect) -> bool {
514        if update.files.is_empty() {
515            return false;
516        }
517        let mut state = self.state.clone();
518        if update.active.is_some() {
519            state.focus = update.active.map(DiffFocus::File);
520        }
521        self.context = update.next_context;
522        self.replace_file_diffs(update.files);
523        self.set_state(state);
524        self.apply(DiffAction::Resize, area) == ViewChange::Changed
525    }
526
527    /// Returns the active file targeted by context changes.
528    fn active_context_file(&self) -> Option<FileId> {
529        self.focused_file().or_else(|| self.visible_file())
530    }
531
532    /// Returns the files targeted by a context change.
533    fn context_file_ids(&self, active: Option<FileId>) -> Vec<FileId> {
534        active
535            .filter(|id| self.document.files.iter().any(|file| file.id == *id))
536            .or_else(|| self.document.files.first().map(|file| file.id))
537            .into_iter()
538            .collect()
539    }
540
541    /// Sets the first visible rendered row.
542    pub fn set_scroll(&mut self, scroll: usize) {
543        self.state.scroll = scroll;
544    }
545
546    /// Sets the focused file or hunk.
547    pub fn set_focus(&mut self, focus: Option<DiffFocus>) {
548        self.state.focus = focus;
549    }
550
551    /// Sets the collapsed file sections.
552    pub fn set_collapsed_files(&mut self, collapsed_files: BTreeSet<FileId>) {
553        self.state.collapsed_files = collapsed_files;
554        self.rebuild_index();
555    }
556
557    /// Returns the file containing the current focus.
558    pub fn focused_file(&self) -> Option<FileId> {
559        match self.state.focus? {
560            DiffFocus::File(file) => Some(file),
561            DiffFocus::Hunk(hunk) => self
562                .document
563                .files
564                .iter()
565                .find(|file| file.hunks.iter().any(|candidate| candidate.id == hunk))
566                .map(|file| file.id),
567        }
568    }
569
570    /// Returns the file occupying the first visible diff row.
571    fn visible_file(&self) -> Option<FileId> {
572        self.file_row_location(self.state.scroll)
573            .map(|location| location.file.id)
574            .or_else(|| self.document.files.first().map(|file| file.id))
575    }
576
577    /// Returns rendered rows plus trailing space needed to top-anchor the final file.
578    fn scroll_rows(&self, visible_rows: usize) -> usize {
579        let last_file_start = self.index.files.last().map_or(0, |file| file.start);
580
581        self.index
582            .rows
583            .max(last_file_start.saturating_add(visible_rows))
584    }
585
586    /// Returns rendered rows plus trailing space needed by `scroll`.
587    fn render_rows_for(&self, scroll: usize, visible_rows: usize) -> usize {
588        self.index.rows.max(scroll.saturating_add(visible_rows))
589    }
590
591    /// Shows `file` in the diff view without moving the file-tree cursor.
592    fn show_file(&mut self, file: FileId, visible_rows: usize) {
593        let Some(row) = self.index.files.iter().find_map(|indexed| {
594            let candidate = self.document.files.get(indexed.file_index)?;
595
596            (candidate.id == file).then_some(indexed.start)
597        }) else {
598            return;
599        };
600        self.state.focus = Some(DiffFocus::File(file));
601        self.state.scroll = View::new(row, self.scroll_rows(visible_rows), visible_rows).offset;
602    }
603
604    /// Updates the file-tree cursor to the visible diff file.
605    fn sync_file_tree(&mut self) {
606        if let Some(file) = self.visible_file() {
607            self.file_tree.select_file(file);
608        }
609    }
610
611    /// Renders the current frame into `buf`.
612    pub fn render(&mut self, area: Rect, buf: &mut Buffer) {
613        if area.is_empty() {
614            return;
615        }
616        let layout = self.layout(area);
617        if let Some(tree) = layout.tree {
618            self.render_file_tree(tree, buf);
619        }
620        self.render_diff(layout.diff, buf);
621    }
622
623    /// Returns the viewport layout for `area`.
624    fn layout(&self, area: Rect) -> DiffLayout {
625        if self.options.file_tree != FileTreeMode::Auto
626            || self.file_tree_visibility == FileTreeVisibility::Hidden
627            || area.cols <= tree::MIN_VIEW_COLS
628            || self.document.files.is_empty()
629        {
630            return DiffLayout {
631                diff: area,
632                tree: None,
633            };
634        }
635
636        let [tree, _, diff] = tui::layout::Layout::new(tui::Direction::Horizontal)
637            .child(tui::Length::Fixed(self.file_tree.cols(area.cols)))
638            .child(tui::Length::Fixed(tree::GAP_COLS))
639            .child(tui::Length::Fill(1))
640            .areas(area);
641
642        DiffLayout {
643            diff,
644            tree: Some(tree),
645        }
646    }
647
648    /// Renders the file tree.
649    fn render_file_tree(&mut self, area: Rect, buf: &mut Buffer) {
650        let active_file = self.visible_file();
651        self.file_tree
652            .render(active_file, self.options.diff_palette, area, buf);
653    }
654
655    /// Renders the main diff view into `buf`.
656    fn render_diff(&mut self, area: Rect, buf: &mut Buffer) {
657        let body_cols = ScrollView::body_cols(area);
658        // Rebuild preamble for the available body width so line wrapping matches
659        // current viewport size.
660        let preamble_rows = self.preamble.len();
661        self.preamble = Self::preamble(self.document.commit.as_ref(), body_cols);
662
663        if self.preamble.len() != preamble_rows {
664            self.rebuild_index();
665        }
666        let scroll = self.state.scroll;
667        let sticky = self.sticky_rows(scroll, area.rows, body_cols);
668        // Body offset skips sticky rows so the main diff starts below the fixed
669        // header strip.
670        let body_offset = scroll.saturating_add(sticky.len().min(area.rows));
671        let render_rows = self.render_rows_for(scroll, area.rows);
672
673        ScrollView::virtualized(render_rows, body_offset, |row, cols| {
674            self.render_row(row, cols)
675                .map(|row| row.line)
676                .unwrap_or_default()
677        })
678        .sticky(sticky)
679        .scrollbar_view(View::new(scroll, render_rows, area.rows))
680        .scrollbar(Self::scrollbar_style())
681        .render(area, buf);
682    }
683
684    /// Applies an action to the viewer state.
685    pub fn apply(&mut self, action: DiffAction, area: Rect) -> ViewChange {
686        let before = self.state.clone();
687        let before_visibility = self.file_tree_visibility;
688        let before_file_tree = self.file_tree.state().clone();
689        let layout = self.layout(area);
690        let diff = layout.diff;
691
692        if layout.tree.is_none()
693            && matches!(
694                action,
695                DiffAction::MoveFileTree(_)
696                    | DiffAction::ShowFileTreeTarget
697                    | DiffAction::ActivateFileTreeTarget
698                    | DiffAction::CollapseFileTreeFolder
699                    | DiffAction::ExpandFileTreeFolder,
700            )
701        {
702            return ViewChange::Unchanged;
703        }
704
705        match action {
706            DiffAction::Scroll(scroll) => {
707                let mut viewport = Viewport::from_offset(self.state.scroll);
708                let previous = self.state.scroll;
709                viewport.scroll(scroll, self.scroll_rows(diff.rows), diff.rows);
710                self.state.scroll = viewport.offset;
711                if self.state.scroll != previous
712                    && layout.tree.is_some()
713                    && let Some(file) = self.visible_file()
714                {
715                    self.state.focus = Some(DiffFocus::File(file));
716                    self.file_tree.select_file(file);
717                }
718            }
719            DiffAction::Resize => {
720                let mut viewport = Viewport::from_offset(self.state.scroll);
721                viewport.clamp(self.scroll_rows(diff.rows), diff.rows);
722                self.state.scroll = viewport.offset;
723                if layout.tree.is_some() {
724                    self.sync_file_tree();
725                }
726            }
727            DiffAction::FocusNext => {
728                self.focus(diff.rows, 1, FocusFilter::File);
729                self.sync_file_tree();
730            }
731            DiffAction::FocusPrevious => {
732                self.focus(diff.rows, -1, FocusFilter::File);
733                self.sync_file_tree();
734            }
735            DiffAction::NextHunk => {
736                self.focus(diff.rows, 1, FocusFilter::Hunk);
737                self.sync_file_tree();
738            }
739            DiffAction::PreviousHunk => {
740                self.focus(diff.rows, -1, FocusFilter::Hunk);
741                self.sync_file_tree();
742            }
743            DiffAction::ToggleFocusedFile => {
744                let had_focus = self.focused_file().is_some();
745                self.toggle_focused_file();
746                if had_focus {
747                    self.sync_file_tree();
748                }
749            }
750            DiffAction::CollapseFocusedFile => {
751                let had_focus = self.focused_file().is_some();
752                self.collapse_focused_file();
753                if had_focus {
754                    self.sync_file_tree();
755                }
756            }
757            DiffAction::ToggleFileTree => match self.file_tree_visibility {
758                FileTreeVisibility::Hidden => {
759                    self.file_tree_visibility = FileTreeVisibility::Auto;
760                    if self.layout(area).tree.is_some() {
761                        self.sync_file_tree();
762                    }
763                }
764                FileTreeVisibility::Auto if layout.tree.is_some() => {
765                    self.file_tree_visibility = FileTreeVisibility::Hidden;
766                }
767                FileTreeVisibility::Auto => {}
768            },
769            DiffAction::MoveFileTree(delta) => {
770                if self.file_tree.state().selected().is_none() {
771                    self.file_tree.enter(self.visible_file());
772                }
773                if let Some(file) = self.file_tree.select(delta) {
774                    self.show_file(file, diff.rows);
775                }
776            }
777            DiffAction::ShowFileTreeTarget => {
778                if let Some(file) = self.file_tree.selected_file() {
779                    self.show_file(file, diff.rows);
780                }
781            }
782            DiffAction::ActivateFileTreeTarget => {
783                if let Some(file) = self.file_tree.activate_target() {
784                    self.show_file(file, diff.rows);
785                }
786            }
787            DiffAction::CollapseFileTreeFolder => {
788                self.file_tree.collapse_folder();
789            }
790            DiffAction::ExpandFileTreeFolder => {
791                self.file_tree.expand_folder();
792            }
793        }
794
795        if before.invalidates_index(&self.state) {
796            self.rebuild_index();
797            self.state.scroll =
798                View::new(self.state.scroll, self.scroll_rows(diff.rows), diff.rows).offset;
799        }
800        if self.state == before
801            && self.file_tree_visibility == before_visibility
802            && *self.file_tree.state() == before_file_tree
803        {
804            ViewChange::Unchanged
805        } else {
806            ViewChange::Changed
807        }
808    }
809
810    /// Applies one input event to the viewer.
811    ///
812    /// Context-changing keys (`.`, `,`, `x`) are handled by the session loop,
813    /// which refetches diffs off the terminal thread, so they fall through here.
814    pub fn handle_input(&mut self, event: Event<()>, area: Rect) -> Control {
815        let action = match event {
816            Event::Key(Key::Char('q')) => return Control::Quit,
817            Event::Key(Key::Char('`')) => DiffAction::ToggleFileTree,
818            Event::Resize(_) => DiffAction::Resize,
819            Event::Mouse(Mouse::Press {
820                button: MouseButton::WheelDown,
821                ..
822            }) => DiffAction::Scroll(Scroll::Lines(WHEEL_SCROLL_ROWS)),
823            Event::Mouse(Mouse::Press {
824                button: MouseButton::WheelUp,
825                ..
826            }) => DiffAction::Scroll(Scroll::Lines(-WHEEL_SCROLL_ROWS)),
827            Event::Mouse(Mouse::Press {
828                button: MouseButton::Left,
829                at,
830                ..
831            }) => {
832                let Some(tree) = self.layout(area).tree else {
833                    return Control::Continue;
834                };
835                let action = match self.file_tree.select_at(tree, at) {
836                    Some(tree::FileTreeClick::Disclosure) => return Control::Redraw,
837                    Some(tree::FileTreeClick::Row) => DiffAction::ShowFileTreeTarget,
838                    None => return Control::Continue,
839                };
840                self.apply(action, area);
841                return Control::Redraw;
842            }
843            Event::Key(Key::Esc) => {
844                if self.apply(DiffAction::CollapseFocusedFile, area) == ViewChange::Changed {
845                    return Control::Redraw;
846                }
847                return Control::Quit;
848            }
849            Event::Key(Key::Char('j') | Key::Down) => {
850                DiffAction::Scroll(Scroll::Lines(LINE_SCROLL_ROWS))
851            }
852            Event::Key(Key::Char('k') | Key::Up) => {
853                DiffAction::Scroll(Scroll::Lines(-LINE_SCROLL_ROWS))
854            }
855            Event::Key(Key::Char('J')) => DiffAction::MoveFileTree(1),
856            Event::Key(Key::Char('K')) => DiffAction::MoveFileTree(-1),
857            Event::Key(Key::Char('H')) => DiffAction::ExpandFileTreeFolder,
858            Event::Key(Key::Char('L')) => DiffAction::CollapseFileTreeFolder,
859            Event::Key(Key::Char(' ') | Key::PageDown) => DiffAction::Scroll(Scroll::Pages(1)),
860            Event::Key(Key::PageUp) => DiffAction::Scroll(Scroll::Pages(-1)),
861            Event::Key(Key::Ctrl('d')) => {
862                DiffAction::Scroll(Scroll::Lines((area.rows / 2).max(1) as isize))
863            }
864            Event::Key(Key::Ctrl('u')) => {
865                DiffAction::Scroll(Scroll::Lines(-((area.rows / 2).max(1) as isize)))
866            }
867            Event::Key(Key::Char('g') | Key::Home) => DiffAction::Scroll(Scroll::Top),
868            Event::Key(Key::Char('G') | Key::End) => DiffAction::Scroll(Scroll::Bottom),
869            Event::Key(Key::Char('n')) => DiffAction::FocusNext,
870            Event::Key(Key::Char('p')) => DiffAction::FocusPrevious,
871            Event::Key(Key::Enter) => DiffAction::ToggleFocusedFile,
872            _ => return Control::Continue,
873        };
874        match self.apply(action, area) {
875            ViewChange::Changed => Control::Redraw,
876            ViewChange::Unchanged => Control::Continue,
877        }
878    }
879
880    /// Returns highlight requests for visible source rows plus configured lookahead.
881    pub fn highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
882        let diff = self.layout(area).diff;
883        let take = diff.rows.saturating_add(self.options.highlight_lookahead);
884        let view = View::new(
885            self.state.scroll,
886            self.render_rows_for(self.state.scroll, diff.rows),
887            diff.rows,
888        );
889        let start = view
890            .offset
891            .saturating_add(self.sticky_row_count(view.offset, diff.rows));
892        let mut requests = Vec::new();
893
894        for row in start..start.saturating_add(take) {
895            let Some(meta) = self.diff_meta_at(row) else {
896                continue;
897            };
898            let key = self.key_for(&meta);
899            if self.highlights.contains_key(&key) || self.pending_highlights.contains(&key) {
900                continue;
901            }
902            self.pending_highlights.insert(key.clone());
903            let source = self.highlight_source_for(&meta);
904            requests.push(HighlightRequest {
905                key,
906                hunk: meta.hunk,
907                row: meta.row,
908                path: meta.path,
909                source,
910            });
911        }
912        requests
913    }
914
915    /// Marks unprocessed highlight requests as requestable again.
916    pub fn cancel_highlights(&mut self, requests: impl IntoIterator<Item = HighlightRequest>) {
917        for request in requests {
918            self.pending_highlights.remove(&request.key);
919        }
920    }
921
922    /// Returns the highlight-cache key for one diff row.
923    fn key_for(&self, meta: &DiffLineMeta) -> HighlightKey {
924        HighlightKey::new(HighlightKeyInput {
925            file: meta.file,
926            side: meta.side,
927            source_line: meta.source_line,
928            text: &meta.text,
929            syntax: self.options.syntax.as_deref(),
930            theme: &self.options.theme,
931        })
932    }
933
934    /// Returns hunk-side source context for a highlighted row.
935    ///
936    /// Hunk sources are cached on the viewer so scrolling through a hunk does
937    /// not rebuild its source text on every highlight-request batch.
938    fn highlight_source_for(&mut self, meta: &DiffLineMeta) -> HighlightSource {
939        if meta.kind == DiffLineKind::NoNewline {
940            return meta.single_row_source();
941        }
942        let key = (meta.file, meta.hunk, meta.side);
943        if let Some(source) = self.hunk_highlight_sources.get(&key) {
944            return source.clone();
945        }
946        let source = self.build_highlight_source(meta);
947        self.hunk_highlight_sources.insert(key, source.clone());
948        source
949    }
950
951    /// Builds source text for one hunk side.
952    fn build_highlight_source(&self, meta: &DiffLineMeta) -> HighlightSource {
953        let Some(file) = self.document.files.get(*meta.file) else {
954            return meta.single_row_source();
955        };
956        let Some(hunk) = file.hunks.iter().find(|hunk| hunk.id == meta.hunk) else {
957            return meta.single_row_source();
958        };
959        hunk.highlight_source(meta.side)
960    }
961
962    /// Merges highlighted rows and returns whether a redraw is needed.
963    ///
964    /// The word-diff overlay is applied here, once, so the cached `Line` is
965    /// ready to render with no per-frame merge work. All paths that write to the
966    /// cached highlighted rows keep this invariant: cached lines are render-ready
967    /// and already overlaid.
968    pub fn apply_highlights(&mut self, results: impl IntoIterator<Item = HighlightResult>) -> bool {
969        let mut changed = false;
970        for result in results {
971            self.pending_highlights.remove(&result.key);
972
973            if let Entry::Vacant(slot) = self.word_diffs.entry(result.hunk)
974                && let Some(hunk) = self
975                    .document
976                    .files
977                    .iter()
978                    .find(|f| f.id == result.key.file)
979                    .and_then(|f| f.hunks.iter().find(|h| h.id == result.hunk))
980            {
981                slot.insert(crate::word::compute(hunk));
982            }
983            let bg = match result.key.side {
984                DiffSide::New => self.options.diff_palette.positive_word_bg,
985                DiffSide::Old => self.options.diff_palette.negative_word_bg,
986            };
987            let line = if let Some(ranges) = self
988                .word_diffs
989                .get(&result.hunk)
990                .and_then(|changes| changes.get(&result.row))
991            {
992                result.line.overlay_ranges(ranges, Style::default().bg(bg))
993            } else {
994                result.line
995            };
996            self.highlights.insert(result.key, line);
997            changed = true;
998        }
999        changed
1000    }
1001
1002    /// Highlights currently visible source rows through `highlighter`.
1003    ///
1004    /// Event-loop owners can still use [`Self::highlight_requests`] and
1005    /// [`Self::apply_highlights`] directly when highlight work runs
1006    /// asynchronously.
1007    pub fn apply_visible_highlights<H>(&mut self, area: Rect, highlighter: &mut H) -> bool
1008    where
1009        H: DiffHighlighter + ?Sized,
1010    {
1011        let requests = self.highlight_requests(area);
1012        if requests.is_empty() {
1013            return false;
1014        }
1015        self.apply_highlights(highlighter.highlight_batch(requests))
1016    }
1017
1018    /// Returns the row count for one file card.
1019    fn file_rows(&self, file: &FileDiff) -> usize {
1020        file.rendered_rows(self.state.collapsed_files.contains(&file.id))
1021    }
1022
1023    /// Returns one rendered row by global row index.
1024    fn render_row(&self, row: usize, cols: usize) -> Option<RenderRow> {
1025        let cols = cols.max(MIN_RENDER_COLS);
1026        if let Some(line) = self.preamble.get(row) {
1027            return Some(RenderRow {
1028                line: line.clone(),
1029                diff: None,
1030            });
1031        }
1032        self.file_row_location(row)
1033            .map(|location| self.render_file_row(location, cols))
1034    }
1035
1036    /// Returns one rendered row inside a file card.
1037    fn render_file_row(&self, location: FileRowLocation<'_>, cols: usize) -> RenderRow {
1038        let file = location.file;
1039        let border = FILE_BORDER;
1040        let inner_cols = cols.saturating_sub(2);
1041        let child_cols = cols.saturating_sub(4);
1042        let collapsed = self.state.collapsed_files.contains(&file.id);
1043        let local = location.local;
1044        let bottom = location.end - location.start - 1;
1045        // Child rows are full-width content lines rendered inside a bordered card.
1046        let wrap_child = |mut line: Line| {
1047            Line::truncate(&mut line, child_cols, "…");
1048            Line::pad(&mut line, child_cols);
1049            Line::new(border.left(1)).extend(line).item(border.right(1))
1050        };
1051        // Dedicated hunk-gap marker row keeps spacing between non-adjacent hunks.
1052        let hunk_gap_line = Line::blank()
1053            .extend(Line::blank().padded(LINE_NUMBER_WIDTH))
1054            .extend(Line::blank().padded(LINE_NUMBER_WIDTH))
1055            .extend(Self::marker_cell(HUNK_GAP_MARKER_CELL, colors::rgb::DIM));
1056
1057        match local {
1058            FILE_TOP_ROW => {
1059                return RenderRow {
1060                    line: border.top(inner_cols),
1061                    diff: None,
1062                };
1063            }
1064            FILE_HEADER_ROW => {
1065                return RenderRow {
1066                    line: wrap_child(file.header_line(child_cols, self.options.diff_palette)),
1067                    diff: None,
1068                };
1069            }
1070            row if row == bottom => {
1071                return RenderRow {
1072                    line: border.bottom(inner_cols),
1073                    diff: None,
1074                };
1075            }
1076            _ if !file.has_body(collapsed) => {
1077                return RenderRow {
1078                    line: border.bottom(inner_cols),
1079                    diff: None,
1080                };
1081            }
1082            FILE_DIVIDER_ROW => {
1083                return RenderRow {
1084                    line: border.divider(inner_cols, DIVIDER),
1085                    diff: None,
1086                };
1087            }
1088            _ => {}
1089        }
1090        let mut body_rows = file.hunk_body_rows(collapsed).peekable();
1091        while let Some(&(hunk, body_start)) = body_rows.peek() {
1092            let body_end = body_start + hunk.lines.len();
1093            if local < body_start {
1094                return RenderRow {
1095                    line: wrap_child(hunk_gap_line),
1096                    diff: None,
1097                };
1098            }
1099            if local < body_end {
1100                let row = self.hunk_row_at(file, hunk, local - body_start, child_cols);
1101                return RenderRow {
1102                    line: wrap_child(row.line),
1103                    diff: row.diff,
1104                };
1105            }
1106            body_rows.next();
1107        }
1108        RenderRow {
1109            line: border.bottom(inner_cols),
1110            diff: None,
1111        }
1112    }
1113
1114    /// Returns source metadata for one rendered row without building UI lines.
1115    fn diff_meta_at(&self, row: usize) -> Option<DiffLineMeta> {
1116        let location = self.file_row_location(row)?;
1117        let collapsed = self.state.collapsed_files.contains(&location.file.id);
1118        for (hunk, body_start) in location.file.hunk_body_rows(collapsed) {
1119            let body_end = body_start + hunk.lines.len();
1120            if location.local < body_start {
1121                return None;
1122            }
1123            if location.local < body_end {
1124                return Some(self.hunk_meta_at(location.file, hunk, location.local - body_start));
1125            }
1126        }
1127        None
1128    }
1129
1130    /// Returns the file location for a global rendered row.
1131    fn file_row_location(&self, row: usize) -> Option<FileRowLocation<'_>> {
1132        let files = &self.index.files;
1133        // The file containing `row` is the last one starting at or before it.
1134        let index = files
1135            .partition_point(|indexed| indexed.start <= row)
1136            .checked_sub(1)?;
1137        let indexed = files[index];
1138        let end = files
1139            .get(index + 1)
1140            .map_or(self.index.rows, |next| next.start);
1141        if row >= end {
1142            return None;
1143        }
1144        let file = self.document.files.get(indexed.file_index)?;
1145
1146        Some(FileRowLocation {
1147            file,
1148            start: indexed.start,
1149            end,
1150            local: row - indexed.start,
1151        })
1152    }
1153
1154    /// Rebuilds cached row positions for the current document visibility state.
1155    fn rebuild_index(&mut self) {
1156        let mut rows = self.preamble.len();
1157        let mut files = Vec::new();
1158
1159        for (file_index, file) in self.document.files.iter().enumerate() {
1160            files.push(IndexedFileRows {
1161                file_index,
1162                start: rows,
1163            });
1164            rows += self.file_rows(file);
1165        }
1166        self.index = RowIndex { files, rows };
1167    }
1168
1169    /// Lays out the commit preamble for the given body width.
1170    fn preamble(commit: Option<&Commit>, cols: usize) -> Vec<Line> {
1171        let Some(commit) = commit else {
1172            return Vec::new();
1173        };
1174        // Normalize the message body first, then trim only outer empty lines.
1175        let message_lines = commit
1176            .message
1177            .split('\n')
1178            .map(|raw| {
1179                let trimmed = raw.trim_end();
1180                trimmed.strip_prefix("    ").unwrap_or(trimmed)
1181            })
1182            .collect::<Vec<_>>();
1183        let message = {
1184            let first_non_empty = message_lines.iter().position(|text| !text.is_empty());
1185            let last_non_empty = message_lines.iter().rposition(|text| !text.is_empty());
1186            if let (Some(start), Some(end)) = (first_non_empty, last_non_empty) {
1187                message_lines[start..=end]
1188                    .iter()
1189                    .enumerate()
1190                    .map(|(index, &text)| {
1191                        let line = if text.is_empty() {
1192                            Line::blank()
1193                        } else {
1194                            Line::new(text.to_owned())
1195                        };
1196                        if index == 0 {
1197                            line.style(Style::default().bold())
1198                        } else {
1199                            line
1200                        }
1201                    })
1202                    .collect()
1203            } else {
1204                Vec::new()
1205            }
1206        };
1207        let hash_width = commit.hash.as_str().width()
1208            + commit.decoration.as_deref().map_or(0, |d| 1 + d.width());
1209        let value_width = std::iter::once(hash_width)
1210            .chain(commit.headers.iter().map(|h| h.value.as_str().width()))
1211            .max()
1212            .unwrap_or_default();
1213        // Hash row is a two-part component (hash plus optional signature marker).
1214        let hash_line = Line::new(Label::new(commit.hash.as_str()).fg(colors::rgb::ORANGE));
1215        let hash_value = if let Some(decoration) = commit.decoration.as_deref() {
1216            HStack::default()
1217                .child(hash_line)
1218                .spacer()
1219                .child(Line::new(Label::new(decoration).fg(colors::rgb::DIM)))
1220                .to_line(Constraint::tight(value_width))
1221        } else {
1222            hash_line
1223        };
1224        // Commit header table is the base preamble chrome (commit id and metadata rows).
1225        let mut table = Table::<2, Line>::new(TableOptions {
1226            overflow: true,
1227            spacing: 2,
1228            ..TableOptions::default()
1229        });
1230        table.push([
1231            Line::new(Label::new("commit").fg(colors::rgb::DIM)),
1232            hash_value,
1233        ]);
1234        // One row per commit header key/value, with date kept dim for softer emphasis.
1235        for header in &commit.headers {
1236            let key = header.key.to_ascii_lowercase();
1237            let header_value = if header.key.eq_ignore_ascii_case("date") {
1238                Line::new(header.value.as_str()).style(Style::new(colors::rgb::DIM))
1239            } else {
1240                Line::new(header.value.as_str())
1241            };
1242            table.push([
1243                Line::new(Label::new(&key).fg(colors::rgb::DIM)),
1244                header_value,
1245            ]);
1246        }
1247        // Optional message section is rendered as stacked lines after a divider.
1248        let mut stack = VStack::default()
1249            .border(Some(tui::Border::new(colors::FAINT)))
1250            .padding(1)
1251            .child(table);
1252
1253        if !message.is_empty() {
1254            stack = stack.divider_cell(Cell::new(DIVIDER, Style::new(colors::FAINT)));
1255            for line in message {
1256                stack.push(line);
1257            }
1258        }
1259        stack.lines(Constraint::tight(cols))
1260    }
1261
1262    /// Returns sticky file-header rows for the current offset.
1263    fn sticky_rows(&self, scroll: usize, visible_rows: usize, cols: usize) -> Vec<Line> {
1264        // Build the fixed sticky header strip directly from current scroll context.
1265        self.sticky_header_rows(scroll, visible_rows)
1266            .map(|sticky| {
1267                (STICKY_HEADER_ROWS - sticky.rows..STICKY_HEADER_ROWS)
1268                    .map(|index| {
1269                        if index == STICKY_HEADER_ROWS - 1 {
1270                            FILE_BORDER.divider(cols.saturating_sub(2), STICKY_DIVIDER)
1271                        } else {
1272                            self.render_row(sticky.start + index, cols)
1273                                .map(|row| row.line)
1274                                .unwrap_or_default()
1275                        }
1276                    })
1277                    .collect()
1278            })
1279            .unwrap_or_default()
1280    }
1281
1282    /// Returns the number of sticky rows for the current offset.
1283    fn sticky_row_count(&self, scroll: usize, visible_rows: usize) -> usize {
1284        self.sticky_header_rows(scroll, visible_rows)
1285            .map_or(0, |sticky| sticky.rows)
1286    }
1287
1288    /// Returns the source row for the sticky header at the current offset.
1289    #[cfg(test)]
1290    fn sticky_start(&self, scroll: usize, visible_rows: usize) -> Option<usize> {
1291        self.sticky_header_rows(scroll, visible_rows)
1292            .map(|sticky| sticky.start)
1293    }
1294
1295    /// Returns the visible sticky header rows at the current offset.
1296    fn sticky_header_rows(&self, scroll: usize, visible_rows: usize) -> Option<StickyHeaderRows> {
1297        let scroll = scroll.min(
1298            self.render_rows_for(scroll, visible_rows)
1299                .saturating_sub(visible_rows),
1300        );
1301        if scroll == 0 {
1302            return None;
1303        }
1304        let location = self.file_row_location(scroll)?;
1305        if scroll <= location.start {
1306            return None;
1307        }
1308        let file_bottom = location.end.saturating_sub(location.start + 1);
1309        let rows = file_bottom
1310            .saturating_sub(location.local)
1311            .min(STICKY_HEADER_ROWS)
1312            .min(visible_rows);
1313        if rows == 0 {
1314            return None;
1315        }
1316        Some(StickyHeaderRows {
1317            start: location.start,
1318            rows,
1319        })
1320    }
1321
1322    /// Focuses a target relative to the current focus.
1323    fn focus(&mut self, visible_rows: usize, delta: isize, filter: FocusFilter) {
1324        let targets = self.focus_targets(filter);
1325        if targets.is_empty() {
1326            return;
1327        }
1328        let current = self
1329            .state
1330            .focus
1331            .and_then(|focus| targets.iter().position(|target| target.focus == focus));
1332        let next = match (current, delta.is_negative()) {
1333            (Some(index), true) => index.saturating_sub(1),
1334            (Some(index), false) => index.saturating_add(1).min(targets.len() - 1),
1335            (None, true) => targets.len() - 1,
1336            (None, false) => 0,
1337        };
1338        let Some(target) = targets.get(next) else {
1339            return;
1340        };
1341
1342        self.state.focus = Some(target.focus);
1343        if filter == FocusFilter::File {
1344            self.state.scroll =
1345                View::new(target.row, self.scroll_rows(visible_rows), visible_rows).offset;
1346            return;
1347        }
1348
1349        let mut viewport = Viewport::from_offset(self.state.scroll);
1350        let margin = visible_rows / 4;
1351        viewport.scroll_to_row(
1352            target.row,
1353            self.scroll_rows(visible_rows),
1354            visible_rows,
1355            Placement::Margin {
1356                before: margin.max(self.sticky_row_count(self.state.scroll, visible_rows)),
1357                after: margin,
1358            },
1359        );
1360        self.state.scroll = viewport.offset;
1361    }
1362
1363    /// Returns focusable targets in rendered row order.
1364    fn focus_targets(&self, filter: FocusFilter) -> Vec<FocusTarget> {
1365        let mut targets = Vec::new();
1366
1367        for indexed in &self.index.files {
1368            let Some(file) = self.document.files.get(indexed.file_index) else {
1369                continue;
1370            };
1371            let collapsed = self.state.collapsed_files.contains(&file.id);
1372            if filter == FocusFilter::File {
1373                targets.push(FocusTarget {
1374                    focus: DiffFocus::File(file.id),
1375                    row: indexed.start,
1376                });
1377            }
1378            if filter == FocusFilter::Hunk {
1379                for (hunk, local) in file.hunk_body_rows(collapsed) {
1380                    targets.push(FocusTarget {
1381                        focus: DiffFocus::Hunk(hunk.id),
1382                        row: indexed.start + local,
1383                    });
1384                }
1385            }
1386        }
1387        targets
1388    }
1389
1390    /// Toggles the file containing the current focus.
1391    fn toggle_focused_file(&mut self) {
1392        let Some(file) = self.focused_file() else {
1393            return;
1394        };
1395        if !self.state.collapsed_files.remove(&file) {
1396            self.state.collapsed_files.insert(file);
1397            self.state.focus = Some(DiffFocus::File(file));
1398        }
1399    }
1400
1401    /// Collapses the file containing the current focus.
1402    fn collapse_focused_file(&mut self) {
1403        let Some(file) = self.focused_file() else {
1404            return;
1405        };
1406        self.state.collapsed_files.insert(file);
1407        self.state.focus = Some(DiffFocus::File(file));
1408    }
1409
1410    /// Returns one rendered row inside a hunk.
1411    fn hunk_row_at(
1412        &self,
1413        file: &FileDiff,
1414        hunk: &crate::Hunk,
1415        line_index: usize,
1416        inner: usize,
1417    ) -> RenderRow {
1418        let source_cols = inner.saturating_sub(LINE_NUMBER_WIDTH * 2 + MARKER_WIDTH);
1419        let (old_line, new_line) = Self::hunk_line_numbers(hunk, line_index);
1420        let line = &hunk.lines[line_index];
1421        let meta = DiffLineMeta::new(file, hunk.id, line, old_line, new_line);
1422
1423        self.hunk_row(meta, line, old_line, source_cols)
1424    }
1425
1426    /// Returns source metadata for one rendered hunk body row.
1427    fn hunk_meta_at(&self, file: &FileDiff, hunk: &crate::Hunk, line_index: usize) -> DiffLineMeta {
1428        let (old_line, new_line) = Self::hunk_line_numbers(hunk, line_index);
1429        DiffLineMeta::new(file, hunk.id, &hunk.lines[line_index], old_line, new_line)
1430    }
1431
1432    /// Returns the old and new source numbers for one hunk body row.
1433    fn hunk_line_numbers(hunk: &crate::Hunk, line_index: usize) -> (u32, u32) {
1434        let mut old_line = hunk.header.old_line_no;
1435        let mut new_line = hunk.header.new_line_no;
1436        for line in &hunk.lines[..line_index] {
1437            old_line = old_line.saturating_add(line.kind.old_len());
1438            new_line = new_line.saturating_add(line.kind.new_len());
1439        }
1440        (old_line, new_line)
1441    }
1442
1443    /// Returns one rendered hunk row.
1444    fn hunk_row(
1445        &self,
1446        meta: DiffLineMeta,
1447        line: &DiffLine,
1448        old_line: u32,
1449        source_cols: usize,
1450    ) -> RenderRow {
1451        let (cells, source, row_style, source_style) = match line.kind {
1452            DiffLineKind::Addition => (
1453                [
1454                    Self::blank_number(self.options.diff_palette.positive_row_bg),
1455                    Self::number_cell(
1456                        meta.source_line,
1457                        LINE_NUMBER_FG,
1458                        self.options.diff_palette.positive_row_bg,
1459                    ),
1460                    Self::marker_cell(" + ", self.options.diff_palette.positive_fg),
1461                ],
1462                self.rendered_source(&meta, source_cols),
1463                Style::default().bg(self.options.diff_palette.positive_row_bg),
1464                Style::default().bg(self.options.diff_palette.positive_row_bg),
1465            ),
1466            DiffLineKind::Deletion => (
1467                [
1468                    Self::number_cell(
1469                        meta.source_line,
1470                        LINE_NUMBER_FG,
1471                        self.options.diff_palette.negative_row_bg,
1472                    ),
1473                    Self::blank_number(self.options.diff_palette.negative_row_bg),
1474                    Self::marker_cell(" - ", self.options.diff_palette.negative_fg),
1475                ],
1476                self.rendered_source(&meta, source_cols),
1477                Style::default().bg(self.options.diff_palette.negative_row_bg),
1478                Style::default()
1479                    .bg(self.options.diff_palette.negative_row_bg)
1480                    .dim(),
1481            ),
1482            DiffLineKind::Context => (
1483                [
1484                    Self::number_cell(old_line, LINE_NUMBER_FG, Color::Unset),
1485                    Self::number_cell(meta.source_line, LINE_NUMBER_FG, Color::Unset),
1486                    Self::marker_cell("   ", Color::Unset),
1487                ],
1488                self.rendered_source(&meta, source_cols),
1489                Style::default(),
1490                Style::default(),
1491            ),
1492            DiffLineKind::NoNewline => (
1493                [
1494                    Line::blank().padded(LINE_NUMBER_WIDTH),
1495                    Line::blank().padded(LINE_NUMBER_WIDTH),
1496                    Self::marker_cell("   ", Color::Unset),
1497                ],
1498                Line::new(NO_NEWLINE_MARKER).style(Style::default().fg(colors::rgb::DIM)),
1499                Style::default(),
1500                Style::default(),
1501            ),
1502        };
1503        let rendered = self.hunk_line(cells, source, source_cols, row_style, source_style);
1504
1505        RenderRow {
1506            line: rendered,
1507            diff: Some(meta),
1508        }
1509    }
1510
1511    /// Returns a fixed-column hunk row line.
1512    fn hunk_line(
1513        &self,
1514        cells: [Line; 3],
1515        mut source: Line,
1516        source_cols: usize,
1517        row_style: Style,
1518        source_style: Style,
1519    ) -> Line {
1520        let inner = source_cols.saturating_add(LINE_NUMBER_WIDTH * 2 + MARKER_WIDTH);
1521
1522        Line::truncate(&mut source, source_cols, "…");
1523        Line::pad(&mut source, source_cols);
1524
1525        let source = source.style(source_style);
1526        let mut line = Line::blank()
1527            .extend(cells[0].clone())
1528            .extend(cells[1].clone())
1529            .extend(cells[2].clone())
1530            .extend(source);
1531
1532        Line::pad(&mut line, inner);
1533        Line::truncate(&mut line, inner, "…");
1534        line.style(row_style)
1535    }
1536
1537    /// Returns the final source-text `Line` for a row, ready to render.
1538    ///
1539    /// Cached entries already include the word-diff overlay (applied once in
1540    /// [`Self::apply_highlights`]). On a cache miss -- the window before the
1541    /// highlight worker responds -- a plain Line is returned; the word-diff
1542    /// background lands once the cached overlaid line arrives.
1543    fn rendered_source(&self, meta: &DiffLineMeta, cols: usize) -> Line {
1544        self.highlights
1545            .get(&self.key_for(meta))
1546            .cloned()
1547            .unwrap_or_else(|| Line::new(Text::truncate(meta.text.as_str(), cols, "…")))
1548    }
1549
1550    /// Returns a line-number cell.
1551    fn number_cell(value: u32, foreground: Color, background: Color) -> Line {
1552        Line::new(Label::new(&value.to_string()).fg(foreground).bg(background))
1553            .padded(LINE_NUMBER_WIDTH)
1554    }
1555
1556    /// Returns a blank line-number cell.
1557    fn blank_number(background: Color) -> Line {
1558        Line::new(Label::space().bg(background)).padded(LINE_NUMBER_WIDTH)
1559    }
1560
1561    /// Returns a marker cell.
1562    fn marker_cell(marker: &str, foreground: Color) -> Line {
1563        Line::new(Label::new(marker).fg(foreground)).padded(MARKER_WIDTH)
1564    }
1565
1566    /// Returns the diff scrollbar style.
1567    fn scrollbar_style() -> ScrollbarStyle {
1568        ScrollbarStyle::new(
1569            Cell::new(SCROLLBAR_TRACK, Style::default().fg(colors::FAINT)),
1570            Cell::new(SCROLLBAR_THUMB, Style::default().fg(SCROLLBAR_THUMB_COLOR)),
1571        )
1572    }
1573}
1574
1575impl Widget for DiffViewer {
1576    fn size(&self, parent: Constraint) -> Size {
1577        let cols = if parent.max.cols == usize::MAX {
1578            MIN_RENDER_COLS
1579        } else {
1580            parent.max.cols
1581        };
1582        Size::new(cols, self.index.rows).constrain(parent)
1583    }
1584
1585    fn render(&mut self, area: Rect, buf: &mut Buffer) {
1586        DiffViewer::render(self, area, buf);
1587    }
1588
1589    fn to_buffer(&mut self, constraints: Constraint) -> Buffer {
1590        let size = self.size(constraints);
1591        let area = Rect::from_size(size);
1592        let mut buffer = Buffer::empty(area);
1593
1594        DiffViewer::render(self, area, &mut buffer);
1595
1596        buffer
1597    }
1598}
1599
1600/// Focus target with its rendered row.
1601#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1602struct FocusTarget {
1603    /// Focus value.
1604    focus: DiffFocus,
1605    /// Rendered row index.
1606    row: usize,
1607}
1608
1609/// Focus target filter.
1610#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1611enum FocusFilter {
1612    /// File targets only.
1613    File,
1614    /// Hunk targets only.
1615    Hunk,
1616}
1617
1618impl FileDiff {
1619    /// Returns whether this file card should render hunk rows.
1620    fn has_body(&self, collapsed: bool) -> bool {
1621        !collapsed && !self.hunks.is_empty()
1622    }
1623
1624    /// Returns the rendered row count for this file's card.
1625    fn rendered_rows(&self, collapsed: bool) -> usize {
1626        if !self.has_body(collapsed) {
1627            return EMPTY_CARD_ROWS;
1628        }
1629        let hunks = self.hunks.len();
1630        let body: usize = self.hunks.iter().map(|hunk| hunk.lines.len()).sum();
1631        // top + header + divider + body lines + gaps + bottom.
1632        HUNK_BODY_START + body + hunks.saturating_sub(1) + 1
1633    }
1634
1635    /// Returns each hunk together with the local row of its first body line.
1636    fn hunk_body_rows(&self, collapsed: bool) -> impl Iterator<Item = (&Hunk, usize)> + '_ {
1637        let has_body = self.has_body(collapsed);
1638        self.hunks
1639            .iter()
1640            .enumerate()
1641            .scan(HUNK_BODY_START, move |local, (index, hunk)| {
1642                if !has_body {
1643                    return None;
1644                }
1645                if index > 0 {
1646                    *local += 1;
1647                }
1648                let row = *local;
1649                *local += hunk.lines.len();
1650                Some((hunk, row))
1651            })
1652    }
1653
1654    /// Returns a file header line.
1655    fn header_line(&self, cols: usize, palette: DiffPalette) -> Line {
1656        let mut left = Line::blank();
1657        left.push(Label::from_char(self.header.kind.marker()).fg(LINE_NUMBER_FG));
1658        left.push(Label::space());
1659        left = left.extend(self.path_line());
1660
1661        if let Some(badge) = self.badge(palette) {
1662            left.push(Label::space());
1663            left.push(badge);
1664        }
1665        let mut header = HStack::default().child(left).spacer();
1666        let stats = self.stats();
1667
1668        if let Some(side) = Self::diffstat_line(stats.additions, stats.deletions, palette) {
1669            header = header.child(side);
1670        }
1671        header.to_line(Constraint::tight(cols))
1672    }
1673
1674    /// Returns the file path display line.
1675    fn path_line(&self) -> Line {
1676        match self.header.kind {
1677            FileKind::Renamed | FileKind::Copied => Line::spaced([
1678                Label::from(Self::display_path(self.header.old_path.as_ref())),
1679                Label::from(RENAME_ARROW),
1680                Label::from(Self::display_path(self.header.new_path.as_ref())),
1681            ]),
1682            _ => Line::new(Self::display_path(self.header.display_path())),
1683        }
1684    }
1685
1686    /// Returns an additions-first diffstat line.
1687    fn diffstat_line(additions: usize, deletions: usize, palette: DiffPalette) -> Option<Line> {
1688        if additions == 0 && deletions == 0 {
1689            return None;
1690        }
1691        let mut line = Line::blank();
1692        if additions > 0 {
1693            line.push(Label::new(&format!("+{additions}")).fg(palette.positive_fg));
1694        }
1695        if deletions > 0 {
1696            if additions > 0 {
1697                line.push(Label::space());
1698            }
1699            line.push(Label::new(&format!("-{deletions}")).fg(palette.negative_fg));
1700        }
1701        Some(line)
1702    }
1703
1704    /// Returns a file-kind badge.
1705    fn badge(&self, palette: DiffPalette) -> Option<Label> {
1706        match self.header.kind {
1707            FileKind::Added => Some(Self::change_badge(
1708                "created",
1709                palette.positive_fg,
1710                palette.positive_row_bg,
1711            )),
1712            FileKind::Deleted => Some(Self::change_badge(
1713                "deleted",
1714                palette.negative_fg,
1715                palette.negative_row_bg,
1716            )),
1717            FileKind::Renamed => Some(Self::change_badge(
1718                "moved",
1719                FILE_KIND_BADGE_FG,
1720                FILE_KIND_BADGE_BG,
1721            )),
1722            FileKind::Copied => Some(Self::change_badge(
1723                "copied",
1724                FILE_KIND_BADGE_FG,
1725                FILE_KIND_BADGE_BG,
1726            )),
1727            FileKind::ModeChanged => Some(Self::change_badge(
1728                "mode changed",
1729                FILE_KIND_BADGE_FG,
1730                FILE_KIND_BADGE_BG,
1731            )),
1732            FileKind::Binary => Some(Self::change_badge(
1733                "binary",
1734                Color::Yellow,
1735                Color::Fixed(236),
1736            )),
1737            FileKind::Modified => None,
1738        }
1739    }
1740
1741    /// Returns a small colored badge.
1742    fn change_badge(text: &str, foreground: Color, background: Color) -> Label {
1743        Label::new(&format!(" {text} "))
1744            .fg(foreground)
1745            .bg(background)
1746    }
1747
1748    /// Returns a display path or placeholder.
1749    fn display_path(path: Option<&PathBuf>) -> String {
1750        path.map_or_else(|| "<unknown>".to_owned(), |path| path.display().to_string())
1751    }
1752}
1753
1754impl DiffLineMeta {
1755    /// Creates metadata for a source row.
1756    fn new(file: &FileDiff, hunk: HunkId, line: &DiffLine, old_line: u32, new_line: u32) -> Self {
1757        let side = match line.kind {
1758            DiffLineKind::Deletion => DiffSide::Old,
1759            _ => DiffSide::New,
1760        };
1761        let source_line = match side {
1762            DiffSide::Old => old_line,
1763            DiffSide::New => new_line,
1764        };
1765        Self {
1766            file: file.id,
1767            hunk,
1768            row: line.id,
1769            kind: line.kind,
1770            side,
1771            source_line,
1772            text: line.text.clone(),
1773            path: file.source_path(side),
1774        }
1775    }
1776
1777    /// Builds a single-row highlight source from this line's own text.
1778    fn single_row_source(&self) -> HighlightSource {
1779        HighlightSource::new(self.text.clone(), self.source_line)
1780    }
1781}
1782
1783#[cfg(test)]
1784#[allow(clippy::unwrap_used)]
1785mod tests {
1786    use std::path::PathBuf;
1787    use std::str::FromStr;
1788
1789    use super::*;
1790
1791    use crate::Decode;
1792    use crate::DiffDocument;
1793    use rustik_repo::{Repo, RepoError};
1794    use rustik_tui::{Modifiers, Point};
1795
1796    /// Returns a left-click event for tests.
1797    fn left_click(x: usize, y: usize, modifiers: Modifiers) -> Event<()> {
1798        Event::Mouse(Mouse::Press {
1799            button: MouseButton::Left,
1800            at: Point::new(x, y),
1801            modifiers,
1802        })
1803    }
1804
1805    fn sample_viewer() -> DiffViewer {
1806        let document = DiffDocument::decode_str(
1807            "\
1808diff --git a/a.rs b/a.rs
1809index 1111111..2222222 100644
1810--- a/a.rs
1811+++ b/a.rs
1812@@ -1,3 +1,4 @@ fn main
1813 context
1814-old
1815+new
1816+extra
1817 tail
1818",
1819        )
1820        .unwrap();
1821
1822        DiffViewer::new(document, DiffOptions::default())
1823    }
1824
1825    #[derive(Default)]
1826    struct RecordingHighlighter {
1827        batches: usize,
1828    }
1829
1830    impl DiffHighlighter for RecordingHighlighter {
1831        fn highlight_batch(&mut self, requests: Vec<HighlightRequest>) -> Vec<HighlightResult> {
1832            self.batches += 1;
1833            requests
1834                .into_iter()
1835                .map(|request| HighlightResult::new(request, Line::new("highlighted")))
1836                .collect()
1837        }
1838    }
1839
1840    fn two_file_viewer() -> DiffViewer {
1841        let document = DiffDocument::decode_str(
1842            "\
1843diff --git a/a.rs b/a.rs
1844index 1111111..2222222 100644
1845--- a/a.rs
1846+++ b/a.rs
1847@@ -1,3 +1,4 @@ fn a
1848 context
1849-old
1850+new
1851+extra
1852 tail
1853diff --git a/b.rs b/b.rs
1854index 3333333..4444444 100644
1855--- a/b.rs
1856+++ b/b.rs
1857@@ -1,2 +1,2 @@ fn b
1858 keep
1859-before
1860+after
1861",
1862        )
1863        .unwrap();
1864
1865        DiffViewer::new(document, DiffOptions::default())
1866    }
1867
1868    fn two_hunk_viewer() -> DiffViewer {
1869        let document = DiffDocument::decode_str(
1870            "\
1871diff --git a/a.rs b/a.rs
1872index 1111111..2222222 100644
1873--- a/a.rs
1874+++ b/a.rs
1875@@ -1,2 +1,2 @@ fn first
1876 keep
1877-old
1878+new
1879@@ -10,2 +10,2 @@ fn second
1880 keep
1881-before
1882+after
1883",
1884        )
1885        .unwrap();
1886
1887        DiffViewer::new(document, DiffOptions::default())
1888    }
1889
1890    fn scroll_viewer() -> DiffViewer {
1891        let document = DiffDocument::decode_str(
1892            "\
1893diff --git a/a.rs b/a.rs
1894index 1111111..2222222 100644
1895--- a/a.rs
1896+++ b/a.rs
1897@@ -1,20 +1,20 @@ fn main
1898 line 01
1899 line 02
1900 line 03
1901 line 04
1902 line 05
1903 line 06
1904 line 07
1905 line 08
1906 line 09
1907 line 10
1908 line 11
1909 line 12
1910 line 13
1911 line 14
1912 line 15
1913 line 16
1914 line 17
1915 line 18
1916 line 19
1917 line 20
1918",
1919        )
1920        .unwrap();
1921
1922        DiffViewer::new(document, DiffOptions::default())
1923    }
1924
1925    fn tree_viewer() -> DiffViewer {
1926        let document = DiffDocument::decode_str(
1927            "\
1928diff --git a/a.rs b/a.rs
1929index 1111111..2222222 100644
1930--- a/a.rs
1931+++ b/a.rs
1932@@ -1 +1 @@
1933-old
1934+new
1935diff --git a/b.rs b/b.rs
1936index 3333333..4444444 100644
1937--- a/b.rs
1938+++ b/b.rs
1939@@ -1 +1 @@
1940-before
1941+after
1942",
1943        )
1944        .unwrap();
1945
1946        DiffViewer::new(
1947            document,
1948            DiffOptions {
1949                file_tree: FileTreeMode::Auto,
1950                file_tree_root: "rustik".to_owned(),
1951                ..DiffOptions::default()
1952            },
1953        )
1954    }
1955
1956    fn nested_tree_viewer() -> DiffViewer {
1957        let document = DiffDocument::decode_str(
1958            "\
1959diff --git a/src/a.rs b/src/a.rs
1960index 1111111..2222222 100644
1961--- a/src/a.rs
1962+++ b/src/a.rs
1963@@ -1 +1 @@
1964-old
1965+new
1966diff --git a/src/b.rs b/src/b.rs
1967index 3333333..4444444 100644
1968--- a/src/b.rs
1969+++ b/src/b.rs
1970@@ -1 +1 @@
1971-before
1972+after
1973diff --git a/README.md b/README.md
1974index 5555555..6666666 100644
1975--- a/README.md
1976+++ b/README.md
1977@@ -1 +1 @@
1978-old readme
1979+new readme
1980",
1981        )
1982        .unwrap();
1983
1984        DiffViewer::new(
1985            document,
1986            DiffOptions {
1987                file_tree: FileTreeMode::Auto,
1988                file_tree_root: "rustik".to_owned(),
1989                ..DiffOptions::default()
1990            },
1991        )
1992    }
1993
1994    fn deep_tree_viewer() -> DiffViewer {
1995        let document = DiffDocument::decode_str(
1996            "\
1997diff --git a/src/app/a.rs b/src/app/a.rs
1998index 1111111..2222222 100644
1999--- a/src/app/a.rs
2000+++ b/src/app/a.rs
2001@@ -1 +1 @@
2002-old
2003+new
2004diff --git a/src/lib/b.rs b/src/lib/b.rs
2005index 3333333..4444444 100644
2006--- a/src/lib/b.rs
2007+++ b/src/lib/b.rs
2008@@ -1 +1 @@
2009-before
2010+after
2011diff --git a/README.md b/README.md
2012index 5555555..6666666 100644
2013--- a/README.md
2014+++ b/README.md
2015@@ -1 +1 @@
2016-old readme
2017+new readme
2018",
2019        )
2020        .unwrap();
2021
2022        DiffViewer::new(
2023            document,
2024            DiffOptions {
2025                file_tree: FileTreeMode::Auto,
2026                file_tree_root: "rustik".to_owned(),
2027                ..DiffOptions::default()
2028            },
2029        )
2030    }
2031
2032    #[test]
2033    fn collapsing_focused_file_hides_hunk_rows() {
2034        let mut viewer = sample_viewer();
2035        let area = Rect::new(0, 0, 64, 6);
2036
2037        viewer.apply(DiffAction::FocusNext, area);
2038        assert_eq!(
2039            viewer.apply(DiffAction::ToggleFocusedFile, area),
2040            ViewChange::Changed
2041        );
2042        assert!(viewer.state().collapsed_files.contains(&FileId::new(0)));
2043    }
2044
2045    #[test]
2046    fn hunk_focus_does_not_change_rendered_row_count() {
2047        let viewer = sample_viewer();
2048        let mut focused = sample_viewer();
2049
2050        focused.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
2051
2052        assert_eq!(focused.index.rows, viewer.index.rows);
2053    }
2054
2055    #[test]
2056    fn multi_hunk_file_counts_gap_row() {
2057        let viewer = two_hunk_viewer();
2058
2059        assert_eq!(viewer.index.rows, 11);
2060    }
2061
2062    #[test]
2063    fn collapsed_file_clamps_scroll() {
2064        let mut viewer = sample_viewer();
2065        let area = Rect::new(0, 0, 64, 6);
2066
2067        viewer.apply(DiffAction::Scroll(Scroll::Bottom), area);
2068        viewer.apply(DiffAction::FocusNext, area);
2069        assert_eq!(
2070            viewer.apply(DiffAction::ToggleFocusedFile, area),
2071            ViewChange::Changed
2072        );
2073
2074        assert_eq!(viewer.state().scroll, 0);
2075    }
2076
2077    #[test]
2078    fn focus_next_and_previous_visit_files_only() {
2079        let mut viewer = two_file_viewer();
2080        let area = Rect::new(0, 0, 64, 6);
2081
2082        viewer.apply(DiffAction::FocusNext, area);
2083        assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(0))));
2084        viewer.apply(DiffAction::FocusNext, area);
2085        assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(1))));
2086        viewer.apply(DiffAction::FocusPrevious, area);
2087        assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(0))));
2088    }
2089
2090    #[test]
2091    fn file_navigation_anchors_file_to_viewport_top() {
2092        let mut viewer = two_file_viewer();
2093        let area = Rect::new(0, 0, 64, 6);
2094
2095        viewer.apply(DiffAction::FocusNext, area);
2096        assert_eq!(viewer.state().scroll, 0);
2097        viewer.apply(DiffAction::FocusNext, area);
2098
2099        assert_eq!(viewer.state().scroll, 9);
2100    }
2101
2102    #[test]
2103    fn next_hunk_visits_hunks_only() {
2104        let mut viewer = two_file_viewer();
2105        let area = Rect::new(0, 0, 64, 6);
2106
2107        viewer.apply(DiffAction::NextHunk, area);
2108        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
2109        viewer.apply(DiffAction::NextHunk, area);
2110        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
2111    }
2112
2113    #[test]
2114    fn scroll_clamps_after_resize() {
2115        let mut viewer = sample_viewer();
2116        let small = Rect::new(0, 0, 64, 3);
2117        let large = Rect::new(0, 0, 64, 30);
2118
2119        viewer.apply(DiffAction::Scroll(Scroll::Bottom), small);
2120        assert!(viewer.state().scroll > 0);
2121        viewer.apply(DiffAction::Resize, large);
2122
2123        assert_eq!(viewer.state().scroll, 0);
2124    }
2125
2126    #[test]
2127    fn sticky_header_renders_when_scrolled_inside_file() {
2128        let mut viewer = sample_viewer();
2129        let area = Rect::new(0, 0, 64, 5);
2130
2131        viewer.apply(DiffAction::Scroll(Scroll::Lines(4)), area);
2132
2133        assert_eq!(viewer.sticky_row_count(viewer.state().scroll, area.rows), 3);
2134    }
2135
2136    #[test]
2137    fn sticky_header_starts_before_header_scrolls_off() {
2138        let mut viewer = sample_viewer();
2139        let area = Rect::new(0, 0, 64, 5);
2140
2141        viewer.apply(DiffAction::Scroll(Scroll::Lines(1)), area);
2142
2143        assert_eq!(
2144            viewer.sticky_start(viewer.state().scroll, area.rows),
2145            Some(0)
2146        );
2147    }
2148
2149    #[test]
2150    fn sticky_header_replaces_scrolled_file_chrome() {
2151        let mut viewer = sample_viewer();
2152        let area = Rect::new(0, 0, 64, 5);
2153
2154        viewer.apply(DiffAction::Scroll(Scroll::Lines(3)), area);
2155
2156        assert_eq!(
2157            viewer.sticky_start(viewer.state().scroll, area.rows),
2158            Some(0)
2159        );
2160    }
2161
2162    #[test]
2163    fn sticky_header_cuts_before_next_file_card() {
2164        let mut viewer = two_file_viewer();
2165        let area = Rect::new(0, 0, 64, 5);
2166
2167        viewer.apply(DiffAction::Scroll(Scroll::Lines(8)), area);
2168
2169        assert_eq!(viewer.sticky_start(viewer.state().scroll, area.rows), None);
2170    }
2171
2172    #[test]
2173    fn sticky_header_stays_visible_until_next_file_reaches_body() {
2174        let mut viewer = two_file_viewer();
2175        let area = Rect::new(0, 0, 64, 5);
2176
2177        viewer.apply(DiffAction::Scroll(Scroll::Lines(5)), area);
2178
2179        assert_eq!(
2180            viewer.sticky_start(viewer.state().scroll, area.rows),
2181            Some(0)
2182        );
2183    }
2184
2185    #[test]
2186    fn sticky_header_stays_visible_at_file_end_boundary() {
2187        let mut viewer = two_file_viewer();
2188        let area = Rect::new(0, 0, 64, 5);
2189
2190        viewer.apply(DiffAction::Scroll(Scroll::Lines(6)), area);
2191
2192        assert_eq!(
2193            viewer.sticky_start(viewer.state().scroll, area.rows),
2194            Some(0)
2195        );
2196        assert_eq!(viewer.sticky_row_count(viewer.state().scroll, area.rows), 2);
2197    }
2198
2199    #[test]
2200    fn sticky_header_stays_visible_at_file_bottom() {
2201        let mut viewer = sample_viewer();
2202        let area = Rect::new(0, 0, 64, 5);
2203
2204        viewer.apply(DiffAction::Scroll(Scroll::Bottom), area);
2205
2206        assert_eq!(
2207            viewer.sticky_start(viewer.state().scroll, area.rows),
2208            Some(0)
2209        );
2210    }
2211
2212    #[test]
2213    fn hunk_navigation_scrolls_focus_out_of_viewport_edge() {
2214        let mut viewer = two_file_viewer();
2215        let area = Rect::new(0, 0, 64, 5);
2216
2217        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
2218        viewer.set_scroll(6);
2219        viewer.apply(DiffAction::NextHunk, area);
2220
2221        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
2222        assert_eq!(viewer.state().scroll, 9);
2223    }
2224
2225    #[test]
2226    fn keyboard_line_scroll_inputs_move_one_row() {
2227        let area = Rect::new(0, 0, 80, 9);
2228        let mut viewer = scroll_viewer();
2229
2230        assert_eq!(
2231            viewer.handle_input(Event::Key(Key::Char('j')), area),
2232            Control::Redraw
2233        );
2234        assert_eq!(viewer.state().scroll, 1);
2235        assert_eq!(
2236            viewer.handle_input(Event::Key(Key::Char('j')), area),
2237            Control::Redraw
2238        );
2239        assert_eq!(viewer.state().scroll, 2);
2240        assert_eq!(
2241            viewer.handle_input(Event::Key(Key::Down), area),
2242            Control::Redraw
2243        );
2244        assert_eq!(viewer.state().scroll, 3);
2245        assert_eq!(
2246            viewer.handle_input(Event::Key(Key::Char('k')), area),
2247            Control::Redraw
2248        );
2249        assert_eq!(viewer.state().scroll, 2);
2250        assert_eq!(
2251            viewer.handle_input(Event::Key(Key::Up), area),
2252            Control::Redraw
2253        );
2254        assert_eq!(viewer.state().scroll, 1);
2255    }
2256
2257    #[test]
2258    fn boundary_scroll_inputs_do_not_redraw() {
2259        let area = Rect::new(0, 0, 80, 9);
2260        let mut viewer = scroll_viewer();
2261
2262        assert_eq!(
2263            viewer.handle_input(Event::Key(Key::Char('k')), area),
2264            Control::Continue
2265        );
2266        assert_eq!(viewer.state().scroll, 0);
2267
2268        viewer.apply(DiffAction::Scroll(Scroll::Bottom), area);
2269        let bottom = viewer.state().scroll;
2270
2271        assert_eq!(
2272            viewer.handle_input(Event::Key(Key::Char('j')), area),
2273            Control::Continue
2274        );
2275        assert_eq!(viewer.state().scroll, bottom);
2276    }
2277
2278    #[test]
2279    fn escape_quits_when_no_file_is_focused() {
2280        let area = Rect::new(0, 0, 100, 9);
2281        let mut viewer = tree_viewer();
2282
2283        assert_eq!(
2284            viewer.handle_input(Event::Key(Key::Esc), area),
2285            Control::Quit
2286        );
2287        assert_eq!(viewer.file_tree.target(), None);
2288    }
2289
2290    #[test]
2291    fn plain_h_and_l_are_unmapped() {
2292        let area = Rect::new(0, 0, 100, 9);
2293        let mut viewer = tree_viewer();
2294
2295        assert_eq!(
2296            viewer.handle_input(Event::Key(Key::Char('h')), area),
2297            Control::Continue
2298        );
2299        assert_eq!(
2300            viewer.handle_input(Event::Key(Key::Char('l')), area),
2301            Control::Continue
2302        );
2303        assert_eq!(viewer.file_tree.target(), None);
2304    }
2305
2306    #[test]
2307    fn shift_j_moves_file_tree_cursor_and_jumps_to_file() {
2308        let area = Rect::new(0, 0, 100, 4);
2309        let mut viewer = tree_viewer();
2310
2311        assert_eq!(
2312            viewer.handle_input(Event::Key(Key::Char('J')), area),
2313            Control::Redraw
2314        );
2315
2316        assert_eq!(
2317            viewer.file_tree.target(),
2318            Some(FileTreeTarget::File(FileId::new(1)))
2319        );
2320        assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(1))));
2321        assert_eq!(viewer.state().scroll, 6);
2322    }
2323
2324    #[test]
2325    fn shift_k_moves_file_tree_cursor_to_folder_first_file() {
2326        let area = Rect::new(0, 0, 100, 9);
2327        let mut viewer = nested_tree_viewer();
2328
2329        assert_eq!(
2330            viewer.handle_input(Event::Key(Key::Char('K')), area),
2331            Control::Redraw
2332        );
2333
2334        assert_eq!(
2335            viewer.file_tree.target(),
2336            Some(FileTreeTarget::Directory(PathBuf::from("src")))
2337        );
2338        assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(0))));
2339        assert_eq!(viewer.state().scroll, 0);
2340    }
2341
2342    #[test]
2343    fn j_scrolls_after_file_tree_mouse_selection() {
2344        let area = Rect::new(0, 0, 100, 4);
2345        let mut viewer = tree_viewer();
2346
2347        viewer.handle_input(left_click(2, 3, Modifiers::NONE), area);
2348        assert_eq!(viewer.state().scroll, 6);
2349        assert_eq!(
2350            viewer.handle_input(Event::Key(Key::Char('j')), area),
2351            Control::Redraw
2352        );
2353
2354        assert_eq!(
2355            viewer.file_tree.target(),
2356            Some(FileTreeTarget::File(FileId::new(1)))
2357        );
2358        assert_eq!(viewer.state().scroll, 7);
2359    }
2360
2361    #[test]
2362    fn mouse_wheel_scroll_updates_file_tree_cursor() {
2363        let area = Rect::new(0, 0, 100, 4);
2364        let mut viewer = tree_viewer();
2365        let down = Event::Mouse(Mouse::Press {
2366            button: MouseButton::WheelDown,
2367            at: Point::new(50, 1),
2368            modifiers: Modifiers::NONE,
2369        });
2370
2371        viewer.handle_input(down.clone(), area);
2372        viewer.handle_input(down, area);
2373
2374        assert_eq!(
2375            viewer.file_tree.target(),
2376            Some(FileTreeTarget::File(FileId::new(1)))
2377        );
2378        assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(1))));
2379    }
2380
2381    #[test]
2382    fn left_click_on_file_tree_file_keeps_all_files_visible() {
2383        let area = Rect::new(0, 0, 100, 9);
2384        let mut viewer = tree_viewer();
2385        let rows = viewer.index.rows;
2386
2387        assert_eq!(
2388            viewer.handle_input(left_click(2, 3, Modifiers::NONE), area),
2389            Control::Redraw
2390        );
2391
2392        assert_eq!(viewer.index.rows, rows);
2393        assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(1))));
2394    }
2395
2396    #[test]
2397    fn file_navigation_updates_file_tree_cursor() {
2398        let area = Rect::new(0, 0, 100, 4);
2399        let mut viewer = tree_viewer();
2400
2401        viewer.handle_input(Event::Key(Key::Char('n')), area);
2402
2403        assert_eq!(
2404            viewer.file_tree.target(),
2405            Some(FileTreeTarget::File(FileId::new(0)))
2406        );
2407    }
2408
2409    #[test]
2410    fn backtick_toggles_file_tree_visibility() {
2411        let area = Rect::new(0, 0, 100, 9);
2412        let mut viewer = tree_viewer();
2413
2414        assert!(viewer.layout(area).tree.is_some());
2415        assert_eq!(
2416            viewer.handle_input(Event::Key(Key::Char('`')), area),
2417            Control::Redraw
2418        );
2419        assert!(viewer.layout(area).tree.is_none());
2420        assert_eq!(
2421            viewer.handle_input(Event::Key(Key::Char('`')), area),
2422            Control::Redraw
2423        );
2424        assert!(viewer.layout(area).tree.is_some());
2425    }
2426
2427    #[test]
2428    fn file_tree_resyncs_when_shown_after_hidden_scroll() {
2429        let area = Rect::new(0, 0, 100, 4);
2430        let mut viewer = tree_viewer();
2431
2432        viewer.handle_input(Event::Key(Key::Char('`')), area);
2433        viewer.apply(DiffAction::Scroll(Scroll::Lines(6)), area);
2434        assert_eq!(viewer.file_tree.target(), None);
2435
2436        assert_eq!(
2437            viewer.handle_input(Event::Key(Key::Char('`')), area),
2438            Control::Redraw
2439        );
2440
2441        assert_eq!(
2442            viewer.file_tree.target(),
2443            Some(FileTreeTarget::File(FileId::new(1)))
2444        );
2445    }
2446
2447    #[test]
2448    fn escape_keeps_quit_behavior_when_tree_is_hidden() {
2449        let area = Rect::new(0, 0, 80, 9);
2450        let mut viewer = tree_viewer();
2451
2452        assert_eq!(
2453            viewer.handle_input(Event::Key(Key::Esc), area),
2454            Control::Quit
2455        );
2456    }
2457
2458    #[test]
2459    fn enter_toggles_focused_file_instead_of_file_tree_cursor() {
2460        let area = Rect::new(0, 0, 100, 9);
2461        let mut viewer = tree_viewer();
2462
2463        viewer.handle_input(Event::Key(Key::Char('J')), area);
2464        assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(1))));
2465        assert!(!viewer.state().collapsed_files.contains(&FileId::new(1)));
2466
2467        assert_eq!(
2468            viewer.handle_input(Event::Key(Key::Enter), area),
2469            Control::Redraw
2470        );
2471        assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(1))));
2472        assert!(viewer.state().collapsed_files.contains(&FileId::new(1)));
2473    }
2474
2475    #[test]
2476    fn shift_l_and_shift_h_collapse_and_expand_file_tree_folders() {
2477        let area = Rect::new(0, 0, 100, 9);
2478        let mut viewer = nested_tree_viewer();
2479
2480        viewer.handle_input(Event::Key(Key::Char('K')), area);
2481        assert_eq!(
2482            viewer.file_tree.target(),
2483            Some(FileTreeTarget::Directory(PathBuf::from("src")))
2484        );
2485
2486        viewer.handle_input(Event::Key(Key::Char('L')), area);
2487        viewer.handle_input(Event::Key(Key::Char('J')), area);
2488        assert_eq!(
2489            viewer.file_tree.target(),
2490            Some(FileTreeTarget::File(FileId::new(2)))
2491        );
2492
2493        viewer.handle_input(Event::Key(Key::Char('K')), area);
2494        viewer.handle_input(Event::Key(Key::Char('H')), area);
2495        viewer.handle_input(Event::Key(Key::Char('J')), area);
2496        assert_eq!(
2497            viewer.file_tree.target(),
2498            Some(FileTreeTarget::File(FileId::new(0)))
2499        );
2500    }
2501
2502    #[test]
2503    fn arrow_keys_do_not_operate_file_tree_folders() {
2504        let area = Rect::new(0, 0, 100, 9);
2505        let mut viewer = nested_tree_viewer();
2506
2507        viewer.handle_input(Event::Key(Key::Char('K')), area);
2508        assert_eq!(
2509            viewer.file_tree.target(),
2510            Some(FileTreeTarget::Directory(PathBuf::from("src")))
2511        );
2512
2513        assert_eq!(
2514            viewer.handle_input(Event::Key(Key::Left), area),
2515            Control::Continue
2516        );
2517        assert_eq!(
2518            viewer.handle_input(Event::Key(Key::Right), area),
2519            Control::Continue
2520        );
2521    }
2522
2523    #[test]
2524    fn left_click_on_file_tree_file_activates_it() {
2525        let area = Rect::new(0, 0, 100, 9);
2526        let mut viewer = tree_viewer();
2527
2528        assert_eq!(
2529            viewer.handle_input(left_click(2, 3, Modifiers::NONE), area),
2530            Control::Redraw
2531        );
2532
2533        assert_eq!(viewer.index.rows, 12);
2534        assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(1))));
2535    }
2536
2537    #[test]
2538    fn file_tree_selection_can_anchor_final_file() {
2539        let area = Rect::new(0, 0, 100, 9);
2540        let mut viewer = tree_viewer();
2541
2542        assert_eq!(
2543            viewer.handle_input(Event::Key(Key::Char('J')), area),
2544            Control::Redraw
2545        );
2546
2547        assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(1))));
2548        assert_eq!(viewer.state().scroll, 6);
2549    }
2550
2551    #[test]
2552    fn control_left_click_on_file_tree_file_jumps_to_it() {
2553        let area = Rect::new(0, 0, 100, 9);
2554        let mut viewer = tree_viewer();
2555        let rows = viewer.index.rows;
2556
2557        assert_eq!(
2558            viewer.handle_input(left_click(2, 3, Modifiers::CONTROL), area),
2559            Control::Redraw
2560        );
2561
2562        assert_eq!(viewer.index.rows, rows);
2563        assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(1))));
2564    }
2565
2566    #[test]
2567    fn left_click_outside_visible_file_tree_is_ignored() {
2568        let mut viewer = tree_viewer();
2569
2570        assert_eq!(
2571            viewer.handle_input(left_click(50, 1, Modifiers::NONE), Rect::new(0, 0, 100, 9)),
2572            Control::Continue
2573        );
2574        assert_eq!(
2575            viewer.handle_input(left_click(2, 1, Modifiers::NONE), Rect::new(0, 0, 80, 9)),
2576            Control::Continue
2577        );
2578        assert_eq!(viewer.state().focus, None);
2579    }
2580
2581    #[test]
2582    fn left_click_on_file_tree_folder_selects_without_toggling() {
2583        let area = Rect::new(0, 0, 100, 9);
2584        let mut viewer = nested_tree_viewer();
2585
2586        assert_eq!(
2587            viewer.handle_input(left_click(4, 2, Modifiers::NONE), area),
2588            Control::Redraw
2589        );
2590        viewer.handle_input(Event::Key(Key::Char('J')), area);
2591
2592        assert_eq!(
2593            viewer.file_tree.target(),
2594            Some(FileTreeTarget::File(FileId::new(0)))
2595        );
2596    }
2597
2598    #[test]
2599    fn selected_folder_background_is_dimmer_than_active_file_background() {
2600        let area = Rect::new(0, 0, 100, 9);
2601        let mut viewer = nested_tree_viewer();
2602        let mut buffer = Buffer::empty(area);
2603
2604        viewer.handle_input(left_click(4, 2, Modifiers::NONE), area);
2605        viewer.render(area, &mut buffer);
2606
2607        assert_eq!(
2608            buffer.get(0, 2).map(|cell| cell.style().bg_color()),
2609            Some(Color::Fixed(234))
2610        );
2611        assert_eq!(
2612            buffer.get(0, 3).map(|cell| cell.style().bg_color()),
2613            Some(Color::Fixed(235))
2614        );
2615    }
2616
2617    #[test]
2618    fn left_click_can_select_parent_and_child_folders_after_folder_selection() {
2619        let area = Rect::new(0, 0, 100, 8);
2620        let mut viewer = deep_tree_viewer();
2621
2622        assert_eq!(
2623            viewer.handle_input(left_click(6, 3, Modifiers::NONE), area),
2624            Control::Redraw
2625        );
2626        assert_eq!(
2627            viewer.file_tree.target(),
2628            Some(FileTreeTarget::Directory(PathBuf::from("src/app")))
2629        );
2630
2631        assert_eq!(
2632            viewer.handle_input(left_click(4, 2, Modifiers::NONE), area),
2633            Control::Redraw
2634        );
2635        assert_eq!(
2636            viewer.file_tree.target(),
2637            Some(FileTreeTarget::Directory(PathBuf::from("src")))
2638        );
2639
2640        assert_eq!(
2641            viewer.handle_input(left_click(6, 5, Modifiers::NONE), area),
2642            Control::Redraw
2643        );
2644        assert_eq!(
2645            viewer.file_tree.target(),
2646            Some(FileTreeTarget::Directory(PathBuf::from("src/lib")))
2647        );
2648    }
2649
2650    #[test]
2651    fn left_click_on_file_tree_disclosure_toggles_folder() {
2652        let area = Rect::new(0, 0, 100, 9);
2653        let mut viewer = nested_tree_viewer();
2654
2655        assert_eq!(
2656            viewer.handle_input(left_click(2, 2, Modifiers::NONE), area),
2657            Control::Redraw
2658        );
2659        assert_eq!(viewer.file_tree.target(), None);
2660        viewer.handle_input(Event::Key(Key::Char('J')), area);
2661        assert_eq!(
2662            viewer.file_tree.target(),
2663            Some(FileTreeTarget::File(FileId::new(2)))
2664        );
2665
2666        viewer.handle_input(Event::Key(Key::Char('K')), area);
2667        assert_eq!(
2668            viewer.handle_input(left_click(2, 2, Modifiers::NONE), area),
2669            Control::Redraw
2670        );
2671        viewer.handle_input(Event::Key(Key::Char('J')), area);
2672
2673        assert_eq!(
2674            viewer.file_tree.target(),
2675            Some(FileTreeTarget::File(FileId::new(0)))
2676        );
2677    }
2678
2679    #[test]
2680    fn left_click_on_file_tree_disclosure_keeps_current_selection() {
2681        let area = Rect::new(0, 0, 100, 8);
2682        let mut viewer = nested_tree_viewer();
2683
2684        viewer.handle_input(left_click(4, 4, Modifiers::NONE), area);
2685        assert_eq!(
2686            viewer.file_tree.target(),
2687            Some(FileTreeTarget::File(FileId::new(1)))
2688        );
2689
2690        assert_eq!(
2691            viewer.handle_input(left_click(2, 2, Modifiers::NONE), area),
2692            Control::Redraw
2693        );
2694
2695        assert_eq!(
2696            viewer.file_tree.target(),
2697            Some(FileTreeTarget::File(FileId::new(1)))
2698        );
2699    }
2700
2701    #[test]
2702    fn mouse_wheel_inputs_move_three_rows() {
2703        let area = Rect::new(0, 0, 80, 9);
2704        let mut viewer = scroll_viewer();
2705        let down = Event::Mouse(Mouse::Press {
2706            button: MouseButton::WheelDown,
2707            at: Point::new(0, 0),
2708            modifiers: Modifiers::NONE,
2709        });
2710        let up = Event::Mouse(Mouse::Press {
2711            button: MouseButton::WheelUp,
2712            at: Point::new(0, 0),
2713            modifiers: Modifiers::NONE,
2714        });
2715
2716        viewer.handle_input(down.clone(), area);
2717        assert_eq!(viewer.state().scroll, 3);
2718        viewer.handle_input(down, area);
2719        assert_eq!(viewer.state().scroll, 6);
2720        viewer.handle_input(up, area);
2721        assert_eq!(viewer.state().scroll, 3);
2722    }
2723
2724    #[test]
2725    fn control_scrolls_like_vim() {
2726        let area = Rect::new(0, 0, 80, 10);
2727        let mut viewer = scroll_viewer();
2728
2729        viewer.handle_input(Event::Key(Key::Ctrl('d')), area);
2730        assert_eq!(viewer.state().scroll, 5);
2731        viewer.handle_input(Event::Key(Key::Ctrl('u')), area);
2732        assert_eq!(viewer.state().scroll, 0);
2733    }
2734
2735    #[test]
2736    fn space_pages_down_like_less() {
2737        let area = Rect::new(0, 0, 80, 10);
2738        let mut viewer = scroll_viewer();
2739
2740        viewer.handle_input(Event::Key(Key::Char(' ')), area);
2741        assert_eq!(viewer.state().scroll, 10);
2742    }
2743
2744    #[test]
2745    fn visible_highlight_requests_only_visible_uncached_rows() {
2746        let mut viewer = sample_viewer();
2747        viewer.options.highlight_lookahead = 0;
2748        let area = Rect::new(0, 0, 64, 5);
2749
2750        let first = viewer.highlight_requests(area);
2751        let second = viewer.highlight_requests(area);
2752
2753        assert_eq!(first.len(), 2);
2754        assert!(second.is_empty());
2755        assert_eq!(
2756            first[0].source.line(first[0].key.source_line),
2757            Some("context")
2758        );
2759        assert_eq!(first[1].source.line(first[1].key.source_line), Some("old"));
2760        assert_eq!(first[0].key.theme, "auto");
2761    }
2762
2763    #[test]
2764    fn cancelled_highlight_requests_can_be_requested_again() {
2765        let mut viewer = sample_viewer();
2766        viewer.options.highlight_lookahead = 0;
2767        let area = Rect::new(0, 0, 64, 5);
2768
2769        let first = viewer.highlight_requests(area);
2770        assert!(!first.is_empty());
2771        viewer.cancel_highlights(first.clone());
2772        let second = viewer.highlight_requests(area);
2773
2774        assert_eq!(second, first);
2775    }
2776
2777    #[test]
2778    fn highlight_requests_use_hunk_side_sources() {
2779        let mut viewer = two_hunk_viewer();
2780
2781        let request = viewer
2782            .highlight_requests(Rect::new(0, 0, 64, 20))
2783            .into_iter()
2784            .find(|request| request.hunk == HunkId::new(1))
2785            .unwrap();
2786
2787        assert_eq!(request.source.head, 10);
2788        assert_eq!(request.source.text.as_ref(), "keep\nafter");
2789        assert_eq!(request.source.line(10), Some("keep"));
2790        assert_eq!(request.source.line(11), Some("after"));
2791        assert_eq!(request.source.line(12), None);
2792    }
2793
2794    #[test]
2795    fn repo_highlight_results_style_css_custom_properties_from_real_context() {
2796        let document = DiffDocument::decode_str(
2797            "\
2798diff --git a/assets/css/style.css b/assets/css/style.css
2799index 1111111..2222222 100644
2800--- a/assets/css/style.css
2801+++ b/assets/css/style.css
2802@@ -12,7 +12,8 @@
2803   --color-foreground: #112;
2804   --color-headers: #222;
2805   --color-background: #d3d1d1;
2806-  --color-background-light: #dedddd;
2807+  --color-background-light: #dad8d8;
2808+  --color-background-dark: #cecccc;
2809   --color-dim: #334;
2810   --color-dimmer: #666;
2811   --color-subtle: #888;
2812",
2813        )
2814        .unwrap();
2815        let mut viewer = DiffViewer::new(document, DiffOptions::default());
2816        let full = DiffDocument::decode_str(
2817            "\
2818diff --git a/assets/css/style.css b/assets/css/style.css
2819index 1111111..2222222 100644
2820--- a/assets/css/style.css
2821+++ b/assets/css/style.css
2822@@ -1,19 +1,20 @@
2823 html {
2824   box-sizing: border-box;
2825 }
2826 *, *::before, *::after {
2827   box-sizing: inherit;
2828 }
2829 body {
2830   margin: 0;
2831 }
2832 :root {
2833   color-scheme: light;
2834   --color-foreground: #112;
2835   --color-headers: #222;
2836   --color-background: #d3d1d1;
2837-  --color-background-light: #dedddd;
2838+  --color-background-light: #dad8d8;
2839+  --color-background-dark: #cecccc;
2840   --color-dim: #334;
2841   --color-dimmer: #666;
2842   --color-subtle: #888;
2843 }
2844",
2845        )
2846        .unwrap();
2847        let mut registry = syntax::Registry::default();
2848        registry.add_theme(
2849            syntax::Theme::parse(include_str!("themes/rustik-catppuccin-mocha.json")).unwrap(),
2850        );
2851        registry.add_grammar(syntax::Grammar::from_str(syntax::syntaxes::CSS).unwrap());
2852        let mut highlighter = crate::BuiltinHighlighter::new(registry, "rustik-catppuccin-mocha");
2853
2854        // Enrich the visible requests with full-file source, as the pager
2855        // worker does, so the highlighter sees the CSS rule in context.
2856        let source = full.files[0].highlight_source(DiffSide::New).unwrap();
2857        let mut requests = viewer.highlight_requests(Rect::new(0, 0, 80, 20));
2858        for request in &mut requests {
2859            if request.key.side == DiffSide::New {
2860                request.source = source.clone();
2861            }
2862        }
2863        let result = highlighter
2864            .highlight_requests(requests)
2865            .into_iter()
2866            .find(|result| {
2867                result.key.text_hash == {
2868                    use std::collections::hash_map::DefaultHasher;
2869                    use std::hash::{Hash, Hasher};
2870
2871                    let mut hasher = DefaultHasher::new();
2872                    "  --color-background-light: #dad8d8;".hash(&mut hasher);
2873                    hasher.finish()
2874                }
2875            })
2876            .unwrap();
2877
2878        let color = Color::RGB(137, 180, 250);
2879        let variable = result
2880            .line
2881            .labels()
2882            .iter()
2883            .find(|label| label.content().contains("--color-background-light"))
2884            .unwrap();
2885
2886        assert_eq!(variable.paint.style().fg_color(), color);
2887    }
2888
2889    #[test]
2890    fn metadata_lookup_matches_rendered_diff_rows() {
2891        let viewer = sample_viewer();
2892        for row in 0..viewer.index.rows {
2893            assert_eq!(
2894                viewer.diff_meta_at(row),
2895                viewer.render_row(row, 64).and_then(|row| row.diff)
2896            );
2897        }
2898    }
2899
2900    #[test]
2901    fn highlight_results_replace_pending_with_cached_lines() {
2902        let mut viewer = sample_viewer();
2903        let area = Rect::new(0, 0, 64, 5);
2904        let request = viewer.highlight_requests(area).into_iter().next().unwrap();
2905        let fresh = HighlightResult::new(request, Line::new(Label::new("fresh").fg(Color::Red)));
2906        assert!(viewer.apply_highlights([fresh]));
2907        assert_eq!(viewer.highlights.len(), 1);
2908    }
2909
2910    #[test]
2911    fn apply_visible_highlights_runs_one_visible_batch() {
2912        let mut viewer = sample_viewer();
2913        viewer.options.highlight_lookahead = 0;
2914        let area = Rect::new(0, 0, 64, 5);
2915        let mut highlighter = RecordingHighlighter::default();
2916
2917        assert!(viewer.apply_visible_highlights(area, &mut highlighter));
2918        assert_eq!(highlighter.batches, 1);
2919        assert_eq!(viewer.highlights.len(), 2);
2920
2921        assert!(!viewer.apply_visible_highlights(area, &mut highlighter));
2922        assert_eq!(highlighter.batches, 1);
2923    }
2924
2925    #[test]
2926    fn apply_highlights_populates_word_diff_cache() {
2927        // Word-diff ranges are computed on demand when the first highlight
2928        // result lands for a hunk, so the cached overlaid `Line` can be built.
2929        let mut viewer = word_diff_viewer();
2930        let area = Rect::new(0, 0, 80, 20);
2931        let request = viewer.highlight_requests(area).into_iter().next().unwrap();
2932        let hunk_id = request.hunk;
2933        let result = HighlightResult::new(request, Line::new(Label::blank()));
2934        viewer.apply_highlights([result]);
2935
2936        let changes = viewer.word_diffs.get(&hunk_id).unwrap();
2937        let added = viewer.document.files[0].hunks[0]
2938            .lines
2939            .iter()
2940            .find(|line| line.kind == DiffLineKind::Addition)
2941            .unwrap()
2942            .id;
2943        assert!(
2944            changes.get(&added).is_some_and(|ranges| !ranges.is_empty()),
2945            "expected new-side row to have changed ranges"
2946        );
2947    }
2948
2949    #[test]
2950    fn apply_highlights_bakes_word_diff_overlay_into_cache() {
2951        // The overlay should be applied at insert time, so the cached `Line`
2952        // already carries the bright bg and the render path performs no merge.
2953        let mut viewer = word_diff_viewer();
2954        let area = Rect::new(0, 0, 80, 20);
2955        let request = viewer
2956            .highlight_requests(area)
2957            .into_iter()
2958            .find(|request| request.key.side == DiffSide::New)
2959            .unwrap();
2960        let key = request.key.clone();
2961        let plain_text = viewer
2962            .document
2963            .files
2964            .iter()
2965            .flat_map(|file| file.hunks.iter().flat_map(|hunk| hunk.lines.iter()))
2966            .find(|line| line.id == request.row)
2967            .unwrap()
2968            .text
2969            .clone();
2970        let result = HighlightResult::new(request, Line::new(Label::new(plain_text.as_str())));
2971        assert!(viewer.apply_highlights([result]));
2972
2973        let cached = viewer.highlights.get(&key).unwrap();
2974        let bright = viewer.options.diff_palette.positive_word_bg;
2975        assert!(
2976            cached
2977                .labels()
2978                .iter()
2979                .any(|label| label.paint.style.bg_color() == bright),
2980            "expected the cached line to already include the bright word-diff bg"
2981        );
2982    }
2983
2984    fn word_diff_viewer() -> DiffViewer {
2985        // A similar-enough pair: only "mut " and ", opts: Options" change, so
2986        // the similarity gate is satisfied and word-diff ranges are emitted.
2987        let document = DiffDocument::decode_str(
2988            "\
2989diff --git a/a.rs b/a.rs
2990index 1111111..2222222 100644
2991--- a/a.rs
2992+++ b/a.rs
2993@@ -1 +1 @@
2994-fn render(view: &View) {
2995+fn render(view: &mut View, opts: Options) {
2996",
2997        )
2998        .unwrap();
2999        DiffViewer::new(document, DiffOptions::default())
3000    }
3001
3002    /// A [`Repo`] that returns a canned patch and records refetch requests.
3003    struct FakeRepo {
3004        /// Raw unified-diff bytes handed back from every refetch.
3005        patch: Vec<u8>,
3006        /// Context width and paths of each `diff` call, in call order.
3007        calls: std::cell::RefCell<Vec<(usize, Vec<PathBuf>)>>,
3008    }
3009
3010    impl FakeRepo {
3011        /// Builds a repo whose refetches return `patch` as raw diff bytes.
3012        fn new(patch: &str) -> Self {
3013            Self {
3014                patch: patch.as_bytes().to_vec(),
3015                calls: std::cell::RefCell::new(Vec::new()),
3016            }
3017        }
3018    }
3019
3020    impl Repo for FakeRepo {
3021        fn diff(
3022            &self,
3023            context_lines: usize,
3024            paths: &[&std::path::Path],
3025        ) -> Result<Vec<u8>, RepoError> {
3026            let paths = paths.iter().map(|path| path.to_path_buf()).collect();
3027            self.calls.borrow_mut().push((context_lines, paths));
3028            Ok(self.patch.clone())
3029        }
3030    }
3031
3032    #[test]
3033    fn async_context_request_decodes_and_applies_update() {
3034        let mut viewer = sample_viewer();
3035        let area = Rect::new(0, 0, 64, 9);
3036        let repo = FakeRepo::new(
3037            "\
3038diff --git a/a.rs b/a.rs
3039index 1111111..2222222 100644
3040--- a/a.rs
3041+++ b/a.rs
3042@@ -1,5 +1,6 @@ fn main
3043 lead
3044 context
3045-old
3046+new
3047+extra
3048 tail
3049 trail
3050",
3051        );
3052        let request = viewer.context_request(ContextChange::Increase).unwrap();
3053        let paths = request.paths().collect::<Vec<_>>();
3054        let patch = repo.diff(request.context_lines(), &paths).unwrap();
3055        drop(paths);
3056        let update = request.decode(&patch).unwrap().unwrap();
3057
3058        viewer.apply_context_update(update, area);
3059        let calls = repo.calls.borrow();
3060        assert_eq!(calls.len(), 1);
3061        assert_eq!(calls[0].0, 4);
3062        assert_eq!(calls[0].1, vec![PathBuf::from("a.rs")]);
3063        assert_eq!(viewer.document.files[0].hunks[0].header.old_size, 5);
3064    }
3065
3066    #[test]
3067    fn context_request_targets_focused_file() {
3068        let mut viewer = two_file_viewer();
3069        viewer.set_focus(Some(DiffFocus::File(FileId::new(1))));
3070
3071        let repo = FakeRepo::new(
3072            "\
3073diff --git a/a.rs b/a.rs
3074index 1111111..2222222 100644
3075--- a/a.rs
3076+++ b/a.rs
3077@@ -1,3 +1,4 @@ fn a
3078 context
3079-old
3080+new
3081+extra
3082 tail
3083diff --git a/b.rs b/b.rs
3084index 3333333..4444444 100644
3085--- a/b.rs
3086+++ b/b.rs
3087@@ -1,3 +1,3 @@ fn b
3088 keep
3089-before
3090+after
3091 trail
3092",
3093        );
3094
3095        let request = viewer.context_request(ContextChange::Increase).unwrap();
3096        let paths = request.paths().collect::<Vec<_>>();
3097        let patch = repo.diff(request.context_lines(), &paths).unwrap();
3098        drop(paths);
3099        let update = request.decode(&patch).unwrap().unwrap();
3100        viewer.apply_context_update(update, Rect::new(0, 0, 64, 20));
3101
3102        let calls = repo.calls.borrow();
3103        assert_eq!(calls.len(), 1);
3104        assert_eq!(calls[0].1, vec![PathBuf::from("b.rs")]);
3105    }
3106}