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::io::Read as _;
9use std::ops::Range;
10use std::path::{Component, Path, PathBuf};
11use std::sync::Arc;
12
13use rustik_highlight as syntax;
14use rustik_tui as tui;
15use tui::{
16    Badge, Buffer, Cell, Color, Constraint, Control, Event, HStack, Key, Label, Line, Mouse,
17    MouseButton, Paint, Rect, Scroll, ScrollView, ScrollbarStyle, Size, Style, Table, TableOptions,
18    Text, VStack, View, Viewport, Widget, colors,
19};
20
21use crate::context::{self, ContextChange, ContextState};
22use crate::decorate::{DiffDecorator, FileDecoration, HunkDecoration, ReviewProgress};
23use crate::highlight::{DiffHighlighter, HighlightKeyInput, HighlightResult};
24use crate::word;
25use crate::{
26    CommitHeader, Decode, DecodeError, DiffDocument, DiffLine, DiffLineKind, DiffSide, FileDiff,
27    FileId, FileKind, FileMode, FileStats, HighlightKey, HighlightRequest, HighlightSource, Hunk,
28    HunkId, Oid, RowId,
29};
30
31pub use tree::{FileTree, FileTreeMode, FileTreeTarget};
32
33/// Visible and lookahead row ranges that should be highlighted.
34#[derive(Clone, Debug, Eq, PartialEq)]
35struct HighlightWindow {
36    /// First row that can produce a visible highlight.
37    start: usize,
38    /// End of the currently visible row range.
39    visible_end: usize,
40    /// End of the lookahead row range.
41    lookahead_end: usize,
42}
43
44/// Minimum width before the viewer attempts table-style diff rows.
45const MIN_RENDER_COLS: usize = 12;
46/// Width of old and new line number cells.
47const LINE_NUMBER_WIDTH: usize = 5;
48/// Width of the review-state gutter before the line numbers.
49const REVIEW_GUTTER_WIDTH: usize = 1;
50/// Foreground color used by old and new line number cells.
51const LINE_NUMBER_FG: Color = colors::fixed::DIM;
52/// Foreground color used by line number cells in the focused hunk.
53const SELECTED_LINE_NUMBER_FG: Color = colors::fixed::MUTED;
54/// Width of the hunk marker cell.
55const MARKER_WIDTH: usize = 3;
56/// Scrollbar track glyph (distinct from box-drawing borders so the column reads as a track).
57const SCROLLBAR_TRACK: char = '๐Ÿฎ˜';
58/// Scrollbar thumb glyph.
59const SCROLLBAR_THUMB: char = 'โ–';
60/// File-card divider glyph (used between header/hunks and between hunks).
61const DIVIDER: char = 'โ”€';
62/// Foreground color for neutral file-kind badges such as moved and copied.
63const FILE_KIND_BADGE_FG: Color = colors::rgb::PURPLE;
64/// Dim background for neutral file-kind badges.
65const FILE_KIND_BADGE_BG: Color = Color::RGB(32, 22, 42);
66/// Shared border style for all file cards.
67const FILE_BORDER: tui::Border = tui::Border::new(colors::FAINT);
68/// Sticky file-header divider glyph.
69const STICKY_DIVIDER: char = 'โ•ด';
70/// Rename arrow.
71const RENAME_ARROW: &str = "โ†’";
72/// Missing trailing newline marker.
73const NO_NEWLINE_MARKER: &str = "\\ No newline at end of file";
74/// Rendered source text replacement for a single source tab.
75const SOURCE_TAB_MARKER: &str = "ยท   ";
76/// Marker cell shown between hunks in the diff marker column.
77const HUNK_GAP_MARKER_CELL: &str = " โ‹ฎ ";
78/// Separator shown between file header metadata segments: ยท.
79const FILE_HEADER_SEGMENT_SEPARATOR: &str = "  ยท ";
80/// Width of the file review progress bar in file headers.
81const FILE_PROGRESS_BAR_WIDTH: usize = 10;
82/// Glyph text used by file review progress bars: โ”.
83const FILE_PROGRESS_BAR_GLYPH: &str = "โ”";
84/// Columns reserved for file-header review status, matching "+9999 -9999".
85const FILE_REVIEW_STATUS_COLS: usize = 11;
86/// Default syntax theme selection stored in highlight keys.
87const DEFAULT_THEME: &str = "auto";
88/// Number of rows in a sticky file header.
89const STICKY_HEADER_ROWS: usize = 3;
90/// Number of body rows moved by keyboard line-scroll inputs.
91const LINE_SCROLL_ROWS: isize = 1;
92/// Number of body rows moved by mouse-wheel inputs.
93const WHEEL_SCROLL_ROWS: isize = 3;
94/// Local row of a file card's top border.
95const FILE_TOP_ROW: usize = 0;
96/// Local row of a file card's header.
97const FILE_HEADER_ROW: usize = 1;
98/// Local row of the divider between a file header and its hunk body.
99const FILE_DIVIDER_ROW: usize = 2;
100/// Local row of the first hunk body line after the fixed file-card chrome.
101const HUNK_BODY_START: usize = FILE_DIVIDER_ROW + 1;
102/// Total card height when the file has no visible body.
103const EMPTY_CARD_ROWS: usize = FILE_DIVIDER_ROW + 1;
104
105/// Mutable read-only diff viewport state.
106#[derive(Clone, Debug, Default, Eq, PartialEq)]
107pub struct DiffState {
108    /// Vertical viewport over the rendered document.
109    pub scroll: Viewport,
110    /// Currently focused commit, file, or hunk.
111    pub focus: Option<DiffFocus>,
112}
113
114/// Focus target inside a diff document.
115#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
116pub enum DiffFocus {
117    /// Focus the commit header.
118    Commit,
119    /// Focus a file header.
120    File(FileId),
121    /// Focus a hunk header.
122    Hunk(HunkId),
123}
124
125/// Viewer action accepted by [`DiffViewer::apply`].
126#[derive(Clone, Copy, Debug, Eq, PartialEq)]
127pub enum DiffAction {
128    /// Scroll the viewport.
129    Scroll(Scroll),
130    /// Clamp scroll after a terminal resize.
131    Resize,
132    /// Focus the next file or hunk target.
133    FocusNext,
134    /// Focus the previous file or hunk target.
135    FocusPrevious,
136    /// Focus the next hunk target.
137    NextHunk,
138    /// Focus the previous hunk target.
139    PreviousHunk,
140    /// Toggle the file tree between automatic visibility and hidden.
141    ToggleFileTree,
142    /// Move the file-tree cursor by visible rows, jumping to files as they are selected.
143    MoveFileTree(isize),
144    /// Show the current file-tree target without changing folder expansion.
145    ShowFileTreeTarget,
146    /// Activate the current file-tree target.
147    ActivateFileTreeTarget,
148    /// Collapse the focused file-tree folder.
149    CollapseFileTreeFolder,
150    /// Expand the focused file-tree folder.
151    ExpandFileTreeFolder,
152}
153
154/// Result of applying a viewer action.
155#[derive(Clone, Copy, Debug, Eq, PartialEq)]
156pub enum ViewChange {
157    /// The action changed viewer state.
158    Changed,
159    /// The action left viewer state unchanged.
160    Unchanged,
161}
162
163/// Diff viewer options.
164#[derive(Clone, Debug)]
165pub struct DiffOptions {
166    /// Optional syntax override stored in highlight requests.
167    pub syntax: Option<String>,
168    /// Theme name stored in highlight requests.
169    pub theme: String,
170    /// Positive and negative colors used for diff chrome.
171    pub diff_palette: DiffPalette,
172    /// Whether the file tree may be rendered beside the diff.
173    pub file_tree: FileTreeMode,
174    /// Folder name shown as the file tree root.
175    pub file_tree_root: String,
176    /// Visual treatment for hunk focus.
177    pub hunk_focus: HunkFocus,
178}
179
180/// Visual treatment for hunk focus.
181#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
182pub enum HunkFocus {
183    /// Render focused and unfocused hunks normally.
184    #[default]
185    Plain,
186    /// Force all non-focused hunk body rows to the dim foreground.
187    DimUnfocused,
188}
189
190/// Positive and negative colors used for diff chrome.
191#[derive(Clone, Copy, Debug, Eq, PartialEq)]
192pub struct DiffPalette {
193    /// Background color for removed source rows.
194    pub negative_row_bg: Color,
195    /// Background color for added source rows.
196    pub positive_row_bg: Color,
197    /// Background color for changed word spans inside removed rows.
198    pub negative_word_bg: Color,
199    /// Background color for changed word spans inside added rows.
200    pub positive_word_bg: Color,
201    /// Foreground color for removed stats, markers, and labels.
202    pub negative_fg: Color,
203    /// Foreground color for added stats, markers, and labels.
204    pub positive_fg: Color,
205}
206
207/// Repo refetch request prepared by the viewer for asynchronous context updates.
208#[derive(Clone, Debug)]
209pub struct ContextRequest {
210    /// Context state to install when the request completes.
211    next_context: ContextState,
212    /// Paths and original file ids to replace.
213    files: Vec<(PathBuf, FileId)>,
214    /// Currently rendered hunks whose identities should survive the refetch.
215    originals: Vec<FileDiff>,
216    /// Git context width to request.
217    context_lines: usize,
218    /// Next hunk and row ids used to remap fetched files.
219    next_ids: (usize, usize),
220}
221
222/// Decoded replacement files for an asynchronous context update.
223#[derive(Clone, Debug)]
224pub struct ContextUpdate {
225    /// Context state prepared when the request was started.
226    next_context: ContextState,
227    /// Replacement file diffs with ids remapped to this viewer.
228    files: Vec<FileDiff>,
229    /// Unchanged rows added outside the original bounded review hunks.
230    expanded_context: BTreeSet<RowId>,
231}
232
233/// Pure diff viewer that renders into a caller-owned buffer.
234#[derive(Clone, Debug)]
235pub struct DiffViewer {
236    /// Diff document being viewed.
237    document: DiffDocument,
238    /// File metadata that does not change with hunk visibility or context.
239    summaries: BTreeMap<FileId, FileSummary>,
240    /// Unchanged full-file rows outside the bounded review hunks.
241    expanded_context: BTreeSet<RowId>,
242    /// Viewer options.
243    options: DiffOptions,
244    /// Mutable viewport state.
245    state: DiffState,
246    /// Last focused visible hunk for each file.
247    hunk_focus: BTreeMap<FileId, HunkId>,
248    /// Highlighted row cache.
249    highlights: BTreeMap<HighlightKey, Line>,
250    /// Requests already handed to a worker.
251    pending_highlights: BTreeSet<HighlightKey>,
252    /// Per-hunk source context reused across highlight-request batches.
253    hunk_highlight_sources: BTreeMap<(FileId, HunkId, DiffSide), HighlightSource>,
254    /// Whole-file source text used as highlighting context, keyed by blob.
255    ///
256    /// A syntax tokenizer's state at a line is the fold of every line before it,
257    /// so a hunk highlighted in isolation starts from a default state and loses
258    /// any enclosing block, comment, or string. Highlighting against the whole
259    /// blob restores that context; sides with no blob (added or deleted files)
260    /// are absent and fall back to the hunk-only source.
261    ///
262    /// Keying by object id rather than by file means hiding hunks or widening
263    /// context cannot invalidate an entry: those rewrite a file's hunks but
264    /// leave it pointing at the same blobs.
265    blob_sources: BTreeMap<Oid, HighlightSource>,
266    /// Whole-file source text for worktree files, which have no new-side blob.
267    worktree_sources: BTreeMap<PathBuf, HighlightSource>,
268    /// Total bytes held across both source maps.
269    source_bytes: usize,
270    /// Cached intra-line word diffs, keyed by hunk.
271    word_diffs: BTreeMap<HunkId, word::WordChanges>,
272    /// Rendered commit-preamble rows for the most recent body width.
273    preamble: Vec<Line>,
274    /// File-tree state and model.
275    file_tree: tree::FileTree,
276    /// Interactive override for file-tree visibility.
277    file_tree_visibility: FileTreeVisibility,
278    /// Cached rendered row positions for visible files.
279    index: RowIndex,
280    /// Hunk-context expansion bookkeeping.
281    context: ContextState,
282    /// Optional host-supplied source of file and hunk decorations.
283    ///
284    /// Shared rather than boxed so the viewer keeps deriving `Clone`. `None`
285    /// renders the plain diff with no decorations.
286    decorator: Option<Arc<dyn DiffDecorator>>,
287}
288
289/// Cached rendered row positions for the current document visibility state.
290///
291/// Visible files tile the content region contiguously, so each file is stored
292/// by its first rendered row only; its last row is the next file's start (or
293/// [`RowIndex::rows`] for the final file).
294#[derive(Clone, Debug, Default)]
295struct RowIndex {
296    /// Visible files in rendered order, each at its first rendered row.
297    files: Vec<IndexedFileRows>,
298    /// Total number of rendered rows.
299    rows: usize,
300}
301
302/// Largest blob kept as syntax-highlighting context, in bytes.
303///
304/// Tokenizing the lines before a hunk is linear in the prefix and cached per
305/// file, so the cap only guards against pathological inputs such as minified
306/// bundles or generated data.
307const MAX_SOURCE_BYTES: usize = 2 * 1024 * 1024;
308
309/// Total bytes of highlight context a viewer keeps across all files.
310///
311/// A per-blob cap alone bounds nothing in aggregate: a review touching
312/// thousands of files would otherwise hold every one of their sides resident.
313/// Files past the budget keep using hunk-only sources.
314const MAX_TOTAL_SOURCE_BYTES: usize = 64 * 1024 * 1024;
315
316/// One source blob read for LOC metadata and highlight context.
317#[derive(Clone, Debug)]
318struct LoadedBlob {
319    /// Nonblank line count.
320    loc: usize,
321    /// Blob source, absent when the blob is binary or above [`MAX_SOURCE_BYTES`].
322    source: Option<HighlightSource>,
323}
324
325impl LoadedBlob {
326    /// Counts lines and keeps the text when it is usable as highlight context.
327    fn read(bytes: Vec<u8>) -> Self {
328        let loc = bytes
329            .split(|byte| *byte == b'\n')
330            .filter(|line| line.iter().any(|byte| !byte.is_ascii_whitespace()))
331            .count();
332        let source = (bytes.len() <= MAX_SOURCE_BYTES)
333            .then(|| String::from_utf8(bytes).ok())
334            .flatten()
335            .map(|text| HighlightSource::new(text, 1));
336
337        Self { loc, source }
338    }
339
340    /// Reads a bounded source from one safe worktree path.
341    ///
342    /// `root` must be canonical so containment checks use one path form.
343    fn read_worktree(root: &Path, path: &Path, mode: FileMode) -> Option<Self> {
344        if path.as_os_str().is_empty()
345            || !path
346                .components()
347                .all(|component| matches!(component, Component::Normal(_)))
348        {
349            return None;
350        }
351        let full_path = root.join(path);
352        let bytes = if mode == FileMode::Link {
353            let parent = full_path.parent()?.canonicalize().ok()?;
354            if !parent.starts_with(root)
355                || !std::fs::symlink_metadata(&full_path)
356                    .ok()?
357                    .file_type()
358                    .is_symlink()
359            {
360                return None;
361            }
362            std::fs::read_link(full_path)
363                .ok()?
364                .into_os_string()
365                .into_encoded_bytes()
366        } else {
367            if !std::fs::symlink_metadata(&full_path)
368                .ok()?
369                .file_type()
370                .is_file()
371            {
372                return None;
373            }
374            let path = full_path.canonicalize().ok()?;
375            if !path.starts_with(root) {
376                return None;
377            }
378            let mut file = std::fs::File::open(path).ok()?;
379            if file.metadata().ok()?.len() > MAX_SOURCE_BYTES as u64 {
380                return None;
381            }
382            let mut bytes = Vec::new();
383            file.by_ref()
384                .take(MAX_SOURCE_BYTES as u64 + 1)
385                .read_to_end(&mut bytes)
386                .ok()?;
387            if bytes.len() > MAX_SOURCE_BYTES {
388                return None;
389            }
390            bytes
391        };
392
393        Some(Self::read(bytes))
394    }
395}
396
397/// Stable metadata shown in a file header.
398#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
399struct FileSummary {
400    /// Nonblank displayed-side lines, upgraded from the full blob when available.
401    loc: Option<usize>,
402    /// Addition and deletion counts in the original file diff.
403    stats: FileStats,
404}
405
406/// Whether separate review hunks render a synthetic gap row between them.
407#[derive(Clone, Copy, Debug, Eq, PartialEq)]
408enum HunkGaps {
409    /// Show a vertical ellipsis where bounded diff context is omitted.
410    Visible,
411    /// Join contiguous full-file context without a synthetic gap.
412    Hidden,
413}
414
415impl From<&FileDiff> for FileSummary {
416    fn from(file: &FileDiff) -> Self {
417        let stats = file.stats();
418        Self {
419            loc: (file.header.kind != FileKind::Binary).then(|| file.loc()),
420            stats,
421        }
422    }
423}
424
425/// The rendered position of one visible file.
426#[derive(Clone, Copy, Debug)]
427struct IndexedFileRows {
428    /// Index into the document file list.
429    file_index: usize,
430    /// First rendered row occupied by the file.
431    start: usize,
432}
433
434/// One rendered row before viewport projection.
435#[derive(Clone, Debug)]
436struct RenderRow {
437    /// Renderable line.
438    line: Line,
439    /// Source-row metadata when this is a diff source row.
440    diff: Option<DiffLineMeta>,
441}
442
443/// Hunk decoration resolved for one rendered body row.
444#[derive(Clone, Copy, Debug, Default)]
445struct HunkRowDecoration {
446    /// Optional marker drawn before a changed row.
447    gutter: Option<Paint<char>>,
448    /// Style composed onto the row body.
449    style: Option<Style>,
450}
451
452/// Render location of a row inside one file card.
453#[derive(Clone, Copy, Debug, Eq, PartialEq)]
454struct FileRowLocation<'a> {
455    /// File containing the row.
456    file: &'a FileDiff,
457    /// Global row where the file card starts.
458    start: usize,
459    /// Global row one past the end of the file card.
460    end: usize,
461    /// Row offset inside the file card.
462    local: usize,
463}
464
465/// Sticky file-header rows visible during a render pass.
466#[derive(Clone, Copy, Debug, Eq, PartialEq)]
467struct StickyHeaderRows {
468    /// Global source row where the full file header starts.
469    start: usize,
470    /// Number of header rows still pinned in the viewport.
471    rows: usize,
472}
473
474/// Metadata for one source row.
475#[derive(Clone, Debug, Eq, PartialEq)]
476struct DiffLineMeta {
477    /// File containing the row.
478    file: FileId,
479    /// Hunk containing the row.
480    hunk: HunkId,
481    /// Row identifier.
482    row: RowId,
483    /// Line role inside the hunk.
484    kind: DiffLineKind,
485    /// Source side used for highlighting.
486    side: DiffSide,
487    /// One-based source line number.
488    source_line: u32,
489    /// Source text.
490    text: String,
491    /// Source path.
492    path: Option<PathBuf>,
493}
494
495/// Main viewer layout for the current viewport.
496#[derive(Clone, Copy, Debug, Eq, PartialEq)]
497struct DiffLayout {
498    /// Main diff rectangle.
499    diff: Rect,
500    /// File tree rectangle, when the tree is visible.
501    tree: Option<Rect>,
502}
503
504/// Interactive override for the configured file-tree rendering policy.
505#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
506enum FileTreeVisibility {
507    /// Follow the configured file-tree rendering policy.
508    #[default]
509    Auto,
510    /// Show the file tree even when automatic layout would hide it.
511    Visible,
512    /// Hide the file tree until it is toggled back on.
513    Hidden,
514}
515
516impl Default for DiffOptions {
517    fn default() -> Self {
518        Self {
519            syntax: None,
520            theme: DEFAULT_THEME.to_owned(),
521            diff_palette: DiffPalette::default(),
522            file_tree: FileTreeMode::default(),
523            file_tree_root: ".".to_owned(),
524            hunk_focus: HunkFocus::default(),
525        }
526    }
527}
528
529impl Default for DiffPalette {
530    fn default() -> Self {
531        Self {
532            negative_row_bg: colors::rgb::NEGATIVE_DARK,
533            positive_row_bg: colors::rgb::POSITIVE_DARK,
534            negative_word_bg: colors::rgb::NEGATIVE,
535            positive_word_bg: colors::rgb::POSITIVE,
536            negative_fg: colors::rgb::NEGATIVE_LIGHT,
537            positive_fg: colors::rgb::POSITIVE_LIGHT,
538        }
539    }
540}
541
542impl From<&syntax::RawTheme> for DiffPalette {
543    fn from(theme: &syntax::RawTheme) -> Self {
544        let mut palette = Self::default();
545        if theme.colors.is_empty() {
546            return palette;
547        };
548        palette.positive_fg =
549            Self::theme_color(&theme.colors, "gitDecoration.addedResourceForeground")
550                .or_else(|| Self::theme_color(&theme.colors, "editorGutter.addedBackground"))
551                .unwrap_or(palette.positive_fg);
552        palette.negative_fg =
553            Self::theme_color(&theme.colors, "gitDecoration.deletedResourceForeground")
554                .or_else(|| Self::theme_color(&theme.colors, "editorGutter.deletedBackground"))
555                .unwrap_or(palette.negative_fg);
556        palette.positive_row_bg =
557            Self::theme_color(&theme.colors, "diffEditor.insertedLineBackground")
558                .unwrap_or(palette.positive_row_bg);
559        palette.negative_row_bg =
560            Self::theme_color(&theme.colors, "diffEditor.removedLineBackground")
561                .unwrap_or(palette.negative_row_bg);
562        palette.positive_word_bg =
563            Self::theme_color(&theme.colors, "diffEditor.insertedTextBackground")
564                .unwrap_or(palette.positive_word_bg);
565        palette.negative_word_bg =
566            Self::theme_color(&theme.colors, "diffEditor.removedTextBackground")
567                .unwrap_or(palette.negative_word_bg);
568        palette
569    }
570}
571
572impl DiffPalette {
573    /// Returns one RGB color from a theme color map.
574    fn theme_color(colors: &BTreeMap<String, String>, key: &str) -> Option<Color> {
575        let color = colors.get(key)?.parse::<syntax::Rgb>().ok()?;
576        Some(Color::RGB(color.r, color.g, color.b))
577    }
578}
579
580impl ContextRequest {
581    /// Returns the Git context width to fetch.
582    pub const fn context_lines(&self) -> usize {
583        self.context_lines
584    }
585
586    /// Returns the paths that should be fetched from the repo.
587    pub fn paths(&self) -> impl Iterator<Item = &Path> {
588        self.files.iter().map(|(path, _)| path.as_path())
589    }
590
591    /// Decodes a repo patch into a viewer update.
592    pub fn decode(self, patch: &[u8]) -> Result<Option<ContextUpdate>, DecodeError> {
593        let document = DiffDocument::decode_bytes(patch)?.split_hunks();
594        let result: Result<Option<Vec<FileDiff>>, Infallible> =
595            context::rebuild(self.next_ids, &self.files, self.context_lines, |_, _| {
596                Ok(document.files)
597            });
598        let mut files = match result {
599            Ok(Some(files)) => files,
600            Ok(None) => return Ok(None),
601            Err(error) => match error {},
602        };
603        let mut expanded_context = BTreeSet::new();
604        for replacement in &mut files {
605            let Some(original) = self.originals.iter().find(|file| file.id == replacement.id)
606            else {
607                continue;
608            };
609            let mut matched = BTreeSet::new();
610            for hunk in &mut replacement.hunks {
611                let changed = hunk
612                    .lines
613                    .iter()
614                    .filter(|line| line.kind != DiffLineKind::Context)
615                    .map(|line| (line.kind, line.text.as_str()));
616                let Some(original) = original.hunks.iter().find(|original| {
617                    !matched.contains(&original.id)
618                        && original
619                            .lines
620                            .iter()
621                            .filter(|line| line.kind != DiffLineKind::Context)
622                            .map(|line| (line.kind, line.text.as_str()))
623                            .eq(changed.clone())
624                }) else {
625                    continue;
626                };
627                hunk.id = original.id;
628                matched.insert(original.id);
629
630                let bounded = hunk.lines.windows(original.lines.len()).position(|window| {
631                    window
632                        .iter()
633                        .zip(&original.lines)
634                        .all(|(left, right)| left.kind == right.kind && left.text == right.text)
635                });
636                if let Some(start) = bounded {
637                    let end = start + original.lines.len();
638                    expanded_context.extend(
639                        hunk.lines[..start]
640                            .iter()
641                            .chain(&hunk.lines[end..])
642                            .filter(|line| line.kind == DiffLineKind::Context)
643                            .map(|line| line.id),
644                    );
645                }
646            }
647        }
648
649        Ok(Some(ContextUpdate {
650            next_context: self.next_context,
651            files,
652            expanded_context,
653        }))
654    }
655}
656
657impl ContextUpdate {
658    /// Returns replacement files so a host can restore stable hunk identities.
659    pub fn files_mut(&mut self) -> &mut [FileDiff] {
660        &mut self.files
661    }
662
663    /// Returns replacement files after host identity reconciliation.
664    pub fn files(&self) -> &[FileDiff] {
665        &self.files
666    }
667}
668
669impl DiffViewer {
670    /// Creates a viewer with plain initial rendering state.
671    pub fn new(document: DiffDocument, options: DiffOptions) -> Self {
672        let preamble = Self::preamble(document.commit.as_ref(), MIN_RENDER_COLS);
673        let file_tree = tree::FileTree::new(&document, options.file_tree_root.clone());
674        let summaries = document
675            .files
676            .iter()
677            .map(|file| (file.id, FileSummary::from(file)))
678            .collect();
679        let state = DiffState {
680            focus: document.commit.is_some().then_some(DiffFocus::Commit),
681            ..DiffState::default()
682        };
683
684        let mut viewer = Self {
685            document,
686            summaries,
687            expanded_context: BTreeSet::new(),
688            options,
689            state,
690            hunk_focus: BTreeMap::new(),
691            highlights: BTreeMap::new(),
692            pending_highlights: BTreeSet::new(),
693            hunk_highlight_sources: BTreeMap::new(),
694            blob_sources: BTreeMap::new(),
695            worktree_sources: BTreeMap::new(),
696            source_bytes: 0,
697            word_diffs: BTreeMap::new(),
698            preamble,
699            file_tree,
700            file_tree_visibility: FileTreeVisibility::default(),
701            index: RowIndex::default(),
702            context: ContextState::new(),
703            decorator: None,
704        };
705        viewer.rebuild_index();
706        viewer
707    }
708
709    /// Sets the source queried for per-file and per-hunk decorations.
710    ///
711    /// Decorations are pure overlays: they change what each file header and
712    /// hunk render without affecting row counts, scrolling, or focus.
713    pub fn set_decorator(&mut self, decorator: impl DiffDecorator + 'static) {
714        self.decorator = Some(Arc::new(decorator));
715    }
716
717    /// Clears any decorator, restoring the plain diff rendering.
718    pub fn clear_decorator(&mut self) {
719        self.decorator = None;
720    }
721
722    /// Returns the decoration for a file header, or the empty default.
723    fn file_decoration(&self, file: FileId) -> FileDecoration {
724        self.decorator
725            .as_ref()
726            .map_or_else(FileDecoration::default, |decorator| decorator.file(file))
727    }
728
729    /// Returns the decoration for a hunk, or the empty default.
730    fn hunk_decoration(&self, file: FileId, hunk: HunkId) -> HunkDecoration {
731        self.decorator
732            .as_ref()
733            .map_or_else(HunkDecoration::default, |decorator| {
734                decorator.hunk(file, hunk)
735            })
736    }
737
738    /// Returns the viewed document.
739    pub const fn document(&self) -> &DiffDocument {
740        &self.document
741    }
742
743    /// Loads full-file LOC metadata and highlight context from each text file's blobs.
744    ///
745    /// Both diff sides are read so deleted rows highlight against the old blob
746    /// and added rows against the new one. Blobs are read once per object id and
747    /// shared between files that reference them.
748    pub fn load_file_sources<E>(
749        &mut self,
750        mut read_blob: impl FnMut(Oid) -> Result<Vec<u8>, E>,
751    ) -> Result<(), E> {
752        let mut blobs: BTreeMap<Oid, usize> = BTreeMap::new();
753
754        for file in &self.document.files {
755            if file.header.kind == FileKind::Binary {
756                continue;
757            }
758            for oid in [file.header.old_oid, file.header.new_oid]
759                .into_iter()
760                .flatten()
761                .filter(|oid| !oid.is_zero())
762            {
763                if let Entry::Vacant(entry) = blobs.entry(oid) {
764                    let blob = LoadedBlob::read(read_blob(oid)?);
765                    entry.insert(blob.loc);
766                    if let Some(source) = blob.source.filter(|source| {
767                        self.source_bytes.saturating_add(source.retained_bytes())
768                            <= MAX_TOTAL_SOURCE_BYTES
769                    }) {
770                        self.source_bytes += source.retained_bytes();
771                        self.blob_sources.insert(oid, source);
772                    }
773                }
774            }
775
776            let oid = if file.header.kind == FileKind::Deleted {
777                file.header.old_oid
778            } else {
779                file.header.new_oid.or(file.header.old_oid)
780            };
781            let Some(loc) = oid.and_then(|oid| blobs.get(&oid)).copied() else {
782                continue;
783            };
784            if let Some(summary) = self.summaries.get_mut(&file.id) {
785                summary.loc = Some(loc);
786            }
787        }
788        Ok(())
789    }
790
791    /// Loads new-side highlight context from the working tree.
792    ///
793    /// Working-tree diffs have no new-side object id, so the post-image only
794    /// exists on disk. Unreadable files are skipped: highlighting falls back to
795    /// the hunk-only source for those.
796    pub fn load_worktree_sources(&mut self, root: &Path) {
797        let Ok(root) = root.canonicalize() else {
798            return;
799        };
800        for file in &self.document.files {
801            if file.header.kind == FileKind::Binary
802                || file.header.kind == FileKind::Deleted
803                || file.header.new_oid.is_some()
804            {
805                continue;
806            }
807            let Some(path) = file.header.new_path.as_ref() else {
808                continue;
809            };
810            let mode = file.header.new_mode.unwrap_or(FileMode::Blob);
811            let Some(blob) = LoadedBlob::read_worktree(&root, path, mode) else {
812                continue;
813            };
814            if let Some(source) = blob.source.filter(|source| {
815                self.source_bytes.saturating_add(source.retained_bytes()) <= MAX_TOTAL_SOURCE_BYTES
816            }) {
817                self.source_bytes += source.retained_bytes();
818                self.worktree_sources.insert(path.clone(), source);
819            }
820            if let Some(summary) = self.summaries.get_mut(&file.id) {
821                summary.loc = Some(blob.loc);
822            }
823        }
824    }
825
826    /// Returns the viewer options.
827    pub const fn options(&self) -> &DiffOptions {
828        &self.options
829    }
830
831    /// Returns the viewer state.
832    pub const fn state(&self) -> &DiffState {
833        &self.state
834    }
835
836    /// Replaces the viewer state.
837    pub fn set_state(&mut self, mut state: DiffState) {
838        let focus = state.focus.take();
839        self.state = state;
840        self.set_focus(focus);
841    }
842
843    /// Replaces existing file diffs in place, matching them by id.
844    pub fn replace_file_diffs(&mut self, files: impl IntoIterator<Item = FileDiff>) {
845        for replacement in files {
846            // File ids match list indices for the originally decoded document;
847            // fall back to a scan when a refetch has perturbed that.
848            let existing = match self.document.files.get_mut(*replacement.id) {
849                Some(existing) if existing.id == replacement.id => Some(existing),
850                _ => self
851                    .document
852                    .files
853                    .iter_mut()
854                    .find(|file| file.id == replacement.id),
855            };
856            if let Some(existing) = existing {
857                *existing = replacement;
858            }
859        }
860        self.pending_highlights.clear();
861        self.hunk_highlight_sources.clear();
862        // Loaded sources are keyed by blob, not by file, so they stay valid
863        // across replacement. A file that now points at a blob never loaded
864        // simply misses the lookup and falls back to its hunk source.
865        self.word_diffs.clear();
866        self.rebuild_index();
867    }
868
869    /// Replaces visibility-filtered file diffs while preserving hunk focus and scroll.
870    pub fn replace_file_diffs_anchored(
871        &mut self,
872        files: impl IntoIterator<Item = FileDiff>,
873        area: Rect,
874    ) {
875        let hunk_focus = self.hunk_focus.clone();
876        let visible_rows = self.layout(area).diff.rows;
877        let focus = self.state.focus;
878        let anchor = self.focus_anchor(visible_rows);
879        let predecessors = self.focused_hunk_predecessors();
880        let active = self.active_file();
881        self.replace_file_diffs(files);
882        // Restore remembered entries before the view so a focus recorded while
883        // restoring a visible predecessor remains the newest value.
884        self.hunk_focus.extend(hunk_focus);
885        self.restore_view(focus, anchor, &predecessors, active, area);
886    }
887
888    /// Returns whether the active file is expanded to its full source.
889    pub fn is_full_file(&self) -> bool {
890        self.active_file()
891            .is_some_and(|file| self.context.is_expanded(file))
892    }
893
894    /// Prepares a repo refetch request for an asynchronous context update.
895    pub fn context_request(&self, change: ContextChange) -> Option<ContextRequest> {
896        let active = self.active_file();
897        let file_ids = self.context_file_ids(active);
898        let plan = self.context.plan(change, &file_ids, &self.document)?;
899        if plan.files.is_empty() {
900            return None;
901        }
902
903        let originals = self
904            .document
905            .files
906            .iter()
907            .filter(|file| file_ids.contains(&file.id))
908            .cloned()
909            .collect();
910        Some(ContextRequest {
911            next_context: plan.state,
912            files: plan.files,
913            originals,
914            context_lines: plan.context_lines,
915            next_ids: context::next_ids(&self.document.files),
916        })
917    }
918
919    /// Applies a completed asynchronous context update.
920    pub fn apply_context_update(&mut self, update: ContextUpdate, area: Rect) -> bool {
921        if update.files.is_empty() {
922            return false;
923        }
924        let before = self.state.clone();
925        let focus = self.state.focus;
926        let visible_rows = self.layout(area).diff.rows;
927        let focus_anchor = self.focus_anchor(visible_rows);
928        let predecessors = self.focused_hunk_predecessors();
929        let active = self.active_file();
930        self.context = update.next_context;
931        self.expanded_context = update.expanded_context;
932        self.replace_file_diffs(update.files);
933        self.restore_view(focus, focus_anchor, &predecessors, active, area);
934        self.state != before
935    }
936
937    /// Restores focus and scroll after replacing rendered diff contents.
938    fn restore_view(
939        &mut self,
940        focus: Option<DiffFocus>,
941        focus_anchor: Option<(DiffFocus, usize)>,
942        predecessors: &[HunkId],
943        active: Option<FileId>,
944        area: Rect,
945    ) {
946        if focus.is_some_and(|focus| !self.has_focus(focus)) {
947            self.set_focus(
948                predecessors
949                    .iter()
950                    .rev()
951                    .copied()
952                    .map(DiffFocus::Hunk)
953                    .find(|focus| self.has_focus(*focus))
954                    .or_else(|| self.document.commit.is_some().then_some(DiffFocus::Commit))
955                    .or_else(|| active.map(DiffFocus::File)),
956            );
957        }
958        let layout = self.layout(area);
959        let visible_rows = layout.diff.rows;
960        let offset = focus_anchor
961            .and_then(|anchor| self.focus_anchor_offset(anchor))
962            .unwrap_or(self.state.scroll.offset);
963
964        self.state
965            .scroll
966            .set_offset(offset, self.scroll_rows(visible_rows), visible_rows);
967        if layout.tree.is_some() {
968            self.sync_file_tree();
969        }
970    }
971
972    /// Returns hunk identities before the focused hunk in document order.
973    fn focused_hunk_predecessors(&self) -> Vec<HunkId> {
974        let Some(DiffFocus::Hunk(focused)) = self.state.focus else {
975            return Vec::new();
976        };
977        self.document
978            .files
979            .iter()
980            .flat_map(|file| file.hunks.iter())
981            .map(|hunk| hunk.id)
982            .take_while(|hunk| *hunk != focused)
983            .collect()
984    }
985
986    /// Returns a visible commit or hunk focus and its terminal row.
987    fn focus_anchor(&self, visible_rows: usize) -> Option<(DiffFocus, usize)> {
988        let focus = self.state.focus?;
989        self.focus_targets(FocusFilter::HunkNavigation)
990            .into_iter()
991            .find(|target| target.focus == focus)
992            .and_then(|target| target.row.checked_sub(self.state.scroll.offset))
993            .filter(|screen_row| *screen_row < visible_rows)
994            .map(|screen_row| (focus, screen_row))
995    }
996
997    /// Returns the scroll offset that restores a captured focus anchor.
998    fn focus_anchor_offset(&self, anchor: (DiffFocus, usize)) -> Option<usize> {
999        let (focus, screen_row) = anchor;
1000        self.focus_targets(FocusFilter::HunkNavigation)
1001            .into_iter()
1002            .find(|target| target.focus == focus)
1003            .map(|target| target.row.saturating_sub(screen_row))
1004    }
1005
1006    /// Returns whether a focus target is visible in the current document.
1007    fn has_focus(&self, focus: DiffFocus) -> bool {
1008        match focus {
1009            DiffFocus::Commit => self.document.commit.is_some(),
1010            DiffFocus::File(file) => self.index.files.iter().any(|indexed| {
1011                self.document
1012                    .files
1013                    .get(indexed.file_index)
1014                    .is_some_and(|candidate| candidate.id == file)
1015            }),
1016            DiffFocus::Hunk(hunk) => self.index.files.iter().any(|indexed| {
1017                self.document
1018                    .files
1019                    .get(indexed.file_index)
1020                    .is_some_and(|file| file.hunks.iter().any(|candidate| candidate.id == hunk))
1021            }),
1022        }
1023    }
1024
1025    /// Returns the files targeted by a context change.
1026    fn context_file_ids(&self, active: Option<FileId>) -> Vec<FileId> {
1027        active
1028            .filter(|id| self.document.files.iter().any(|file| file.id == *id))
1029            .or_else(|| self.document.files.first().map(|file| file.id))
1030            .into_iter()
1031            .collect()
1032    }
1033
1034    /// Sets the first visible rendered row.
1035    pub fn set_scroll(&mut self, scroll: usize) {
1036        self.state.scroll = Viewport::from_offset(scroll);
1037    }
1038
1039    /// Sets the focused file or hunk.
1040    pub fn set_focus(&mut self, focus: Option<DiffFocus>) {
1041        let focus = focus.filter(|focus| self.has_focus(*focus));
1042        if let Some(DiffFocus::Hunk(hunk)) = focus
1043            && let Some(file) = self
1044                .document
1045                .files
1046                .iter()
1047                .find(|file| file.hunks.iter().any(|candidate| candidate.id == hunk))
1048        {
1049            self.hunk_focus.insert(file.id, hunk);
1050        }
1051        self.state.focus = focus;
1052    }
1053
1054    /// Returns the file containing the current focus.
1055    pub fn focused_file(&self) -> Option<FileId> {
1056        match self.state.focus? {
1057            DiffFocus::Commit => None,
1058            DiffFocus::File(file) => Some(file),
1059            DiffFocus::Hunk(hunk) => self
1060                .document
1061                .files
1062                .iter()
1063                .find(|file| file.hunks.iter().any(|candidate| candidate.id == hunk))
1064                .map(|file| file.id),
1065        }
1066    }
1067
1068    /// Returns the focused file, or the first visible file when focus is unset.
1069    fn active_file(&self) -> Option<FileId> {
1070        self.focused_file().or_else(|| self.visible_file())
1071    }
1072
1073    /// Returns the file occupying the first visible diff row.
1074    fn visible_file(&self) -> Option<FileId> {
1075        self.file_row_location(self.state.scroll.offset)
1076            .map(|location| location.file.id)
1077            .or_else(|| self.document.files.first().map(|file| file.id))
1078    }
1079
1080    /// Returns rendered rows plus trailing space needed to top-anchor the final file.
1081    fn scroll_rows(&self, visible_rows: usize) -> usize {
1082        let last_file_start = self.index.files.last().map_or(0, |file| file.start);
1083
1084        self.index
1085            .rows
1086            .max(last_file_start.saturating_add(visible_rows))
1087    }
1088
1089    /// Returns rendered rows plus trailing space needed by `scroll`.
1090    fn render_rows_for(&self, scroll: usize, visible_rows: usize) -> usize {
1091        self.index.rows.max(scroll.saturating_add(visible_rows))
1092    }
1093
1094    /// Shows `file` in the diff view without moving the file-tree cursor.
1095    fn show_file(&mut self, file: FileId, visible_rows: usize) {
1096        let Some(row) = self.index.files.iter().find_map(|indexed| {
1097            let candidate = self.document.files.get(indexed.file_index)?;
1098
1099            (candidate.id == file).then_some(indexed.start)
1100        }) else {
1101            return;
1102        };
1103        self.set_focus(Some(DiffFocus::File(file)));
1104        self.state
1105            .scroll
1106            .set_offset(row, self.scroll_rows(visible_rows), visible_rows);
1107    }
1108
1109    /// Focuses the remembered or first hunk in `file` and keeps it visible.
1110    fn focus_file(&mut self, file: FileId, visible_rows: usize) {
1111        let was_hunk_focused = matches!(self.state.focus, Some(DiffFocus::Hunk(_)));
1112        let remembered = self.hunk_focus.get(&file).copied();
1113        let focus = self
1114            .document
1115            .files
1116            .iter()
1117            .find(|candidate| candidate.id == file)
1118            .and_then(|file| {
1119                remembered
1120                    .filter(|hunk| file.hunks.iter().any(|candidate| candidate.id == *hunk))
1121                    .or_else(|| file.hunks.first().map(|hunk| hunk.id))
1122            })
1123            .map_or(DiffFocus::File(file), DiffFocus::Hunk);
1124        let filter = if matches!(focus, DiffFocus::Hunk(_)) {
1125            FocusFilter::HunkNavigation
1126        } else {
1127            FocusFilter::File
1128        };
1129        let Some(target) = self
1130            .focus_targets(filter)
1131            .into_iter()
1132            .find(|target| target.focus == focus)
1133        else {
1134            return;
1135        };
1136
1137        self.set_focus(Some(focus));
1138        let current = self.state.scroll.offset;
1139        let preserved = target.scroll_offset(current, visible_rows, HunkScroll::Preserve);
1140        let placement = if preserved == current || was_hunk_focused {
1141            HunkScroll::Preserve
1142        } else {
1143            HunkScroll::Center
1144        };
1145        let next = target.scroll_offset(current, visible_rows, placement);
1146        self.state
1147            .scroll
1148            .set_offset(next, self.scroll_rows(visible_rows), visible_rows);
1149    }
1150
1151    /// Updates the file-tree cursor to the focused or visible diff file.
1152    fn sync_file_tree(&mut self) {
1153        if let Some(file) = self.active_file() {
1154            self.file_tree.select_file(file);
1155        }
1156    }
1157
1158    /// Renders the current frame into `buf`.
1159    pub fn render(&mut self, area: Rect, buf: &mut Buffer) {
1160        if area.is_empty() {
1161            return;
1162        }
1163        let layout = self.layout(area);
1164        if let Some(tree) = layout.tree {
1165            self.render_file_tree(tree, buf);
1166        }
1167        self.render_diff(layout.diff, buf);
1168    }
1169
1170    /// Returns the viewport layout for `area`.
1171    fn layout(&self, area: Rect) -> DiffLayout {
1172        if self.options.file_tree != FileTreeMode::Auto
1173            || self.file_tree_visibility == FileTreeVisibility::Hidden
1174            || self.document.files.is_empty()
1175        {
1176            return DiffLayout {
1177                diff: area,
1178                tree: None,
1179            };
1180        }
1181
1182        let tree_cols = self.file_tree.cols(area.cols);
1183        if self.file_tree_visibility == FileTreeVisibility::Auto
1184            && area
1185                .cols
1186                .saturating_sub(tree_cols.saturating_add(tree::GAP_COLS))
1187                < tree::MIN_DIFF_COLS
1188        {
1189            return DiffLayout {
1190                diff: area,
1191                tree: None,
1192            };
1193        }
1194
1195        let [tree, _, diff] = tui::layout::Layout::new(tui::Direction::Horizontal)
1196            .child(tui::Length::Fixed(tree_cols))
1197            .child(tui::Length::Fixed(tree::GAP_COLS))
1198            .child(tui::Length::Fill(1))
1199            .areas(area);
1200
1201        DiffLayout {
1202            diff,
1203            tree: Some(tree),
1204        }
1205    }
1206
1207    /// Renders the file tree.
1208    fn render_file_tree(&mut self, area: Rect, buf: &mut Buffer) {
1209        let active_file = self.visible_file();
1210        self.file_tree.draw(
1211            active_file,
1212            self.options.diff_palette,
1213            self.decorator.as_deref(),
1214            area,
1215            buf,
1216        );
1217    }
1218
1219    /// Renders the main diff view into `buf`.
1220    fn render_diff(&mut self, area: Rect, buf: &mut Buffer) {
1221        let body_cols = ScrollView::body_cols(area);
1222        // Rebuild preamble for the available body width so line wrapping matches
1223        // current viewport size.
1224        let preamble_rows = self.preamble.len();
1225        self.preamble = Self::preamble(self.document.commit.as_ref(), body_cols);
1226
1227        if self.preamble.len() != preamble_rows {
1228            self.rebuild_index();
1229        }
1230        let scroll = self.state.scroll.offset;
1231        let sticky = self.sticky_rows(scroll, area.rows, body_cols);
1232        // Body offset skips sticky rows so the main diff starts below the fixed
1233        // header strip.
1234        let body_offset = scroll.saturating_add(sticky.len().min(area.rows));
1235        let render_rows = self.render_rows_for(scroll, area.rows);
1236
1237        ScrollView::virtualized(render_rows, body_offset, |row, cols| {
1238            self.render_row(row, cols)
1239                .map(|row| row.line)
1240                .unwrap_or_default()
1241        })
1242        .sticky(sticky)
1243        .scrollbar_view(View::new(scroll, render_rows, area.rows))
1244        .scrollbar(Self::scrollbar_style())
1245        .render(area, buf);
1246    }
1247
1248    /// Applies an action to the viewer state.
1249    pub fn apply(&mut self, action: DiffAction, area: Rect) -> ViewChange {
1250        let before = self.state.clone();
1251        let before_visibility = self.file_tree_visibility;
1252        let before_file_tree = self.file_tree.state().clone();
1253        let layout = self.layout(area);
1254        let diff = layout.diff;
1255
1256        if layout.tree.is_none()
1257            && matches!(
1258                action,
1259                DiffAction::MoveFileTree(_)
1260                    | DiffAction::ShowFileTreeTarget
1261                    | DiffAction::ActivateFileTreeTarget
1262                    | DiffAction::CollapseFileTreeFolder
1263                    | DiffAction::ExpandFileTreeFolder,
1264            )
1265        {
1266            return ViewChange::Unchanged;
1267        }
1268
1269        match action {
1270            DiffAction::Scroll(scroll) => {
1271                let previous = self.state.scroll.offset;
1272                self.state
1273                    .scroll
1274                    .scroll(scroll, self.scroll_rows(diff.rows), diff.rows);
1275                if self.state.scroll.offset != previous
1276                    && let Some(file) = self.visible_file()
1277                {
1278                    if !matches!(self.state.focus, Some(DiffFocus::Hunk(_))) {
1279                        self.set_focus(Some(DiffFocus::File(file)));
1280                    }
1281                    if layout.tree.is_some() {
1282                        self.file_tree.select_file(file);
1283                    }
1284                }
1285            }
1286            DiffAction::Resize => {
1287                self.state
1288                    .scroll
1289                    .clamp(self.scroll_rows(diff.rows), diff.rows);
1290                if layout.tree.is_some() {
1291                    self.sync_file_tree();
1292                }
1293            }
1294            DiffAction::FocusNext => {
1295                self.focus(diff.rows, 1, FocusFilter::File);
1296                self.sync_file_tree();
1297            }
1298            DiffAction::FocusPrevious => {
1299                self.focus(diff.rows, -1, FocusFilter::File);
1300                self.sync_file_tree();
1301            }
1302            DiffAction::NextHunk => {
1303                self.focus(diff.rows, 1, FocusFilter::HunkNavigation);
1304                if self.state.focus != before.focus {
1305                    self.sync_file_tree();
1306                }
1307            }
1308            DiffAction::PreviousHunk => {
1309                self.focus(diff.rows, -1, FocusFilter::HunkNavigation);
1310                if self.state.focus != before.focus {
1311                    self.sync_file_tree();
1312                }
1313            }
1314            DiffAction::ToggleFileTree => match self.file_tree_visibility {
1315                FileTreeVisibility::Hidden => {
1316                    self.file_tree_visibility = FileTreeVisibility::Visible;
1317                    if self.layout(area).tree.is_some() {
1318                        self.sync_file_tree();
1319                    }
1320                }
1321                FileTreeVisibility::Auto | FileTreeVisibility::Visible if layout.tree.is_some() => {
1322                    self.file_tree_visibility = FileTreeVisibility::Hidden;
1323                }
1324                FileTreeVisibility::Auto => {
1325                    self.file_tree_visibility = FileTreeVisibility::Visible;
1326                    if self.layout(area).tree.is_some() {
1327                        self.sync_file_tree();
1328                    }
1329                }
1330                FileTreeVisibility::Visible => {
1331                    self.file_tree_visibility = FileTreeVisibility::Hidden;
1332                }
1333            },
1334            DiffAction::MoveFileTree(delta) => {
1335                if self.file_tree.state().selected().is_none() {
1336                    self.file_tree.enter(self.visible_file());
1337                }
1338                if let Some(file) = self.file_tree.select(delta) {
1339                    self.show_file(file, diff.rows);
1340                }
1341            }
1342            DiffAction::ShowFileTreeTarget => {
1343                if let Some(file) = self.file_tree.selected_file() {
1344                    self.focus_file(file, diff.rows);
1345                }
1346            }
1347            DiffAction::ActivateFileTreeTarget => {
1348                if let Some(file) = self.file_tree.activate_target() {
1349                    self.show_file(file, diff.rows);
1350                }
1351            }
1352            DiffAction::CollapseFileTreeFolder => {
1353                self.file_tree.collapse_folder();
1354            }
1355            DiffAction::ExpandFileTreeFolder => {
1356                self.file_tree.expand_folder();
1357            }
1358        }
1359
1360        if self.state == before
1361            && self.file_tree_visibility == before_visibility
1362            && *self.file_tree.state() == before_file_tree
1363        {
1364            ViewChange::Unchanged
1365        } else {
1366            ViewChange::Changed
1367        }
1368    }
1369
1370    /// Applies one input event to the viewer.
1371    ///
1372    /// Context-changing keys (`.`, `,`, `x`) are handled by the session loop,
1373    /// which refetches diffs off the terminal thread, so they fall through here.
1374    pub fn handle_input(&mut self, event: Event<()>, area: Rect) -> Control {
1375        let action = match event {
1376            Event::Key(Key::Char('q')) => return Control::Quit,
1377            Event::Key(Key::Char('`')) => DiffAction::ToggleFileTree,
1378            Event::Resize(_) => DiffAction::Resize,
1379            Event::Mouse(Mouse::Press {
1380                button: MouseButton::WheelDown,
1381                ..
1382            }) => DiffAction::Scroll(Scroll::Lines(WHEEL_SCROLL_ROWS)),
1383            Event::Mouse(Mouse::Press {
1384                button: MouseButton::WheelUp,
1385                ..
1386            }) => DiffAction::Scroll(Scroll::Lines(-WHEEL_SCROLL_ROWS)),
1387            Event::Mouse(Mouse::Press {
1388                button: MouseButton::Left,
1389                at,
1390                ..
1391            }) => {
1392                let Some(tree) = self.layout(area).tree else {
1393                    return Control::Continue;
1394                };
1395                let action = match self.file_tree.select_at(tree, at) {
1396                    Some(tree::FileTreeClick::Disclosure) => return Control::Redraw,
1397                    Some(tree::FileTreeClick::Row) => DiffAction::ShowFileTreeTarget,
1398                    None => return Control::Continue,
1399                };
1400                self.apply(action, area);
1401                return Control::Redraw;
1402            }
1403            Event::Key(Key::Esc) => return Control::Quit,
1404            Event::Key(Key::Char('n')) => DiffAction::FocusNext,
1405            Event::Key(Key::Char('p')) => DiffAction::FocusPrevious,
1406            Event::Key(Key::Char('j') | Key::Down) => {
1407                DiffAction::Scroll(Scroll::Lines(LINE_SCROLL_ROWS))
1408            }
1409            Event::Key(Key::Char('k') | Key::Up) => {
1410                DiffAction::Scroll(Scroll::Lines(-LINE_SCROLL_ROWS))
1411            }
1412            Event::Key(Key::Char('J')) => DiffAction::MoveFileTree(1),
1413            Event::Key(Key::Char('K')) => DiffAction::MoveFileTree(-1),
1414            Event::Key(Key::Char('H')) => DiffAction::ExpandFileTreeFolder,
1415            Event::Key(Key::Char('L')) => DiffAction::CollapseFileTreeFolder,
1416            Event::Key(Key::Char(' ') | Key::PageDown) => DiffAction::Scroll(Scroll::Pages(1)),
1417            Event::Key(Key::PageUp) => DiffAction::Scroll(Scroll::Pages(-1)),
1418            Event::Key(Key::Ctrl('d')) => {
1419                DiffAction::Scroll(Scroll::Lines((area.rows / 2).max(1) as isize))
1420            }
1421            Event::Key(Key::Ctrl('u')) => {
1422                DiffAction::Scroll(Scroll::Lines(-((area.rows / 2).max(1) as isize)))
1423            }
1424            Event::Key(Key::Char('g') | Key::Home) => DiffAction::Scroll(Scroll::Top),
1425            Event::Key(Key::Char('G') | Key::End) => DiffAction::Scroll(Scroll::Bottom),
1426            _ => return Control::Continue,
1427        };
1428        match self.apply(action, area) {
1429            ViewChange::Changed => Control::Redraw,
1430            ViewChange::Unchanged => Control::Continue,
1431        }
1432    }
1433
1434    /// Returns highlight requests for visible source rows.
1435    pub fn visible_highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
1436        let window = self.highlight_window(area);
1437        self.highlight_requests_in(window.start..window.visible_end)
1438    }
1439
1440    /// Returns highlight requests for one viewport after the visible rows.
1441    pub fn lookahead_highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
1442        let window = self.highlight_window(area);
1443        self.highlight_requests_in(window.visible_end..window.lookahead_end)
1444    }
1445
1446    /// Returns highlight requests for visible source rows plus one viewport of lookahead.
1447    pub fn highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
1448        let window = self.highlight_window(area);
1449        self.highlight_requests_in(window.start..window.lookahead_end)
1450    }
1451
1452    /// Returns the row ranges used for visible and lookahead highlighting.
1453    fn highlight_window(&self, area: Rect) -> HighlightWindow {
1454        let diff = self.layout(area).diff;
1455        let view = View::new(
1456            self.state.scroll.offset,
1457            self.render_rows_for(self.state.scroll.offset, diff.rows),
1458            diff.rows,
1459        );
1460        let start = view
1461            .offset
1462            .saturating_add(self.sticky_row_count(view.offset, diff.rows));
1463        let visible_end = view.offset.saturating_add(diff.rows);
1464
1465        HighlightWindow {
1466            start,
1467            visible_end,
1468            lookahead_end: visible_end.saturating_add(diff.rows),
1469        }
1470    }
1471
1472    /// Returns highlight requests for one absolute row range.
1473    fn highlight_requests_in(&mut self, rows: Range<usize>) -> Vec<HighlightRequest> {
1474        let mut requests = Vec::new();
1475
1476        for row in rows {
1477            let Some(meta) = self.diff_meta_at(row) else {
1478                continue;
1479            };
1480            let key = self.key_for(&meta);
1481            if self.highlights.contains_key(&key) || self.pending_highlights.contains(&key) {
1482                continue;
1483            }
1484            self.pending_highlights.insert(key.clone());
1485            let source = self.highlight_source_for(&meta);
1486            requests.push(HighlightRequest {
1487                key,
1488                hunk: meta.hunk,
1489                row: meta.row,
1490                path: meta.path,
1491                source,
1492            });
1493        }
1494        requests
1495    }
1496
1497    /// Marks unprocessed highlight requests as requestable again.
1498    pub fn cancel_highlights(&mut self, requests: impl IntoIterator<Item = HighlightRequest>) {
1499        for request in requests {
1500            self.pending_highlights.remove(&request.key);
1501        }
1502    }
1503
1504    /// Makes every pending highlight request eligible to be queued again.
1505    pub fn retry_pending_highlights(&mut self) {
1506        self.pending_highlights.clear();
1507    }
1508
1509    /// Returns the highlight-cache key for one diff row.
1510    fn key_for(&self, meta: &DiffLineMeta) -> HighlightKey {
1511        HighlightKey::new(HighlightKeyInput {
1512            file: meta.file,
1513            side: meta.side,
1514            source_line: meta.source_line,
1515            text: &meta.text,
1516            syntax: self.options.syntax.as_deref(),
1517            theme: &self.options.theme,
1518        })
1519    }
1520
1521    /// Returns hunk-side source context for a highlighted row.
1522    ///
1523    /// Hunk sources are cached on the viewer so scrolling through a hunk does
1524    /// not rebuild its source text on every highlight-request batch.
1525    fn highlight_source_for(&mut self, meta: &DiffLineMeta) -> HighlightSource {
1526        if meta.kind == DiffLineKind::NoNewline {
1527            return meta.single_row_source();
1528        }
1529        let key = (meta.file, meta.hunk, meta.side);
1530        if let Some(source) = self.hunk_highlight_sources.get(&key) {
1531            return source.clone();
1532        }
1533        let source = self.build_highlight_source(meta);
1534        self.hunk_highlight_sources.insert(key, source.clone());
1535        source
1536    }
1537
1538    /// Builds source text for one hunk side.
1539    ///
1540    /// The whole-file blob is preferred so the tokenizer reaches the hunk with
1541    /// the parser state its enclosing lines produce. Requests sharing a blob
1542    /// also share one tokenizer cache downstream, so the prefix is walked once
1543    /// per file rather than once per hunk.
1544    fn build_highlight_source(&self, meta: &DiffLineMeta) -> HighlightSource {
1545        let Some(file) = self.document.files.iter().find(|file| file.id == meta.file) else {
1546            return meta.single_row_source();
1547        };
1548        let Some(hunk) = file.hunks.iter().find(|hunk| hunk.id == meta.hunk) else {
1549            return meta.single_row_source();
1550        };
1551        if let Some(source) = self.file_source(file, meta.side) {
1552            // Rendered rows come from the source, so a source that disagrees
1553            // with the patch would show text the patch never contained. The
1554            // whole hunk is checked because one source is cached for all of it.
1555            if source.matches_hunk(hunk, meta.side) {
1556                return source.clone();
1557            }
1558        }
1559        hunk.highlight_source(meta.side)
1560    }
1561
1562    /// Returns whole-file source text for one file side, when it was loaded.
1563    fn file_source(&self, file: &FileDiff, side: DiffSide) -> Option<&HighlightSource> {
1564        let oid = match side {
1565            DiffSide::Old => file.header.old_oid,
1566            DiffSide::New => file.header.new_oid,
1567        };
1568        if let Some(text) = oid.and_then(|oid| self.blob_sources.get(&oid)) {
1569            return Some(text);
1570        }
1571        // Only the new side of a worktree diff lacks a blob; the old side is
1572        // always a committed object.
1573        if side == DiffSide::New && oid.is_none() {
1574            return file
1575                .header
1576                .new_path
1577                .as_ref()
1578                .and_then(|path| self.worktree_sources.get(path));
1579        }
1580        None
1581    }
1582
1583    /// Merges highlighted rows and returns whether a redraw is needed.
1584    ///
1585    /// The word-diff overlay is applied here, once, so the cached `Line` is
1586    /// ready to render with no per-frame merge work. All paths that write to the
1587    /// cached highlighted rows keep this invariant: cached lines are render-ready
1588    /// and already overlaid.
1589    pub fn apply_highlights(&mut self, results: impl IntoIterator<Item = HighlightResult>) -> bool {
1590        let mut changed = false;
1591        for result in results {
1592            self.pending_highlights.remove(&result.key);
1593
1594            let Some(hunk) = self
1595                .document
1596                .files
1597                .iter()
1598                .find(|f| f.id == result.key.file)
1599                .and_then(|f| f.hunks.iter().find(|h| h.id == result.hunk))
1600            else {
1601                continue;
1602            };
1603            let Some(source) = hunk.lines.iter().find(|line| line.id == result.row) else {
1604                continue;
1605            };
1606            // An empty highlight for a non-empty row means the highlighter
1607            // produced nothing useful; keep the plain source text instead.
1608            if !source.text.is_empty() && result.line.width() == 0 {
1609                continue;
1610            }
1611
1612            if let Entry::Vacant(slot) = self.word_diffs.entry(result.hunk) {
1613                slot.insert(crate::word::compute(hunk));
1614            }
1615            let bg = match result.key.side {
1616                DiffSide::New => self.options.diff_palette.positive_word_bg,
1617                DiffSide::Old => self.options.diff_palette.negative_word_bg,
1618            };
1619            let line = if let Some(ranges) = self
1620                .word_diffs
1621                .get(&result.hunk)
1622                .and_then(|changes| changes.get(&result.row))
1623            {
1624                result.line.overlay_ranges(ranges, Style::default().bg(bg))
1625            } else {
1626                result.line
1627            };
1628            self.highlights.insert(result.key, line);
1629            changed = true;
1630        }
1631        changed
1632    }
1633
1634    /// Highlights currently visible source rows through `highlighter`.
1635    ///
1636    /// Event-loop owners can still use [`Self::highlight_requests`] and
1637    /// [`Self::apply_highlights`] directly when highlight work runs
1638    /// asynchronously.
1639    pub fn apply_visible_highlights<H>(&mut self, area: Rect, highlighter: &mut H) -> bool
1640    where
1641        H: DiffHighlighter + ?Sized,
1642    {
1643        let requests = self.highlight_requests(area);
1644        if requests.is_empty() {
1645            return false;
1646        }
1647        self.apply_highlights(highlighter.highlight_batch(requests))
1648    }
1649
1650    /// Returns the row count for one file card.
1651    fn file_rows(&self, file: &FileDiff) -> usize {
1652        file.rendered_rows(self.hunk_gaps(file.id))
1653    }
1654
1655    /// Returns whether a file needs synthetic rows between review hunks.
1656    fn hunk_gaps(&self, file: FileId) -> HunkGaps {
1657        if self.context.is_expanded(file) {
1658            HunkGaps::Hidden
1659        } else {
1660            HunkGaps::Visible
1661        }
1662    }
1663
1664    /// Returns one rendered row by global row index.
1665    fn render_row(&self, row: usize, cols: usize) -> Option<RenderRow> {
1666        let cols = cols.max(MIN_RENDER_COLS);
1667        if let Some(line) = self.preamble.get(row) {
1668            let line = line.clone();
1669            let line = if self.dims_unfocused(DiffFocus::Commit) {
1670                Self::muted_line(line)
1671            } else {
1672                line
1673            };
1674            return Some(RenderRow { line, diff: None });
1675        }
1676        self.file_row_location(row)
1677            .map(|location| self.render_file_row(location, cols))
1678    }
1679
1680    /// Returns one rendered row inside a file card.
1681    fn render_file_row(&self, location: FileRowLocation<'_>, cols: usize) -> RenderRow {
1682        let file = location.file;
1683        let border = FILE_BORDER;
1684        let inner_cols = cols.saturating_sub(2);
1685        let child_cols = cols.saturating_sub(4);
1686        let local = location.local;
1687        let bottom = location.end - location.start - 1;
1688        // Child rows are full-width content lines rendered inside a bordered card.
1689        let wrap_child = |mut line: Line| {
1690            Line::truncate(&mut line, child_cols, "โ€ฆ");
1691            Line::pad(&mut line, child_cols);
1692            Line::new(border.left(1)).extend(line).item(border.right(1))
1693        };
1694        // Dedicated hunk-gap marker row keeps spacing between non-adjacent hunks.
1695        let hunk_gap_line = Line::blank()
1696            .extend(Line::blank().padded(REVIEW_GUTTER_WIDTH))
1697            .extend(Line::blank().padded(LINE_NUMBER_WIDTH))
1698            .extend(Line::blank().padded(LINE_NUMBER_WIDTH))
1699            .extend(Self::marker_cell(HUNK_GAP_MARKER_CELL, colors::rgb::DIM));
1700
1701        match local {
1702            FILE_TOP_ROW => {
1703                return RenderRow {
1704                    line: border.top(inner_cols),
1705                    diff: None,
1706                };
1707            }
1708            FILE_HEADER_ROW => {
1709                let decoration = self.file_decoration(file.id);
1710                let summary = self
1711                    .summaries
1712                    .get(&file.id)
1713                    .copied()
1714                    .unwrap_or_else(|| FileSummary::from(file));
1715                return RenderRow {
1716                    line: wrap_child(file.header_line(
1717                        child_cols,
1718                        self.options.diff_palette,
1719                        &decoration,
1720                        summary,
1721                    )),
1722                    diff: None,
1723                };
1724            }
1725            row if row == bottom => {
1726                return RenderRow {
1727                    line: border.bottom(inner_cols),
1728                    diff: None,
1729                };
1730            }
1731            _ if !file.has_body() => {
1732                return RenderRow {
1733                    line: border.bottom(inner_cols),
1734                    diff: None,
1735                };
1736            }
1737            FILE_DIVIDER_ROW => {
1738                return RenderRow {
1739                    line: border.divider(inner_cols, DIVIDER),
1740                    diff: None,
1741                };
1742            }
1743            _ => {}
1744        }
1745        let mut body_rows = file.hunk_body_rows(self.hunk_gaps(file.id)).peekable();
1746        while let Some(&(hunk, body_start)) = body_rows.peek() {
1747            let body_end = body_start + hunk.lines.len();
1748            if local < body_start {
1749                return RenderRow {
1750                    line: wrap_child(hunk_gap_line),
1751                    diff: None,
1752                };
1753            }
1754            if local < body_end {
1755                let decoration = self.hunk_decoration(file.id, hunk.id);
1756                let mut row =
1757                    self.hunk_row_at(file, hunk, local - body_start, child_cols, &decoration);
1758                // The corner marker is drawn over the hunk's first body row.
1759                if local == body_start {
1760                    row.line = Self::overlay_corner(row.line, &decoration.corner, child_cols);
1761                }
1762                let expanded = row
1763                    .diff
1764                    .as_ref()
1765                    .is_some_and(|meta| self.expanded_context.contains(&meta.row));
1766                if expanded || self.dims_unfocused(DiffFocus::Hunk(hunk.id)) {
1767                    row.line = Self::muted_line(row.line);
1768                }
1769                return RenderRow {
1770                    line: wrap_child(row.line),
1771                    diff: row.diff,
1772                };
1773            }
1774            body_rows.next();
1775        }
1776        RenderRow {
1777            line: border.bottom(inner_cols),
1778            diff: None,
1779        }
1780    }
1781
1782    /// Returns source metadata for one rendered row without building UI lines.
1783    fn diff_meta_at(&self, row: usize) -> Option<DiffLineMeta> {
1784        let location = self.file_row_location(row)?;
1785        for (hunk, body_start) in location
1786            .file
1787            .hunk_body_rows(self.hunk_gaps(location.file.id))
1788        {
1789            let body_end = body_start + hunk.lines.len();
1790            if location.local < body_start {
1791                return None;
1792            }
1793            if location.local < body_end {
1794                return Some(self.hunk_meta_at(location.file, hunk, location.local - body_start));
1795            }
1796        }
1797        None
1798    }
1799
1800    /// Returns the file location for a global rendered row.
1801    fn file_row_location(&self, row: usize) -> Option<FileRowLocation<'_>> {
1802        let files = &self.index.files;
1803        // The file containing `row` is the last one starting at or before it.
1804        let index = files
1805            .partition_point(|indexed| indexed.start <= row)
1806            .checked_sub(1)?;
1807        let indexed = files[index];
1808        let end = files
1809            .get(index + 1)
1810            .map_or(self.index.rows, |next| next.start);
1811        if row >= end {
1812            return None;
1813        }
1814        let file = self.document.files.get(indexed.file_index)?;
1815
1816        Some(FileRowLocation {
1817            file,
1818            start: indexed.start,
1819            end,
1820            local: row - indexed.start,
1821        })
1822    }
1823
1824    /// Rebuilds cached row positions for the current document visibility state.
1825    fn rebuild_index(&mut self) {
1826        let mut rows = self.preamble.len();
1827        let mut files = Vec::new();
1828
1829        for (file_index, file) in self.document.files.iter().enumerate() {
1830            files.push(IndexedFileRows {
1831                file_index,
1832                start: rows,
1833            });
1834            rows += self.file_rows(file);
1835        }
1836        self.index = RowIndex { files, rows };
1837        let document = &self.document;
1838        self.hunk_focus.retain(|file, hunk| {
1839            document.files.iter().any(|candidate| {
1840                candidate.id == *file
1841                    && candidate
1842                        .hunks
1843                        .iter()
1844                        .any(|candidate| candidate.id == *hunk)
1845            })
1846        });
1847        let focus = self.state.focus;
1848        self.set_focus(focus);
1849    }
1850
1851    /// Lays out the commit preamble for the given body width.
1852    fn preamble(commit: Option<&CommitHeader>, cols: usize) -> Vec<Line> {
1853        let Some(commit) = commit else {
1854            return Vec::new();
1855        };
1856        // Normalize the message body first, then trim only outer empty lines.
1857        let message_lines = commit
1858            .message
1859            .split('\n')
1860            .map(|raw| {
1861                let trimmed = raw.trim_end();
1862                trimmed.strip_prefix("    ").unwrap_or(trimmed)
1863            })
1864            .collect::<Vec<_>>();
1865        let message = {
1866            let first_non_empty = message_lines.iter().position(|text| !text.is_empty());
1867            let last_non_empty = message_lines.iter().rposition(|text| !text.is_empty());
1868            if let (Some(start), Some(end)) = (first_non_empty, last_non_empty) {
1869                let lines = &message_lines[start..=end];
1870                let trailer_start = lines
1871                    .iter()
1872                    .rposition(|text| text.is_empty())
1873                    .map(|index| index + 1)
1874                    .filter(|&index| {
1875                        index < lines.len()
1876                            && lines[index..]
1877                                .iter()
1878                                .try_fold(false, |has_trailer, text| {
1879                                    if text.as_bytes().first().is_some_and(u8::is_ascii_whitespace)
1880                                    {
1881                                        has_trailer.then_some(true)
1882                                    } else {
1883                                        text.split_once(':')
1884                                            .is_some_and(|(key, value)| {
1885                                                !key.is_empty()
1886                                                    && !value.trim().is_empty()
1887                                                    && key.chars().all(|character| {
1888                                                        character.is_ascii_alphanumeric()
1889                                                            || character == '-'
1890                                                    })
1891                                            })
1892                                            .then_some(true)
1893                                    }
1894                                })
1895                                .is_some()
1896                    });
1897                lines
1898                    .iter()
1899                    .enumerate()
1900                    .map(|(index, &text)| {
1901                        let line = if text.is_empty() {
1902                            Line::blank()
1903                        } else {
1904                            Line::new(text.to_owned())
1905                        };
1906                        if index == 0 {
1907                            line.style(Style::default().bold())
1908                        } else if trailer_start.is_some_and(|start| index >= start) {
1909                            line.style(Style::new(colors::rgb::DIM))
1910                        } else {
1911                            line
1912                        }
1913                    })
1914                    .collect()
1915            } else {
1916                Vec::new()
1917            }
1918        };
1919        let hash = commit.hash.to_string();
1920        let hash_width = hash.width() + commit.decoration.as_deref().map_or(0, |d| 1 + d.width());
1921        let value_width = std::iter::once(hash_width)
1922            .chain(commit.signature.iter().map(|line| line.as_str().width()))
1923            .chain(commit.headers.iter().map(|h| h.value.as_str().width()))
1924            .max()
1925            .unwrap_or_default();
1926        // Hash row is a two-part component (hash plus optional signature marker).
1927        let hash_line = Line::new(Label::new(hash.as_str()).fg(colors::rgb::ORANGE));
1928        let hash_value = if let Some(decoration) = commit.decoration.as_deref() {
1929            HStack::default()
1930                .child(hash_line)
1931                .spacer()
1932                .child(Line::new(Label::new(decoration).fg(colors::rgb::DIM)))
1933                .to_line(Constraint::tight(value_width))
1934        } else {
1935            hash_line
1936        };
1937        // Commit header table is the base preamble chrome (commit id and metadata rows).
1938        let mut table = Table::<2, Line>::new(TableOptions {
1939            overflow: true,
1940            spacing: 2,
1941            ..TableOptions::default()
1942        })
1943        .row([
1944            Line::new(Label::new("commit").fg(colors::rgb::DIM)),
1945            hash_value,
1946        ]);
1947        for (index, signature) in commit.signature.iter().enumerate() {
1948            let key = if index == 0 { "signature" } else { "" };
1949            table.push([
1950                Line::new(Label::new(key).fg(colors::rgb::DIM)),
1951                Line::new(signature.as_str()),
1952            ]);
1953        }
1954        // One row per commit header key/value, with date kept dim for softer emphasis.
1955        for header in &commit.headers {
1956            let key = header.key.to_ascii_lowercase();
1957            let header_value = if header.key.eq_ignore_ascii_case("date") {
1958                Line::new(header.value.as_str()).style(Style::new(colors::rgb::DIM))
1959            } else {
1960                Line::new(header.value.as_str())
1961            };
1962            table.push([
1963                Line::new(Label::new(&key).fg(colors::rgb::DIM)),
1964                header_value,
1965            ]);
1966        }
1967        // Optional message section is rendered as stacked lines after a divider.
1968        let mut stack = VStack::default()
1969            .bordered(tui::Border::new(colors::FAINT))
1970            .padding(1)
1971            .child(table);
1972
1973        if !message.is_empty() {
1974            stack = stack.divider_cell(Cell::new(DIVIDER, Style::new(colors::FAINT)));
1975            for line in message {
1976                stack.push(line);
1977            }
1978        }
1979        stack.lines(Constraint::tight(cols))
1980    }
1981
1982    /// Returns sticky file-header rows for the current offset.
1983    fn sticky_rows(&self, scroll: usize, visible_rows: usize, cols: usize) -> Vec<Line> {
1984        // Build the fixed sticky header strip directly from current scroll context.
1985        self.sticky_header_rows(scroll, visible_rows)
1986            .map(|sticky| {
1987                (STICKY_HEADER_ROWS - sticky.rows..STICKY_HEADER_ROWS)
1988                    .map(|index| {
1989                        if index == STICKY_HEADER_ROWS - 1 {
1990                            FILE_BORDER.divider(cols.saturating_sub(2), STICKY_DIVIDER)
1991                        } else {
1992                            self.render_row(sticky.start + index, cols)
1993                                .map(|row| row.line)
1994                                .unwrap_or_default()
1995                        }
1996                    })
1997                    .collect()
1998            })
1999            .unwrap_or_default()
2000    }
2001
2002    /// Returns the number of sticky rows for the current offset.
2003    fn sticky_row_count(&self, scroll: usize, visible_rows: usize) -> usize {
2004        self.sticky_header_rows(scroll, visible_rows)
2005            .map_or(0, |sticky| sticky.rows)
2006    }
2007
2008    /// Returns the source row for the sticky header at the current offset.
2009    #[cfg(test)]
2010    fn sticky_start(&self, scroll: usize, visible_rows: usize) -> Option<usize> {
2011        self.sticky_header_rows(scroll, visible_rows)
2012            .map(|sticky| sticky.start)
2013    }
2014
2015    /// Returns the visible sticky header rows at the current offset.
2016    fn sticky_header_rows(&self, scroll: usize, visible_rows: usize) -> Option<StickyHeaderRows> {
2017        let scroll = scroll.min(
2018            self.render_rows_for(scroll, visible_rows)
2019                .saturating_sub(visible_rows),
2020        );
2021        if scroll == 0 {
2022            return None;
2023        }
2024        let location = self.file_row_location(scroll)?;
2025        if scroll <= location.start {
2026            return None;
2027        }
2028        let file_bottom = location.end.saturating_sub(location.start + 1);
2029        let rows = file_bottom
2030            .saturating_sub(location.local)
2031            .min(STICKY_HEADER_ROWS)
2032            .min(visible_rows);
2033        if rows == 0 {
2034            return None;
2035        }
2036        Some(StickyHeaderRows {
2037            start: location.start,
2038            rows,
2039        })
2040    }
2041
2042    /// Focuses a target relative to the current focus.
2043    fn focus(&mut self, visible_rows: usize, delta: isize, filter: FocusFilter) {
2044        let targets = self.focus_targets(filter);
2045        if targets.is_empty() {
2046            return;
2047        }
2048        let current = self
2049            .state
2050            .focus
2051            .and_then(|focus| targets.iter().position(|target| target.focus == focus))
2052            .or_else(|| {
2053                if filter != FocusFilter::File {
2054                    return None;
2055                }
2056                self.focused_file().and_then(|file| {
2057                    targets
2058                        .iter()
2059                        .position(|target| target.focus == DiffFocus::File(file))
2060                })
2061            });
2062        let next = match (current, filter, delta.is_negative()) {
2063            (Some(index), _, true) => index.checked_sub(1),
2064            (Some(index), _, false) => index.checked_add(1).filter(|index| *index < targets.len()),
2065            (None, FocusFilter::HunkNavigation, true) => targets
2066                .partition_point(|target| target.row <= self.state.scroll.offset)
2067                .checked_sub(1),
2068            (None, FocusFilter::HunkNavigation, false) => {
2069                let index = targets.partition_point(|target| target.row < self.state.scroll.offset);
2070                (index < targets.len()).then_some(index)
2071            }
2072            (None, FocusFilter::File, true) => targets.len().checked_sub(1),
2073            (None, FocusFilter::File, false) => Some(0),
2074        };
2075        let Some(target) = next.and_then(|next| targets.get(next)) else {
2076            return;
2077        };
2078        if filter == FocusFilter::File {
2079            let DiffFocus::File(file) = target.focus else {
2080                return;
2081            };
2082            self.focus_file(file, visible_rows);
2083            return;
2084        }
2085        let was_hunk_focused = matches!(self.state.focus, Some(DiffFocus::Hunk(_)));
2086        let focus = target.focus;
2087        self.set_focus(Some(focus));
2088
2089        let current = self.state.scroll.offset;
2090        let preserved = target.scroll_offset(current, visible_rows, HunkScroll::Preserve);
2091        let placement = if preserved == current || was_hunk_focused {
2092            HunkScroll::Preserve
2093        } else {
2094            HunkScroll::Center
2095        };
2096        let next = target.scroll_offset(current, visible_rows, placement);
2097
2098        self.state
2099            .scroll
2100            .set_offset(next, self.scroll_rows(visible_rows), visible_rows);
2101    }
2102
2103    /// Returns focusable targets in rendered row order.
2104    fn focus_targets(&self, filter: FocusFilter) -> Vec<FocusTarget> {
2105        let mut targets = Vec::new();
2106
2107        if filter == FocusFilter::HunkNavigation && self.document.commit.is_some() {
2108            targets.push(FocusTarget {
2109                focus: DiffFocus::Commit,
2110                row: 0,
2111                height: self.preamble.len(),
2112                file_start: 0,
2113            });
2114        }
2115
2116        for indexed in &self.index.files {
2117            let Some(file) = self.document.files.get(indexed.file_index) else {
2118                continue;
2119            };
2120            if filter == FocusFilter::File {
2121                targets.push(FocusTarget {
2122                    focus: DiffFocus::File(file.id),
2123                    row: indexed.start,
2124                    height: 1,
2125                    file_start: indexed.start,
2126                });
2127            }
2128            if filter == FocusFilter::HunkNavigation {
2129                for (hunk, local) in file.hunk_body_rows(self.hunk_gaps(file.id)) {
2130                    let leading = hunk
2131                        .lines
2132                        .iter()
2133                        .take_while(|line| self.expanded_context.contains(&line.id))
2134                        .count();
2135                    let trailing = hunk
2136                        .lines
2137                        .iter()
2138                        .rev()
2139                        .take_while(|line| self.expanded_context.contains(&line.id))
2140                        .count();
2141                    targets.push(FocusTarget {
2142                        focus: DiffFocus::Hunk(hunk.id),
2143                        row: indexed.start + local + leading,
2144                        height: hunk.lines.len().saturating_sub(leading + trailing),
2145                        file_start: indexed.start,
2146                    });
2147                }
2148            }
2149        }
2150        targets
2151    }
2152
2153    /// Returns one rendered row inside a hunk.
2154    fn hunk_row_at(
2155        &self,
2156        file: &FileDiff,
2157        hunk: &crate::Hunk,
2158        line_index: usize,
2159        inner: usize,
2160        decoration: &HunkDecoration,
2161    ) -> RenderRow {
2162        let (old_line, new_line) = Self::hunk_line_numbers(hunk, line_index);
2163        let line = &hunk.lines[line_index];
2164        let meta = DiffLineMeta::new(file, hunk.id, line, old_line, new_line);
2165
2166        self.hunk_row(meta, line, old_line, inner, decoration)
2167    }
2168
2169    /// Returns source metadata for one rendered hunk body row.
2170    fn hunk_meta_at(&self, file: &FileDiff, hunk: &crate::Hunk, line_index: usize) -> DiffLineMeta {
2171        let (old_line, new_line) = Self::hunk_line_numbers(hunk, line_index);
2172        DiffLineMeta::new(file, hunk.id, &hunk.lines[line_index], old_line, new_line)
2173    }
2174
2175    /// Returns the old and new source numbers for one hunk body row.
2176    fn hunk_line_numbers(hunk: &crate::Hunk, line_index: usize) -> (u32, u32) {
2177        let mut old_line = hunk.header.old_line_no;
2178        let mut new_line = hunk.header.new_line_no;
2179        for line in &hunk.lines[..line_index] {
2180            old_line = old_line.saturating_add(line.kind.old_len());
2181            new_line = new_line.saturating_add(line.kind.new_len());
2182        }
2183        (old_line, new_line)
2184    }
2185
2186    /// Returns one rendered hunk row.
2187    fn hunk_row(
2188        &self,
2189        meta: DiffLineMeta,
2190        line: &DiffLine,
2191        old_line: u32,
2192        row_cols: usize,
2193        decoration: &HunkDecoration,
2194    ) -> RenderRow {
2195        let line_number_fg = if matches!(self.state.focus, Some(DiffFocus::Hunk(focused)) if focused == meta.hunk)
2196        {
2197            SELECTED_LINE_NUMBER_FG
2198        } else {
2199            LINE_NUMBER_FG
2200        };
2201        let (cells, source, row_style, source_style) = match line.kind {
2202            DiffLineKind::Addition => (
2203                [
2204                    Self::blank_number(self.options.diff_palette.positive_row_bg),
2205                    Self::number_cell(
2206                        meta.source_line,
2207                        line_number_fg,
2208                        self.options.diff_palette.positive_row_bg,
2209                    ),
2210                    Self::marker_cell(" + ", self.options.diff_palette.positive_fg),
2211                ],
2212                self.rendered_source(&meta),
2213                Style::default().bg(self.options.diff_palette.positive_row_bg),
2214                Style::default().bg(self.options.diff_palette.positive_row_bg),
2215            ),
2216            DiffLineKind::Deletion => (
2217                [
2218                    Self::number_cell(
2219                        meta.source_line,
2220                        line_number_fg,
2221                        self.options.diff_palette.negative_row_bg,
2222                    ),
2223                    Self::blank_number(self.options.diff_palette.negative_row_bg),
2224                    Self::marker_cell(" - ", self.options.diff_palette.negative_fg),
2225                ],
2226                self.rendered_source(&meta),
2227                Style::default().bg(self.options.diff_palette.negative_row_bg),
2228                Style::default()
2229                    .bg(self.options.diff_palette.negative_row_bg)
2230                    .dim(),
2231            ),
2232            DiffLineKind::Context => (
2233                [
2234                    Self::number_cell(old_line, line_number_fg, Color::Unset),
2235                    Self::number_cell(meta.source_line, line_number_fg, Color::Unset),
2236                    Self::marker_cell("   ", Color::Unset),
2237                ],
2238                self.rendered_source(&meta),
2239                Style::default(),
2240                Style::default(),
2241            ),
2242            DiffLineKind::NoNewline => (
2243                [
2244                    Line::blank().padded(LINE_NUMBER_WIDTH),
2245                    Line::blank().padded(LINE_NUMBER_WIDTH),
2246                    Self::marker_cell("   ", Color::Unset),
2247                ],
2248                Line::new(NO_NEWLINE_MARKER).style(Style::default().fg(colors::rgb::DIM)),
2249                Style::default(),
2250                Style::default(),
2251            ),
2252        };
2253        let decoration = HunkRowDecoration {
2254            gutter: if matches!(line.kind, DiffLineKind::Addition | DiffLineKind::Deletion) {
2255                decoration.gutter
2256            } else {
2257                None
2258            },
2259            style: if matches!(self.state.focus, Some(DiffFocus::Hunk(hunk)) if hunk == meta.hunk) {
2260                None
2261            } else {
2262                decoration.style
2263            },
2264        };
2265        let rendered = self.hunk_line(cells, source, row_cols, row_style, source_style, decoration);
2266
2267        RenderRow {
2268            line: rendered,
2269            diff: Some(meta),
2270        }
2271    }
2272
2273    /// Returns a fixed-column hunk row line.
2274    fn hunk_line(
2275        &self,
2276        cells: [Line; 3],
2277        mut source: Line,
2278        row_cols: usize,
2279        row_style: Style,
2280        source_style: Style,
2281        decoration: HunkRowDecoration,
2282    ) -> Line {
2283        let source_cols =
2284            row_cols.saturating_sub(REVIEW_GUTTER_WIDTH + LINE_NUMBER_WIDTH * 2 + MARKER_WIDTH);
2285
2286        if source_cols > 0 {
2287            Line::truncate(&mut source, source_cols, "โ€ฆ");
2288            let source_width = source.width();
2289            if source_width < source_cols {
2290                let padding = " ".repeat(source_cols - source_width);
2291                source.push(Label::new(&padding));
2292            }
2293        }
2294
2295        let source = source.style(source_style);
2296        let body_cols = row_cols.saturating_sub(REVIEW_GUTTER_WIDTH);
2297        let mut body = Line::blank()
2298            .extend(cells[0].clone())
2299            .extend(cells[1].clone())
2300            .extend(cells[2].clone())
2301            .extend(source);
2302
2303        Line::pad(&mut body, body_cols);
2304        Line::truncate(&mut body, body_cols, "โ€ฆ");
2305        body = body.style(row_style);
2306        if let Some(style) = decoration.style {
2307            body = body.style(style);
2308        }
2309        let gutter = decoration.gutter.map_or_else(
2310            || Line::blank().padded(REVIEW_GUTTER_WIDTH),
2311            |paint| Line::new(Label::from_char(paint.item).style(paint.style)),
2312        );
2313        gutter.extend(body)
2314    }
2315
2316    /// Returns the final source-text `Line` for a row, ready to render.
2317    ///
2318    /// Cached entries already include the word-diff overlay (applied once in
2319    /// [`Self::apply_highlights`]). On a cache miss -- the window before the
2320    /// highlight worker responds -- a plain Line is returned; the word-diff
2321    /// background lands once the cached overlaid line arrives.
2322    fn rendered_source(&self, meta: &DiffLineMeta) -> Line {
2323        if let Some(line) = self.highlights.get(&self.key_for(meta)) {
2324            let line = line.clone();
2325            return if meta.text.contains('\t') {
2326                Self::expand_source_tabs(line)
2327            } else {
2328                line
2329            };
2330        }
2331
2332        Self::plain_source_line(meta)
2333    }
2334
2335    /// Returns the unhighlighted source text for a row.
2336    fn plain_source_line(meta: &DiffLineMeta) -> Line {
2337        if meta.text.contains('\t') {
2338            Self::expand_source_tabs(Line::new(meta.text.as_str()))
2339        } else {
2340            Line::new(meta.text.as_str())
2341        }
2342    }
2343
2344    /// Returns a source line with tabs rendered as fixed-width visible cells.
2345    fn expand_source_tabs(line: Line) -> Line {
2346        let mut expanded = Line::blank();
2347        for label in line {
2348            if !label.content().contains('\t') {
2349                expanded.push(label);
2350                continue;
2351            }
2352            let style = label.paint.style();
2353            let tab_style = style.fg(colors::FAINT);
2354            let mut start = 0;
2355            for (index, _) in label.content().match_indices('\t') {
2356                if start < index {
2357                    expanded.push(Label::new(&label.content()[start..index]).style(style));
2358                }
2359                expanded.push(Label::new(SOURCE_TAB_MARKER).style(tab_style));
2360                start = index + 1;
2361            }
2362            if start < label.content().len() {
2363                expanded.push(Label::new(&label.content()[start..]).style(style));
2364            }
2365        }
2366        expanded
2367    }
2368
2369    /// Returns a line-number cell.
2370    fn number_cell(value: u32, foreground: Color, background: Color) -> Line {
2371        Line::new(Label::new(&value.to_string()).fg(foreground).bg(background))
2372            .padded(LINE_NUMBER_WIDTH)
2373    }
2374
2375    /// Returns a blank line-number cell.
2376    fn blank_number(background: Color) -> Line {
2377        Line::new(Label::space().bg(background)).padded(LINE_NUMBER_WIDTH)
2378    }
2379
2380    /// Returns a marker cell.
2381    fn marker_cell(marker: &str, foreground: Color) -> Line {
2382        Line::new(Label::new(marker).fg(foreground)).padded(MARKER_WIDTH)
2383    }
2384
2385    /// Returns whether focus styling should dim an unselected target.
2386    fn dims_unfocused(&self, target: DiffFocus) -> bool {
2387        self.options.hunk_focus == HunkFocus::DimUnfocused
2388            && matches!(self.state.focus, Some(focus) if focus != target)
2389    }
2390
2391    /// Returns a row with every label rendered dimly.
2392    fn muted_line(line: Line) -> Line {
2393        line.into_iter()
2394            .map(|label| {
2395                let style = label
2396                    .paint
2397                    .style()
2398                    .bg(Self::muted_background(label.paint.style().bg_color()))
2399                    .dim();
2400                Label::new(label.content()).style(style)
2401            })
2402            .collect::<Vec<_>>()
2403            .into()
2404    }
2405
2406    /// Returns a darker variant of an inactive hunk background, at half the
2407    /// brightness of the focused one.
2408    fn muted_background(color: Color) -> Color {
2409        match color {
2410            Color::RGB(r, g, b) => Color::RGB(r / 2, g / 2, b / 2),
2411            color => color,
2412        }
2413    }
2414
2415    /// Overlays `corner` onto the right edge of a child-width row line.
2416    ///
2417    /// The hunk row already fills `cols`; truncating to leave room for the
2418    /// corner and re-padding preserves the row background, then the corner is
2419    /// appended so it sits flush in the hunk's top-right corner. A corner that
2420    /// does not fit is dropped rather than truncated.
2421    fn overlay_corner(mut line: Line, corner: &Line, cols: usize) -> Line {
2422        let width = corner.width();
2423        if width == 0 || width >= cols {
2424            return line;
2425        }
2426        let left = cols - width;
2427        Line::truncate(&mut line, left, "โ€ฆ");
2428        Line::pad(&mut line, left);
2429        line.extend(corner.clone())
2430    }
2431
2432    /// Returns the scrollbar style used by diff views.
2433    pub fn scrollbar_style() -> ScrollbarStyle {
2434        ScrollbarStyle::new(
2435            Cell::new(SCROLLBAR_TRACK, Style::default().fg(colors::FAINT)),
2436            Cell::new(SCROLLBAR_THUMB, Style::default().fg(colors::FAINT)),
2437        )
2438    }
2439}
2440
2441impl Widget for DiffViewer {
2442    fn size(&self, parent: Constraint) -> Size {
2443        let cols = if parent.max.cols == usize::MAX {
2444            MIN_RENDER_COLS
2445        } else {
2446            parent.max.cols
2447        };
2448        Size::new(cols, self.index.rows).constrain(parent)
2449    }
2450
2451    fn render(&mut self, area: Rect, buf: &mut Buffer) {
2452        DiffViewer::render(self, area, buf);
2453    }
2454
2455    fn to_buffer(&mut self, constraints: Constraint) -> Buffer {
2456        let size = self.size(constraints);
2457        let area = Rect::from_size(size);
2458        let mut buffer = Buffer::empty(area);
2459
2460        DiffViewer::render(self, area, &mut buffer);
2461
2462        buffer
2463    }
2464}
2465
2466/// Focus target with its rendered row.
2467#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2468struct FocusTarget {
2469    /// Focus value.
2470    focus: DiffFocus,
2471    /// Rendered row index.
2472    row: usize,
2473    /// Rendered height of the focus target.
2474    height: usize,
2475    /// Rendered row where the containing file starts.
2476    file_start: usize,
2477}
2478
2479impl FocusTarget {
2480    /// Returns sticky file-header rows covering a scroll offset.
2481    fn sticky_rows(self, scroll: usize) -> usize {
2482        if scroll > self.file_start {
2483            STICKY_HEADER_ROWS
2484        } else {
2485            0
2486        }
2487    }
2488
2489    /// Returns the scroll offset for placing this target in a viewport.
2490    fn scroll_offset(self, current: usize, visible_rows: usize, placement: HunkScroll) -> usize {
2491        if visible_rows == 0 {
2492            return current;
2493        }
2494        let height = self.height.max(1);
2495        let top = self.row.saturating_sub(self.sticky_rows(self.row));
2496        let leading = self.row.saturating_sub(top);
2497        let available = visible_rows.saturating_sub(leading);
2498        if height > available {
2499            return top;
2500        }
2501
2502        match placement {
2503            HunkScroll::Center => {
2504                let screen_row = leading + available.saturating_sub(height) / 2;
2505
2506                self.row.saturating_sub(screen_row)
2507            }
2508            HunkScroll::Preserve => {
2509                let top = self.sticky_rows(current).saturating_add(1);
2510                let bottom = visible_rows.saturating_sub(1);
2511                let screen_top = self.row.saturating_sub(current);
2512                let screen_bottom = screen_top.saturating_add(height);
2513
2514                if screen_top < top {
2515                    self.row.saturating_sub(top)
2516                } else if screen_bottom > bottom {
2517                    self.row.saturating_add(height).saturating_sub(bottom)
2518                } else {
2519                    current
2520                }
2521            }
2522        }
2523    }
2524}
2525
2526/// Focus target filter.
2527#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2528enum FocusFilter {
2529    /// File targets only.
2530    File,
2531    /// Targets traversed by hunk-navigation actions.
2532    HunkNavigation,
2533}
2534
2535/// Hunk navigation scroll behavior.
2536#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2537enum HunkScroll {
2538    /// Center the focused hunk when possible.
2539    Center,
2540    /// Preserve current scroll while the focused hunk remains comfortably visible.
2541    Preserve,
2542}
2543
2544impl FileDiff {
2545    /// Returns whether this file card should render hunk rows.
2546    fn has_body(&self) -> bool {
2547        !self.hunks.is_empty()
2548    }
2549
2550    /// Returns the rendered row count for this file's card.
2551    fn rendered_rows(&self, gaps: HunkGaps) -> usize {
2552        if !self.has_body() {
2553            return EMPTY_CARD_ROWS;
2554        }
2555        let gaps = match gaps {
2556            HunkGaps::Visible => self.hunks.len().saturating_sub(1),
2557            HunkGaps::Hidden => 0,
2558        };
2559        let body: usize = self.hunks.iter().map(|hunk| hunk.lines.len()).sum();
2560        // top + header + divider + body lines + gaps + bottom.
2561        HUNK_BODY_START + body + gaps + 1
2562    }
2563
2564    /// Returns each hunk together with the local row of its first body line.
2565    fn hunk_body_rows(&self, gaps: HunkGaps) -> impl Iterator<Item = (&Hunk, usize)> + '_ {
2566        self.hunks
2567            .iter()
2568            .enumerate()
2569            .scan(HUNK_BODY_START, move |local, (index, hunk)| {
2570                if index > 0 && gaps == HunkGaps::Visible {
2571                    *local += 1;
2572                }
2573                let row = *local;
2574                *local += hunk.lines.len();
2575                Some((hunk, row))
2576            })
2577    }
2578
2579    /// Returns a file header line, applying any host decoration.
2580    ///
2581    /// The leading marker is the decorated status when the host provides one,
2582    /// and the file-kind marker otherwise.
2583    fn header_line(
2584        &self,
2585        cols: usize,
2586        palette: DiffPalette,
2587        decoration: &FileDecoration,
2588        summary: FileSummary,
2589    ) -> Line {
2590        let mut left = Line::blank();
2591        if let Some(status) = &decoration.status {
2592            left.push(Label::from_char(status.item).style(status.style));
2593        } else {
2594            let fg = match self.header.kind {
2595                FileKind::Added => palette.positive_fg,
2596                FileKind::Deleted => palette.negative_fg,
2597                FileKind::Renamed => FILE_KIND_BADGE_FG,
2598                FileKind::Modified
2599                | FileKind::Copied
2600                | FileKind::ModeChanged
2601                | FileKind::Binary => Color::Yellow,
2602            };
2603            left.push(Label::from_char(self.header.kind.marker()).fg(fg));
2604        }
2605        left.push(Label::space());
2606        left = left.extend(self.path_line());
2607        if let Some(loc) = summary.loc {
2608            left.push(Label::space());
2609            left.push(Label::new(&format!("{loc} LOC")).fg(colors::rgb::DIM));
2610        }
2611
2612        if let Some(badge) = self.badge(palette) {
2613            left.push(Label::space());
2614            left = left.extend(badge.line());
2615        }
2616        // Right-aligned segments: host annotations first, then the diffstat (or
2617        // its decoration override), joined by a fixed gap.
2618        let mut right = decoration.annotations.clone();
2619        let stats = decoration.stats.unwrap_or(summary.stats);
2620        if let Some(progress) = decoration.progress {
2621            let mut progress_line = Self::progress_bar(progress, palette);
2622            if !progress.is_complete()
2623                && let Some(stats) = Self::diffstat_line(stats.additions, stats.deletions, palette)
2624            {
2625                progress_line.push(Label::space());
2626                progress_line =
2627                    progress_line.extend(Self::review_status_line(stats).labels().iter().cloned());
2628            }
2629            right.push(progress_line);
2630        } else if let Some(stats) = Self::diffstat_line(stats.additions, stats.deletions, palette) {
2631            right.push(stats);
2632        }
2633        let mut header = HStack::default().child(left).spacer();
2634        for (index, segment) in right.into_iter().enumerate() {
2635            if index > 0 {
2636                header = header.child(Line::new(
2637                    Label::new(FILE_HEADER_SEGMENT_SEPARATOR).fg(colors::rgb::DIM),
2638                ));
2639            }
2640            header = header.child(segment);
2641        }
2642        header.to_line(Constraint::tight(cols))
2643    }
2644
2645    /// Returns the file path display line.
2646    fn path_line(&self) -> Line {
2647        match self.header.kind {
2648            FileKind::Renamed | FileKind::Copied => Line::spaced([
2649                Label::from(Self::display_path(self.header.old_path.as_ref())),
2650                Label::from(RENAME_ARROW),
2651                Label::from(Self::display_path(self.header.new_path.as_ref())),
2652            ]),
2653            _ => Line::new(Self::display_path(self.header.display_path())),
2654        }
2655    }
2656
2657    /// Returns an additions-first diffstat line.
2658    fn diffstat_line(additions: usize, deletions: usize, palette: DiffPalette) -> Option<Line> {
2659        if additions == 0 && deletions == 0 {
2660            return None;
2661        }
2662        let mut line = Line::blank();
2663        if additions > 0 {
2664            line.push(Label::new(&format!("+{additions}")).fg(palette.positive_fg));
2665        }
2666        if additions > 0 && deletions > 0 {
2667            line.push(Label::space());
2668        }
2669        if deletions > 0 {
2670            line.push(Label::new(&format!("-{deletions}")).fg(palette.negative_fg));
2671        }
2672        Some(line)
2673    }
2674
2675    /// Returns a status line padded to the file-header review status width.
2676    fn review_status_line(line: Line) -> Line {
2677        let padding = FILE_REVIEW_STATUS_COLS.saturating_sub(line.width());
2678        Line::new(Label::new(&" ".repeat(padding))).extend(line.labels().iter().cloned())
2679    }
2680
2681    /// Returns a compact file review progress bar.
2682    fn progress_bar(progress: ReviewProgress, palette: DiffPalette) -> Line {
2683        let filled = progress.filled(FILE_PROGRESS_BAR_WIDTH);
2684        let empty = FILE_PROGRESS_BAR_WIDTH - filled;
2685
2686        Line::blank()
2687            .item(Label::new(&FILE_PROGRESS_BAR_GLYPH.repeat(filled)).fg(palette.positive_fg))
2688            .item(Label::new(&FILE_PROGRESS_BAR_GLYPH.repeat(empty)).fg(colors::FAINT))
2689    }
2690
2691    /// Returns the nonblank displayed-side line count in this diff.
2692    fn loc(&self) -> usize {
2693        let deleted = self.header.kind == FileKind::Deleted;
2694
2695        self.hunks
2696            .iter()
2697            .flat_map(|hunk| &hunk.lines)
2698            .filter(|line| {
2699                let displayed = match line.kind {
2700                    DiffLineKind::Context => true,
2701                    DiffLineKind::Addition => !deleted,
2702                    DiffLineKind::Deletion => deleted,
2703                    DiffLineKind::NoNewline => false,
2704                };
2705
2706                displayed && !line.text.trim().is_empty()
2707            })
2708            .count()
2709    }
2710
2711    /// Returns a file-kind badge.
2712    fn badge(&self, palette: DiffPalette) -> Option<Badge> {
2713        match self.header.kind {
2714            FileKind::Added => Some(Self::change_badge(
2715                "created",
2716                palette.positive_fg,
2717                palette.positive_row_bg,
2718            )),
2719            FileKind::Deleted => Some(Self::change_badge(
2720                "deleted",
2721                palette.negative_fg,
2722                palette.negative_row_bg,
2723            )),
2724            FileKind::Renamed => Some(Self::change_badge(
2725                "moved",
2726                FILE_KIND_BADGE_FG,
2727                FILE_KIND_BADGE_BG,
2728            )),
2729            FileKind::Copied => Some(Self::change_badge(
2730                "copied",
2731                FILE_KIND_BADGE_FG,
2732                FILE_KIND_BADGE_BG,
2733            )),
2734            FileKind::ModeChanged => Some(Self::change_badge(
2735                "mode changed",
2736                FILE_KIND_BADGE_FG,
2737                FILE_KIND_BADGE_BG,
2738            )),
2739            FileKind::Binary => Some(Self::change_badge(
2740                "binary",
2741                Color::Yellow,
2742                Color::Fixed(236),
2743            )),
2744            FileKind::Modified => None,
2745        }
2746    }
2747
2748    /// Returns a small colored badge.
2749    fn change_badge(text: &str, foreground: Color, background: Color) -> Badge {
2750        let style = Style::new(foreground).bg(background);
2751
2752        Badge::new(text)
2753            .caps(" ", " ")
2754            .cap_style(style)
2755            .style(style)
2756    }
2757
2758    /// Returns a display path or placeholder.
2759    fn display_path(path: Option<&PathBuf>) -> String {
2760        path.map_or_else(|| "<unknown>".to_owned(), |path| path.display().to_string())
2761    }
2762}
2763
2764impl DiffLineMeta {
2765    /// Creates metadata for a source row.
2766    fn new(file: &FileDiff, hunk: HunkId, line: &DiffLine, old_line: u32, new_line: u32) -> Self {
2767        let side = match line.kind {
2768            DiffLineKind::Deletion => DiffSide::Old,
2769            _ => DiffSide::New,
2770        };
2771        let source_line = match side {
2772            DiffSide::Old => old_line,
2773            DiffSide::New => new_line,
2774        };
2775        Self {
2776            file: file.id,
2777            hunk,
2778            row: line.id,
2779            kind: line.kind,
2780            side,
2781            source_line,
2782            text: line.text.clone(),
2783            path: file.source_path(side),
2784        }
2785    }
2786
2787    /// Builds a single-row highlight source from this line's own text.
2788    fn single_row_source(&self) -> HighlightSource {
2789        HighlightSource::new(self.text.clone(), self.source_line)
2790    }
2791}
2792
2793#[cfg(test)]
2794#[allow(clippy::unwrap_used)]
2795mod tests {
2796    use std::fs;
2797    use std::path::PathBuf;
2798    use std::str::FromStr;
2799    use std::time::{SystemTime, UNIX_EPOCH};
2800
2801    use super::*;
2802
2803    use crate::Decode;
2804    use crate::DiffDocument;
2805    use rustik_repo::{DiffRepository, RepoError};
2806    use rustik_tui::{Modifiers, Point};
2807
2808    /// Returns a left-click event for tests.
2809    fn left_click(x: usize, y: usize, modifiers: Modifiers) -> Event<()> {
2810        Event::Mouse(Mouse::Press {
2811            button: MouseButton::Left,
2812            at: Point::new(x, y),
2813            modifiers,
2814        })
2815    }
2816
2817    fn sample_viewer() -> DiffViewer {
2818        let document = DiffDocument::decode_str(
2819            "\
2820diff --git a/a.rs b/a.rs
2821index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
2822--- a/a.rs
2823+++ b/a.rs
2824@@ -1,3 +1,4 @@ fn main
2825 context
2826-old
2827+new
2828+extra
2829 tail
2830",
2831        )
2832        .unwrap();
2833
2834        DiffViewer::new(document, DiffOptions::default())
2835    }
2836
2837    #[test]
2838    fn binary_file_header_omits_loc() {
2839        let document = DiffDocument::decode_str(
2840            "\
2841diff --git a/image.png b/image.png
2842index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
2843Binary files a/image.png and b/image.png differ
2844",
2845        )
2846        .unwrap();
2847        let viewer = DiffViewer::new(document, DiffOptions::default());
2848
2849        let header = viewer.render_row(0, 80).unwrap().line;
2850
2851        assert!(!header.to_string().contains("LOC"));
2852    }
2853
2854    #[derive(Default)]
2855    struct RecordingHighlighter {
2856        batches: usize,
2857    }
2858
2859    impl DiffHighlighter for RecordingHighlighter {
2860        fn highlight_batch(&mut self, requests: Vec<HighlightRequest>) -> Vec<HighlightResult> {
2861            self.batches += 1;
2862            requests
2863                .into_iter()
2864                .map(|request| HighlightResult::new(request, Line::new("highlighted")))
2865                .collect()
2866        }
2867    }
2868
2869    fn two_file_viewer() -> DiffViewer {
2870        let document = DiffDocument::decode_str(
2871            "\
2872diff --git a/a.rs b/a.rs
2873index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
2874--- a/a.rs
2875+++ b/a.rs
2876@@ -1,3 +1,4 @@ fn a
2877 context
2878-old
2879+new
2880+extra
2881 tail
2882diff --git a/b.rs b/b.rs
2883index 3333333333333333333333333333333333333333..4444444444444444444444444444444444444444 100644
2884--- a/b.rs
2885+++ b/b.rs
2886@@ -1,2 +1,2 @@ fn b
2887 keep
2888-before
2889+after
2890",
2891        )
2892        .unwrap();
2893
2894        DiffViewer::new(document, DiffOptions::default())
2895    }
2896
2897    fn two_hunk_viewer() -> DiffViewer {
2898        let document = DiffDocument::decode_str(
2899            "\
2900diff --git a/a.rs b/a.rs
2901index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
2902--- a/a.rs
2903+++ b/a.rs
2904@@ -1,2 +1,2 @@ fn first
2905 keep
2906-old
2907+new
2908@@ -10,2 +10,2 @@ fn second
2909 keep
2910-before
2911+after
2912",
2913        )
2914        .unwrap();
2915
2916        DiffViewer::new(document, DiffOptions::default())
2917    }
2918
2919    fn commit_viewer() -> DiffViewer {
2920        let document = DiffDocument::decode_str(
2921            "\
2922commit 1234567890abcdef1234567890abcdef12345678
2923Author: A <a@example.com>
2924
2925    Summary
2926
2927diff --git a/a.rs b/a.rs
2928index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
2929--- a/a.rs
2930+++ b/a.rs
2931@@ -1,2 +1,2 @@ fn first
2932 keep
2933-old
2934+new
2935@@ -10,2 +10,2 @@ fn second
2936 keep
2937-before
2938+after
2939",
2940        )
2941        .unwrap();
2942
2943        DiffViewer::new(
2944            document,
2945            DiffOptions {
2946                hunk_focus: HunkFocus::DimUnfocused,
2947                ..DiffOptions::default()
2948            },
2949        )
2950    }
2951
2952    fn scroll_viewer() -> DiffViewer {
2953        let document = DiffDocument::decode_str(
2954            "\
2955diff --git a/a.rs b/a.rs
2956index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
2957--- a/a.rs
2958+++ b/a.rs
2959@@ -1,20 +1,20 @@ fn main
2960 line 01
2961 line 02
2962 line 03
2963 line 04
2964 line 05
2965 line 06
2966 line 07
2967 line 08
2968 line 09
2969 line 10
2970 line 11
2971 line 12
2972 line 13
2973 line 14
2974 line 15
2975 line 16
2976 line 17
2977 line 18
2978 line 19
2979 line 20
2980",
2981        )
2982        .unwrap();
2983
2984        DiffViewer::new(document, DiffOptions::default())
2985    }
2986
2987    fn tree_viewer() -> DiffViewer {
2988        let document = DiffDocument::decode_str(
2989            "\
2990diff --git a/a.rs b/a.rs
2991index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
2992--- a/a.rs
2993+++ b/a.rs
2994@@ -1 +1 @@
2995-old
2996+new
2997diff --git a/b.rs b/b.rs
2998index 3333333333333333333333333333333333333333..4444444444444444444444444444444444444444 100644
2999--- a/b.rs
3000+++ b/b.rs
3001@@ -1 +1 @@
3002-before
3003+after
3004",
3005        )
3006        .unwrap();
3007
3008        DiffViewer::new(
3009            document,
3010            DiffOptions {
3011                file_tree: FileTreeMode::Auto,
3012                file_tree_root: "rustik".to_owned(),
3013                ..DiffOptions::default()
3014            },
3015        )
3016    }
3017
3018    fn long_file_tree_viewer() -> DiffViewer {
3019        let document = DiffDocument::decode_str(
3020            "\
3021diff --git a/crates/diff/tests/golden/sticky_header_before_next_file_64x5.txt b/crates/diff/tests/golden/sticky_header_before_next_file_64x5.txt
3022index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
3023--- a/crates/diff/tests/golden/sticky_header_before_next_file_64x5.txt
3024+++ b/crates/diff/tests/golden/sticky_header_before_next_file_64x5.txt
3025@@ -1 +1 @@
3026-old
3027+new
3028",
3029        )
3030        .unwrap();
3031
3032        DiffViewer::new(
3033            document,
3034            DiffOptions {
3035                file_tree: FileTreeMode::Auto,
3036                file_tree_root: "rustik".to_owned(),
3037                ..DiffOptions::default()
3038            },
3039        )
3040    }
3041
3042    fn nested_tree_viewer() -> DiffViewer {
3043        let document = DiffDocument::decode_str(
3044            "\
3045diff --git a/src/a.rs b/src/a.rs
3046index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
3047--- a/src/a.rs
3048+++ b/src/a.rs
3049@@ -1 +1 @@
3050-old
3051+new
3052diff --git a/src/b.rs b/src/b.rs
3053index 3333333333333333333333333333333333333333..4444444444444444444444444444444444444444 100644
3054--- a/src/b.rs
3055+++ b/src/b.rs
3056@@ -1 +1 @@
3057-before
3058+after
3059diff --git a/README.md b/README.md
3060index 5555555555555555555555555555555555555555..6666666666666666666666666666666666666666 100644
3061--- a/README.md
3062+++ b/README.md
3063@@ -1 +1 @@
3064-old readme
3065+new readme
3066",
3067        )
3068        .unwrap();
3069
3070        DiffViewer::new(
3071            document,
3072            DiffOptions {
3073                file_tree: FileTreeMode::Auto,
3074                file_tree_root: "rustik".to_owned(),
3075                ..DiffOptions::default()
3076            },
3077        )
3078    }
3079
3080    fn deep_tree_viewer() -> DiffViewer {
3081        let document = DiffDocument::decode_str(
3082            "\
3083diff --git a/src/app/a.rs b/src/app/a.rs
3084index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
3085--- a/src/app/a.rs
3086+++ b/src/app/a.rs
3087@@ -1 +1 @@
3088-old
3089+new
3090diff --git a/src/lib/b.rs b/src/lib/b.rs
3091index 3333333333333333333333333333333333333333..4444444444444444444444444444444444444444 100644
3092--- a/src/lib/b.rs
3093+++ b/src/lib/b.rs
3094@@ -1 +1 @@
3095-before
3096+after
3097diff --git a/README.md b/README.md
3098index 5555555555555555555555555555555555555555..6666666666666666666666666666666666666666 100644
3099--- a/README.md
3100+++ b/README.md
3101@@ -1 +1 @@
3102-old readme
3103+new readme
3104",
3105        )
3106        .unwrap();
3107
3108        DiffViewer::new(
3109            document,
3110            DiffOptions {
3111                file_tree: FileTreeMode::Auto,
3112                file_tree_root: "rustik".to_owned(),
3113                ..DiffOptions::default()
3114            },
3115        )
3116    }
3117
3118    #[test]
3119    fn hunk_focus_does_not_change_rendered_row_count() {
3120        let viewer = sample_viewer();
3121        let mut focused = sample_viewer();
3122
3123        focused.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
3124
3125        assert_eq!(focused.index.rows, viewer.index.rows);
3126    }
3127
3128    #[test]
3129    fn multi_hunk_file_counts_gap_row() {
3130        let viewer = two_hunk_viewer();
3131
3132        assert_eq!(viewer.index.rows, 11);
3133    }
3134
3135    #[test]
3136    fn commit_is_initial_hunk_navigation_target() {
3137        let mut viewer = commit_viewer();
3138        let area = Rect::new(0, 0, 64, 6);
3139        let targets = viewer
3140            .focus_targets(FocusFilter::HunkNavigation)
3141            .into_iter()
3142            .map(|target| target.focus)
3143            .collect::<Vec<_>>();
3144
3145        assert_eq!(
3146            targets,
3147            vec![
3148                DiffFocus::Commit,
3149                DiffFocus::Hunk(HunkId::new(0)),
3150                DiffFocus::Hunk(HunkId::new(1)),
3151            ]
3152        );
3153        assert_eq!(viewer.state().focus, Some(DiffFocus::Commit));
3154        assert_eq!(
3155            viewer.apply(DiffAction::PreviousHunk, area),
3156            ViewChange::Unchanged
3157        );
3158        viewer.apply(DiffAction::NextHunk, area);
3159        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
3160        viewer.apply(DiffAction::PreviousHunk, area);
3161        assert_eq!(viewer.state().focus, Some(DiffFocus::Commit));
3162        assert_eq!(
3163            viewer.apply(DiffAction::PreviousHunk, area),
3164            ViewChange::Unchanged
3165        );
3166    }
3167
3168    #[test]
3169    fn state_restore_accepts_commit_focus_only_with_commit_header() {
3170        let state = DiffState {
3171            focus: Some(DiffFocus::Commit),
3172            ..DiffState::default()
3173        };
3174        let mut commit = commit_viewer();
3175        commit.set_focus(None);
3176        commit.set_state(state.clone());
3177
3178        assert_eq!(commit.state().focus, Some(DiffFocus::Commit));
3179
3180        let mut patch = sample_viewer();
3181        patch.set_state(state);
3182
3183        assert_eq!(patch.state().focus, None);
3184    }
3185
3186    #[test]
3187    fn hiding_first_hunk_restores_commit_boundary() {
3188        let mut viewer = commit_viewer();
3189        let area = Rect::new(0, 0, 64, 6);
3190        let visible = viewer.document.files[0].clone();
3191        let mut hidden = visible.clone();
3192        hidden.hunks.remove(0);
3193        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
3194
3195        viewer.replace_file_diffs_anchored([hidden], area);
3196        assert_eq!(viewer.state().focus, Some(DiffFocus::Commit));
3197
3198        viewer.replace_file_diffs_anchored([visible], area);
3199        assert_eq!(viewer.state().focus, Some(DiffFocus::Commit));
3200        viewer.apply(DiffAction::NextHunk, area);
3201        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
3202    }
3203
3204    #[test]
3205    fn dim_unfocused_follows_commit_and_hunk_selection() {
3206        let mut viewer = commit_viewer();
3207        let summary = viewer
3208            .preamble
3209            .iter()
3210            .position(|line| line.to_string().contains("Summary"))
3211            .unwrap();
3212        let hunk = viewer
3213            .focus_targets(FocusFilter::HunkNavigation)
3214            .into_iter()
3215            .find(|target| target.focus == DiffFocus::Hunk(HunkId::new(0)))
3216            .unwrap()
3217            .row;
3218        let is_dimmed = |viewer: &DiffViewer, row| {
3219            let line = viewer.render_row(row, 80).unwrap().line;
3220
3221            format!("{}", line.styled()).contains("\x1b[2m")
3222        };
3223
3224        assert!(!is_dimmed(&viewer, summary));
3225        assert!(is_dimmed(&viewer, hunk));
3226
3227        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
3228        assert!(is_dimmed(&viewer, summary));
3229        assert!(!is_dimmed(&viewer, hunk));
3230
3231        viewer.set_focus(Some(DiffFocus::Commit));
3232        assert!(!is_dimmed(&viewer, summary));
3233    }
3234
3235    #[test]
3236    fn patch_only_viewer_keeps_unset_focus_and_plain_hunks() {
3237        let document = two_hunk_viewer().document().clone();
3238        let mut viewer = DiffViewer::new(
3239            document,
3240            DiffOptions {
3241                hunk_focus: HunkFocus::DimUnfocused,
3242                ..DiffOptions::default()
3243            },
3244        );
3245        let area = Rect::new(0, 0, 64, 6);
3246        let target = viewer.focus_targets(FocusFilter::HunkNavigation)[0];
3247        let line = viewer.render_row(target.row, 64).unwrap().line;
3248
3249        assert_eq!(viewer.state().focus, None);
3250        assert_eq!(target.focus, DiffFocus::Hunk(HunkId::new(0)));
3251        assert!(!format!("{}", line.styled()).contains("\x1b[2m"));
3252
3253        viewer.apply(DiffAction::NextHunk, area);
3254        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
3255    }
3256
3257    #[test]
3258    fn focus_next_and_previous_visit_files_only() {
3259        let mut viewer = two_file_viewer();
3260        let area = Rect::new(0, 0, 64, 6);
3261
3262        viewer.apply(DiffAction::FocusNext, area);
3263        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
3264        viewer.apply(DiffAction::FocusNext, area);
3265        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
3266        viewer.apply(DiffAction::FocusPrevious, area);
3267        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
3268    }
3269
3270    #[test]
3271    fn file_navigation_restores_each_files_last_focused_hunk() {
3272        let mut viewer = two_file_viewer();
3273        let area = Rect::new(0, 0, 64, 6);
3274        let mut second_a = viewer.document.files[0].hunks[0].clone();
3275        second_a.id = HunkId::new(2);
3276        viewer.document.files[0].hunks.push(second_a);
3277        let mut second_b = viewer.document.files[1].hunks[0].clone();
3278        second_b.id = HunkId::new(3);
3279        viewer.document.files[1].hunks.push(second_b);
3280        viewer.rebuild_index();
3281
3282        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(2))));
3283        viewer.apply(DiffAction::FocusNext, area);
3284        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
3285        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(3))));
3286        viewer.apply(DiffAction::FocusPrevious, area);
3287        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(2))));
3288        let target = viewer
3289            .focus_targets(FocusFilter::HunkNavigation)
3290            .into_iter()
3291            .find(|target| target.focus == DiffFocus::Hunk(HunkId::new(2)))
3292            .unwrap();
3293        assert_ne!(viewer.state.scroll.offset, target.file_start);
3294        assert!(
3295            (viewer.state.scroll.offset..viewer.state.scroll.offset + area.rows)
3296                .contains(&target.row)
3297        );
3298        viewer.apply(DiffAction::FocusNext, area);
3299        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(3))));
3300    }
3301
3302    #[test]
3303    fn file_navigation_forgets_replaced_hunks() {
3304        let mut viewer = two_file_viewer();
3305        let area = Rect::new(0, 0, 64, 6);
3306        let mut hidden = viewer.document.files[0].hunks[0].clone();
3307        hidden.id = HunkId::new(2);
3308        viewer.document.files[0].hunks.push(hidden);
3309        viewer.rebuild_index();
3310        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(2))));
3311        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(1))));
3312        let mut file = viewer.document.files[0].clone();
3313        file.hunks.remove(1);
3314
3315        viewer.replace_file_diffs([file]);
3316        viewer.apply(DiffAction::FocusPrevious, area);
3317
3318        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
3319    }
3320
3321    #[test]
3322    fn file_navigation_restores_hunk_after_visibility_replacement() {
3323        let mut viewer = two_file_viewer();
3324        let area = Rect::new(0, 0, 64, 6);
3325        let mut later = viewer.document.files[0].hunks[0].clone();
3326        later.id = HunkId::new(2);
3327        viewer.document.files[0].hunks.push(later);
3328        viewer.rebuild_index();
3329        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(2))));
3330        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(1))));
3331        let visible = viewer.document.files[0].clone();
3332        let mut hidden = visible.clone();
3333        hidden.hunks.remove(1);
3334
3335        viewer.replace_file_diffs_anchored([hidden], area);
3336        viewer.replace_file_diffs_anchored([visible], area);
3337        viewer.apply(DiffAction::FocusPrevious, area);
3338
3339        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(2))));
3340    }
3341
3342    #[test]
3343    fn restored_predecessor_replaces_stale_hidden_hunk_focus() {
3344        let mut viewer = two_file_viewer();
3345        let area = Rect::new(0, 0, 64, 6);
3346        let mut later = viewer.document.files[0].hunks[0].clone();
3347        later.id = HunkId::new(2);
3348        viewer.document.files[0].hunks.push(later);
3349        viewer.rebuild_index();
3350        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(2))));
3351        let visible = viewer.document.files[0].clone();
3352        let mut hidden = visible.clone();
3353        hidden.hunks.remove(1);
3354
3355        viewer.replace_file_diffs_anchored([hidden], area);
3356        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
3357        viewer.replace_file_diffs_anchored([visible], area);
3358        viewer.apply(DiffAction::FocusNext, area);
3359        viewer.apply(DiffAction::FocusPrevious, area);
3360
3361        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
3362    }
3363
3364    #[test]
3365    fn standalone_input_navigates_files() {
3366        let mut viewer = two_file_viewer();
3367        let area = Rect::new(0, 0, 64, 6);
3368        assert_eq!(
3369            viewer.handle_input(Event::Key(Key::Char('n')), area),
3370            Control::Redraw
3371        );
3372        assert_eq!(viewer.focused_file(), Some(FileId::new(0)));
3373        assert_eq!(
3374            viewer.handle_input(Event::Key(Key::Char('n')), area),
3375            Control::Redraw
3376        );
3377        assert_eq!(viewer.focused_file(), Some(FileId::new(1)));
3378        assert_eq!(
3379            viewer.handle_input(Event::Key(Key::Char('p')), area),
3380            Control::Redraw
3381        );
3382        assert_eq!(viewer.focused_file(), Some(FileId::new(0)));
3383    }
3384    #[test]
3385    fn initial_next_file_navigation_selects_first_file() {
3386        let mut viewer = two_file_viewer();
3387        let area = Rect::new(0, 0, 64, 6);
3388        viewer.apply(DiffAction::FocusNext, area);
3389        assert_eq!(viewer.focused_file(), Some(FileId::new(0)));
3390        viewer.apply(DiffAction::FocusNext, area);
3391        assert_eq!(viewer.focused_file(), Some(FileId::new(1)));
3392        viewer.apply(DiffAction::FocusPrevious, area);
3393        assert_eq!(viewer.focused_file(), Some(FileId::new(0)));
3394    }
3395
3396    #[test]
3397    fn commit_message_trailers_are_dimmed() {
3398        let commit = CommitHeader::from_str(
3399            "\
3400commit 1234567890abcdef1234567890abcdef12345678
3401
3402    Commit summary
3403
3404    Body text.
3405
3406    Assisted-by: Codex:gpt-5.6
3407        continued trailer value
3408    Signed-off-by: A <a@example.com>
3409",
3410        )
3411        .unwrap();
3412
3413        let lines = DiffViewer::preamble(Some(&commit), 80);
3414        let color = |text| {
3415            lines
3416                .iter()
3417                .flat_map(Line::labels)
3418                .find(|label| label.content().contains(text))
3419                .map(|label| label.paint.style().fg_color())
3420        };
3421
3422        assert_eq!(color("Body text."), Some(Color::Unset));
3423        assert_eq!(color("Assisted-by: Codex:gpt-5.6"), Some(colors::rgb::DIM));
3424        assert_eq!(color("continued trailer value"), Some(colors::rgb::DIM));
3425        assert_eq!(
3426            color("Signed-off-by: A <a@example.com>"),
3427            Some(colors::rgb::DIM)
3428        );
3429    }
3430
3431    #[test]
3432    fn initial_next_file_navigation_selects_first_file_from_preamble() {
3433        let document = DiffDocument::decode_str(
3434            "\
3435commit 1234567890abcdef1234567890abcdef12345678
3436Author: A <a@example.com>
3437
3438    Commit summary
3439
3440diff --git a/a.rs b/a.rs
3441index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
3442--- a/a.rs
3443+++ b/a.rs
3444@@ -1 +1 @@ fn a
3445-old
3446+new
3447diff --git a/b.rs b/b.rs
3448index 3333333333333333333333333333333333333333..4444444444444444444444444444444444444444 100644
3449--- a/b.rs
3450+++ b/b.rs
3451@@ -1 +1 @@ fn b
3452-before
3453+after
3454",
3455        )
3456        .unwrap();
3457        let mut viewer = DiffViewer::new(document, DiffOptions::default());
3458        let area = Rect::new(0, 0, 64, 6);
3459
3460        assert_eq!(
3461            viewer.apply(DiffAction::FocusNext, area),
3462            ViewChange::Changed
3463        );
3464
3465        assert_eq!(viewer.focused_file(), Some(FileId::new(0)));
3466    }
3467
3468    #[test]
3469    fn next_hunk_visits_hunks_only() {
3470        let mut viewer = two_file_viewer();
3471        let area = Rect::new(0, 0, 64, 6);
3472
3473        viewer.apply(DiffAction::NextHunk, area);
3474        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
3475        viewer.apply(DiffAction::NextHunk, area);
3476        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
3477    }
3478
3479    #[test]
3480    fn next_hunk_from_file_focus_uses_visible_position() {
3481        let mut viewer = two_hunk_viewer();
3482        let area = Rect::new(0, 0, 64, 5);
3483
3484        viewer.set_focus(Some(DiffFocus::File(FileId::new(0))));
3485        viewer.set_scroll(7);
3486        viewer.apply(DiffAction::NextHunk, area);
3487
3488        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
3489        assert_eq!(viewer.state().scroll.offset, 4);
3490    }
3491
3492    #[test]
3493    fn previous_hunk_from_file_focus_uses_visible_position() {
3494        let mut viewer = two_hunk_viewer();
3495        let area = Rect::new(0, 0, 64, 5);
3496
3497        viewer.set_focus(Some(DiffFocus::File(FileId::new(0))));
3498        viewer.set_scroll(7);
3499        viewer.apply(DiffAction::PreviousHunk, area);
3500
3501        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
3502        assert_eq!(viewer.state().scroll.offset, 4);
3503    }
3504
3505    #[test]
3506    fn scroll_clamps_after_resize() {
3507        let mut viewer = sample_viewer();
3508        let small = Rect::new(0, 0, 64, 3);
3509        let large = Rect::new(0, 0, 64, 30);
3510
3511        viewer.apply(DiffAction::Scroll(Scroll::Bottom), small);
3512        assert!(viewer.state().scroll.offset > 0);
3513        viewer.apply(DiffAction::Resize, large);
3514
3515        assert_eq!(viewer.state().scroll.offset, 0);
3516    }
3517
3518    #[test]
3519    fn sticky_header_renders_when_scrolled_inside_file() {
3520        let mut viewer = sample_viewer();
3521        let area = Rect::new(0, 0, 64, 5);
3522
3523        viewer.apply(DiffAction::Scroll(Scroll::Lines(4)), area);
3524
3525        assert_eq!(
3526            viewer.sticky_row_count(viewer.state().scroll.offset, area.rows),
3527            3
3528        );
3529    }
3530
3531    #[test]
3532    fn sticky_header_starts_before_header_scrolls_off() {
3533        let mut viewer = sample_viewer();
3534        let area = Rect::new(0, 0, 64, 5);
3535
3536        viewer.apply(DiffAction::Scroll(Scroll::Lines(1)), area);
3537
3538        assert_eq!(
3539            viewer.sticky_start(viewer.state().scroll.offset, area.rows),
3540            Some(0)
3541        );
3542    }
3543
3544    #[test]
3545    fn sticky_header_replaces_scrolled_file_chrome() {
3546        let mut viewer = sample_viewer();
3547        let area = Rect::new(0, 0, 64, 5);
3548
3549        viewer.apply(DiffAction::Scroll(Scroll::Lines(3)), area);
3550
3551        assert_eq!(
3552            viewer.sticky_start(viewer.state().scroll.offset, area.rows),
3553            Some(0)
3554        );
3555    }
3556
3557    #[test]
3558    fn sticky_header_cuts_before_next_file_card() {
3559        let mut viewer = two_file_viewer();
3560        let area = Rect::new(0, 0, 64, 5);
3561
3562        viewer.apply(DiffAction::Scroll(Scroll::Lines(8)), area);
3563
3564        assert_eq!(
3565            viewer.sticky_start(viewer.state().scroll.offset, area.rows),
3566            None
3567        );
3568    }
3569
3570    #[test]
3571    fn sticky_header_stays_visible_until_next_file_reaches_body() {
3572        let mut viewer = two_file_viewer();
3573        let area = Rect::new(0, 0, 64, 5);
3574
3575        viewer.apply(DiffAction::Scroll(Scroll::Lines(5)), area);
3576
3577        assert_eq!(
3578            viewer.sticky_start(viewer.state().scroll.offset, area.rows),
3579            Some(0)
3580        );
3581    }
3582
3583    #[test]
3584    fn sticky_header_stays_visible_at_file_end_boundary() {
3585        let mut viewer = two_file_viewer();
3586        let area = Rect::new(0, 0, 64, 5);
3587
3588        viewer.apply(DiffAction::Scroll(Scroll::Lines(6)), area);
3589
3590        assert_eq!(
3591            viewer.sticky_start(viewer.state().scroll.offset, area.rows),
3592            Some(0)
3593        );
3594        assert_eq!(
3595            viewer.sticky_row_count(viewer.state().scroll.offset, area.rows),
3596            2
3597        );
3598    }
3599
3600    #[test]
3601    fn sticky_header_stays_visible_at_file_bottom() {
3602        let mut viewer = sample_viewer();
3603        let area = Rect::new(0, 0, 64, 5);
3604
3605        viewer.apply(DiffAction::Scroll(Scroll::Bottom), area);
3606
3607        assert_eq!(
3608            viewer.sticky_start(viewer.state().scroll.offset, area.rows),
3609            Some(0)
3610        );
3611    }
3612
3613    #[test]
3614    fn oversized_hunk_navigation_shows_its_first_line() {
3615        let target = FocusTarget {
3616            focus: DiffFocus::Hunk(HunkId::new(0)),
3617            row: 10,
3618            height: 20,
3619            file_start: 0,
3620        };
3621
3622        assert_eq!(target.scroll_offset(15, 5, HunkScroll::Preserve), 7);
3623
3624        let fitting = FocusTarget {
3625            height: 2,
3626            ..target
3627        };
3628        assert_eq!(fitting.scroll_offset(0, 5, HunkScroll::Center), 7);
3629    }
3630
3631    #[test]
3632    fn hunk_navigation_preserves_scroll_with_one_line_margin() {
3633        let top = FocusTarget {
3634            focus: DiffFocus::Hunk(HunkId::new(0)),
3635            row: 11,
3636            height: 2,
3637            file_start: 10,
3638        };
3639        let bottom = FocusTarget { row: 19, ..top };
3640
3641        assert_eq!(top.scroll_offset(10, 12, HunkScroll::Preserve), 10);
3642        assert_eq!(bottom.scroll_offset(10, 12, HunkScroll::Preserve), 10);
3643    }
3644
3645    #[test]
3646    fn next_hunk_preserves_scroll_with_one_line_top_margin() {
3647        let mut viewer = two_file_viewer();
3648        let mut tail = viewer.document.files[1].clone();
3649        tail.id = FileId::new(2);
3650        tail.hunks[0].id = HunkId::new(2);
3651        viewer.document.files.push(tail);
3652        viewer.rebuild_index();
3653        let area = Rect::new(0, 0, 64, 16);
3654        let targets = viewer.focus_targets(FocusFilter::HunkNavigation);
3655        let target = targets[1];
3656        let offset = target.file_start;
3657
3658        viewer.set_focus(Some(targets[0].focus));
3659        viewer.set_scroll(offset);
3660        viewer.apply(DiffAction::NextHunk, area);
3661
3662        assert_eq!(viewer.state().focus, Some(target.focus));
3663        assert_eq!(viewer.state().scroll.offset, offset);
3664
3665        viewer.set_focus(None);
3666        viewer.set_scroll(offset);
3667        viewer.apply(DiffAction::NextHunk, area);
3668
3669        assert_eq!(viewer.state().focus, Some(target.focus));
3670        assert_eq!(viewer.state().scroll.offset, offset);
3671    }
3672
3673    #[test]
3674    fn hunk_navigation_scrolls_focus_out_of_viewport_edge() {
3675        let mut viewer = two_file_viewer();
3676        let area = Rect::new(0, 0, 64, 5);
3677
3678        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
3679        viewer.set_scroll(6);
3680        viewer.apply(DiffAction::NextHunk, area);
3681
3682        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
3683        assert_eq!(viewer.state().scroll.offset, 9);
3684    }
3685
3686    #[test]
3687    fn keyboard_line_scroll_inputs_move_one_row() {
3688        let area = Rect::new(0, 0, 80, 9);
3689        let mut viewer = scroll_viewer();
3690
3691        assert_eq!(
3692            viewer.handle_input(Event::Key(Key::Char('j')), area),
3693            Control::Redraw
3694        );
3695        assert_eq!(viewer.state().scroll.offset, 1);
3696        assert_eq!(
3697            viewer.handle_input(Event::Key(Key::Char('j')), area),
3698            Control::Redraw
3699        );
3700        assert_eq!(viewer.state().scroll.offset, 2);
3701        assert_eq!(
3702            viewer.handle_input(Event::Key(Key::Down), area),
3703            Control::Redraw
3704        );
3705        assert_eq!(viewer.state().scroll.offset, 3);
3706        assert_eq!(
3707            viewer.handle_input(Event::Key(Key::Char('k')), area),
3708            Control::Redraw
3709        );
3710        assert_eq!(viewer.state().scroll.offset, 2);
3711        assert_eq!(
3712            viewer.handle_input(Event::Key(Key::Up), area),
3713            Control::Redraw
3714        );
3715        assert_eq!(viewer.state().scroll.offset, 1);
3716    }
3717
3718    #[test]
3719    fn scroll_preserves_hunk_focus() {
3720        let area = Rect::new(0, 0, 64, 5);
3721        let mut viewer = two_hunk_viewer();
3722
3723        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
3724        viewer.handle_input(Event::Key(Key::Char('j')), area);
3725
3726        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
3727        assert_eq!(viewer.state().scroll.offset, 1);
3728    }
3729
3730    #[test]
3731    fn boundary_scroll_inputs_do_not_redraw() {
3732        let area = Rect::new(0, 0, 80, 9);
3733        let mut viewer = scroll_viewer();
3734
3735        assert_eq!(
3736            viewer.handle_input(Event::Key(Key::Char('k')), area),
3737            Control::Continue
3738        );
3739        assert_eq!(viewer.state().scroll.offset, 0);
3740
3741        viewer.apply(DiffAction::Scroll(Scroll::Bottom), area);
3742        let bottom = viewer.state().scroll.offset;
3743
3744        assert_eq!(
3745            viewer.handle_input(Event::Key(Key::Char('j')), area),
3746            Control::Continue
3747        );
3748        assert_eq!(viewer.state().scroll.offset, bottom);
3749    }
3750
3751    #[test]
3752    fn escape_quits_when_no_file_is_focused() {
3753        let area = Rect::new(0, 0, 100, 9);
3754        let mut viewer = tree_viewer();
3755
3756        assert_eq!(
3757            viewer.handle_input(Event::Key(Key::Esc), area),
3758            Control::Quit
3759        );
3760        assert_eq!(viewer.file_tree.target(), None);
3761    }
3762
3763    #[test]
3764    fn plain_h_and_l_are_unmapped() {
3765        let area = Rect::new(0, 0, 100, 9);
3766        let mut viewer = tree_viewer();
3767
3768        assert_eq!(
3769            viewer.handle_input(Event::Key(Key::Char('h')), area),
3770            Control::Continue
3771        );
3772        assert_eq!(
3773            viewer.handle_input(Event::Key(Key::Char('l')), area),
3774            Control::Continue
3775        );
3776        assert_eq!(viewer.file_tree.target(), None);
3777    }
3778
3779    #[test]
3780    fn shift_j_moves_file_tree_cursor_and_jumps_to_file() {
3781        let area = Rect::new(0, 0, 120, 4);
3782        let mut viewer = tree_viewer();
3783
3784        assert_eq!(
3785            viewer.handle_input(Event::Key(Key::Char('J')), area),
3786            Control::Redraw
3787        );
3788
3789        assert_eq!(
3790            viewer.file_tree.target(),
3791            Some(FileTreeTarget::File(FileId::new(1)))
3792        );
3793        assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(1))));
3794        assert_eq!(viewer.state().scroll.offset, 6);
3795    }
3796
3797    #[test]
3798    fn shift_k_moves_file_tree_cursor_to_folder_first_file() {
3799        let area = Rect::new(0, 0, 120, 9);
3800        let mut viewer = nested_tree_viewer();
3801
3802        assert_eq!(
3803            viewer.handle_input(Event::Key(Key::Char('K')), area),
3804            Control::Redraw
3805        );
3806
3807        assert_eq!(
3808            viewer.file_tree.target(),
3809            Some(FileTreeTarget::Directory(PathBuf::from("src")))
3810        );
3811        assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(0))));
3812        assert_eq!(viewer.state().scroll.offset, 0);
3813    }
3814
3815    #[test]
3816    fn j_scrolls_after_file_tree_mouse_selection() {
3817        let area = Rect::new(0, 0, 120, 4);
3818        let mut viewer = tree_viewer();
3819
3820        viewer.handle_input(left_click(2, 3, Modifiers::NONE), area);
3821        assert_eq!(viewer.state().scroll.offset, 6);
3822        assert_eq!(
3823            viewer.handle_input(Event::Key(Key::Char('j')), area),
3824            Control::Redraw
3825        );
3826
3827        assert_eq!(
3828            viewer.file_tree.target(),
3829            Some(FileTreeTarget::File(FileId::new(1)))
3830        );
3831        assert_eq!(viewer.state().scroll.offset, 7);
3832    }
3833
3834    #[test]
3835    fn mouse_wheel_scroll_updates_file_tree_cursor() {
3836        let area = Rect::new(0, 0, 120, 4);
3837        let mut viewer = tree_viewer();
3838        let down = Event::Mouse(Mouse::Press {
3839            button: MouseButton::WheelDown,
3840            at: Point::new(50, 1),
3841            modifiers: Modifiers::NONE,
3842        });
3843
3844        viewer.handle_input(down.clone(), area);
3845        viewer.handle_input(down, area);
3846
3847        assert_eq!(
3848            viewer.file_tree.target(),
3849            Some(FileTreeTarget::File(FileId::new(1)))
3850        );
3851        assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(1))));
3852    }
3853
3854    #[test]
3855    fn left_click_on_file_tree_file_keeps_all_files_visible() {
3856        let area = Rect::new(0, 0, 120, 9);
3857        let mut viewer = tree_viewer();
3858        let rows = viewer.index.rows;
3859
3860        assert_eq!(
3861            viewer.handle_input(left_click(2, 3, Modifiers::NONE), area),
3862            Control::Redraw
3863        );
3864
3865        assert_eq!(viewer.index.rows, rows);
3866        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
3867    }
3868
3869    #[test]
3870    fn file_navigation_updates_file_tree_cursor() {
3871        let area = Rect::new(0, 0, 120, 4);
3872        let mut viewer = tree_viewer();
3873
3874        viewer.apply(DiffAction::FocusNext, area);
3875
3876        assert_eq!(
3877            viewer.file_tree.target(),
3878            Some(FileTreeTarget::File(FileId::new(0)))
3879        );
3880    }
3881
3882    #[test]
3883    fn hunk_navigation_updates_file_tree_to_focused_file() {
3884        let area = Rect::new(0, 0, 120, 20);
3885        let mut viewer = tree_viewer();
3886
3887        viewer.apply(DiffAction::NextHunk, area);
3888        viewer.apply(DiffAction::NextHunk, area);
3889
3890        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
3891        assert_eq!(
3892            viewer.file_tree.target(),
3893            Some(FileTreeTarget::File(FileId::new(1)))
3894        );
3895    }
3896
3897    #[test]
3898    fn backtick_toggles_file_tree_visibility() {
3899        let area = Rect::new(0, 0, 120, 9);
3900        let mut viewer = tree_viewer();
3901
3902        assert!(viewer.layout(area).tree.is_some());
3903        assert_eq!(
3904            viewer.handle_input(Event::Key(Key::Char('`')), area),
3905            Control::Redraw
3906        );
3907        assert!(viewer.layout(area).tree.is_none());
3908        assert_eq!(
3909            viewer.handle_input(Event::Key(Key::Char('`')), area),
3910            Control::Redraw
3911        );
3912        assert!(viewer.layout(area).tree.is_some());
3913    }
3914
3915    #[test]
3916    fn file_tree_hides_when_dynamic_width_would_starve_diff() {
3917        let area = Rect::new(0, 0, 100, 9);
3918        let mut viewer = long_file_tree_viewer();
3919
3920        assert_eq!(
3921            viewer.layout(area),
3922            DiffLayout {
3923                diff: area,
3924                tree: None
3925            }
3926        );
3927        assert_eq!(
3928            viewer.handle_input(Event::Key(Key::Char('`')), area),
3929            Control::Redraw
3930        );
3931        assert!(viewer.layout(area).tree.is_some());
3932    }
3933
3934    #[test]
3935    fn file_tree_hides_when_source_view_would_be_too_narrow() {
3936        let viewer = tree_viewer();
3937        let tree_cols = viewer.file_tree.cols(usize::MAX);
3938        let one_column_short = tree_cols + tree::GAP_COLS + tree::MIN_DIFF_COLS - 1;
3939        let exactly_enough = tree_cols + tree::GAP_COLS + tree::MIN_DIFF_COLS;
3940        let diff_start = tree_cols + tree::GAP_COLS;
3941
3942        assert_eq!(
3943            viewer.layout(Rect::new(0, 0, one_column_short, 9)),
3944            DiffLayout {
3945                diff: Rect::new(0, 0, one_column_short, 9),
3946                tree: None
3947            }
3948        );
3949        assert_eq!(
3950            viewer.layout(Rect::new(0, 0, exactly_enough, 9)),
3951            DiffLayout {
3952                diff: Rect::new(diff_start, 0, tree::MIN_DIFF_COLS, 9),
3953                tree: Some(Rect::new(0, 0, tree_cols, 9))
3954            }
3955        );
3956    }
3957
3958    #[test]
3959    fn file_tree_resyncs_when_shown_after_hidden_scroll() {
3960        let area = Rect::new(0, 0, 120, 4);
3961        let mut viewer = tree_viewer();
3962
3963        viewer.handle_input(Event::Key(Key::Char('`')), area);
3964        viewer.apply(DiffAction::Scroll(Scroll::Lines(6)), area);
3965        assert_eq!(viewer.file_tree.target(), None);
3966
3967        assert_eq!(
3968            viewer.handle_input(Event::Key(Key::Char('`')), area),
3969            Control::Redraw
3970        );
3971
3972        assert_eq!(
3973            viewer.file_tree.target(),
3974            Some(FileTreeTarget::File(FileId::new(1)))
3975        );
3976    }
3977
3978    #[test]
3979    fn escape_keeps_quit_behavior_when_tree_is_hidden() {
3980        let area = Rect::new(0, 0, 80, 9);
3981        let mut viewer = tree_viewer();
3982
3983        assert_eq!(
3984            viewer.handle_input(Event::Key(Key::Esc), area),
3985            Control::Quit
3986        );
3987    }
3988
3989    #[test]
3990    fn shift_l_and_shift_h_collapse_and_expand_file_tree_folders() {
3991        let area = Rect::new(0, 0, 120, 9);
3992        let mut viewer = nested_tree_viewer();
3993
3994        viewer.handle_input(Event::Key(Key::Char('K')), area);
3995        assert_eq!(
3996            viewer.file_tree.target(),
3997            Some(FileTreeTarget::Directory(PathBuf::from("src")))
3998        );
3999
4000        viewer.handle_input(Event::Key(Key::Char('L')), area);
4001        viewer.handle_input(Event::Key(Key::Char('J')), area);
4002        assert_eq!(
4003            viewer.file_tree.target(),
4004            Some(FileTreeTarget::File(FileId::new(2)))
4005        );
4006
4007        viewer.handle_input(Event::Key(Key::Char('K')), area);
4008        viewer.handle_input(Event::Key(Key::Char('H')), area);
4009        viewer.handle_input(Event::Key(Key::Char('J')), area);
4010        assert_eq!(
4011            viewer.file_tree.target(),
4012            Some(FileTreeTarget::File(FileId::new(0)))
4013        );
4014    }
4015
4016    #[test]
4017    fn arrow_keys_do_not_operate_file_tree_folders() {
4018        let area = Rect::new(0, 0, 120, 9);
4019        let mut viewer = nested_tree_viewer();
4020
4021        viewer.handle_input(Event::Key(Key::Char('K')), area);
4022        assert_eq!(
4023            viewer.file_tree.target(),
4024            Some(FileTreeTarget::Directory(PathBuf::from("src")))
4025        );
4026
4027        assert_eq!(
4028            viewer.handle_input(Event::Key(Key::Left), area),
4029            Control::Continue
4030        );
4031        assert_eq!(
4032            viewer.handle_input(Event::Key(Key::Right), area),
4033            Control::Continue
4034        );
4035    }
4036
4037    #[test]
4038    fn left_click_on_file_tree_file_activates_it() {
4039        let area = Rect::new(0, 0, 120, 9);
4040        let mut viewer = tree_viewer();
4041
4042        assert_eq!(
4043            viewer.handle_input(left_click(2, 3, Modifiers::NONE), area),
4044            Control::Redraw
4045        );
4046
4047        assert_eq!(viewer.index.rows, 12);
4048        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
4049    }
4050
4051    #[test]
4052    fn left_click_on_file_tree_file_restores_its_hunk_focus() {
4053        let area = Rect::new(0, 0, 120, 4);
4054        let mut viewer = tree_viewer();
4055        let mut later = viewer.document.files[1].hunks[0].clone();
4056        later.id = HunkId::new(2);
4057        viewer.document.files[1].hunks.push(later);
4058        viewer.rebuild_index();
4059        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(2))));
4060        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
4061
4062        viewer.handle_input(left_click(2, 3, Modifiers::NONE), area);
4063
4064        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(2))));
4065        let target = viewer
4066            .focus_targets(FocusFilter::HunkNavigation)
4067            .into_iter()
4068            .find(|target| target.focus == DiffFocus::Hunk(HunkId::new(2)))
4069            .unwrap();
4070        assert!(
4071            (viewer.state.scroll.offset..viewer.state.scroll.offset + area.rows)
4072                .contains(&target.row)
4073        );
4074    }
4075
4076    #[test]
4077    fn file_tree_selection_can_anchor_final_file() {
4078        let area = Rect::new(0, 0, 120, 9);
4079        let mut viewer = tree_viewer();
4080
4081        assert_eq!(
4082            viewer.handle_input(Event::Key(Key::Char('J')), area),
4083            Control::Redraw
4084        );
4085
4086        assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(1))));
4087        assert_eq!(viewer.state().scroll.offset, 6);
4088    }
4089
4090    #[test]
4091    fn control_left_click_on_file_tree_file_jumps_to_it() {
4092        let area = Rect::new(0, 0, 120, 9);
4093        let mut viewer = tree_viewer();
4094        let rows = viewer.index.rows;
4095
4096        assert_eq!(
4097            viewer.handle_input(left_click(2, 3, Modifiers::CONTROL), area),
4098            Control::Redraw
4099        );
4100
4101        assert_eq!(viewer.index.rows, rows);
4102        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
4103    }
4104
4105    #[test]
4106    fn left_click_outside_visible_file_tree_is_ignored() {
4107        let mut viewer = tree_viewer();
4108
4109        assert_eq!(
4110            viewer.handle_input(left_click(50, 1, Modifiers::NONE), Rect::new(0, 0, 120, 9)),
4111            Control::Continue
4112        );
4113        assert_eq!(
4114            viewer.handle_input(left_click(2, 1, Modifiers::NONE), Rect::new(0, 0, 80, 9)),
4115            Control::Continue
4116        );
4117        assert_eq!(viewer.state().focus, None);
4118    }
4119
4120    #[test]
4121    fn left_click_on_file_tree_folder_selects_without_toggling() {
4122        let area = Rect::new(0, 0, 120, 9);
4123        let mut viewer = nested_tree_viewer();
4124
4125        assert_eq!(
4126            viewer.handle_input(left_click(4, 2, Modifiers::NONE), area),
4127            Control::Redraw
4128        );
4129        viewer.handle_input(Event::Key(Key::Char('J')), area);
4130
4131        assert_eq!(
4132            viewer.file_tree.target(),
4133            Some(FileTreeTarget::File(FileId::new(0)))
4134        );
4135    }
4136
4137    #[test]
4138    fn selected_folder_background_is_dimmer_than_active_file_background() {
4139        let area = Rect::new(0, 0, 120, 9);
4140        let mut viewer = nested_tree_viewer();
4141        let mut buffer = Buffer::empty(area);
4142
4143        viewer.handle_input(left_click(4, 2, Modifiers::NONE), area);
4144        viewer.render(area, &mut buffer);
4145
4146        assert_eq!(
4147            buffer.get(0, 2).map(|cell| cell.style().bg_color()),
4148            Some(Color::Fixed(234))
4149        );
4150        assert_eq!(
4151            buffer.get(0, 3).map(|cell| cell.style().bg_color()),
4152            Some(Color::Fixed(235))
4153        );
4154    }
4155
4156    #[test]
4157    fn left_click_can_select_parent_and_child_folders_after_folder_selection() {
4158        let area = Rect::new(0, 0, 120, 8);
4159        let mut viewer = deep_tree_viewer();
4160
4161        assert_eq!(
4162            viewer.handle_input(left_click(6, 3, Modifiers::NONE), area),
4163            Control::Redraw
4164        );
4165        assert_eq!(
4166            viewer.file_tree.target(),
4167            Some(FileTreeTarget::Directory(PathBuf::from("src/app")))
4168        );
4169
4170        assert_eq!(
4171            viewer.handle_input(left_click(4, 2, Modifiers::NONE), area),
4172            Control::Redraw
4173        );
4174        assert_eq!(
4175            viewer.file_tree.target(),
4176            Some(FileTreeTarget::Directory(PathBuf::from("src")))
4177        );
4178
4179        assert_eq!(
4180            viewer.handle_input(left_click(6, 5, Modifiers::NONE), area),
4181            Control::Redraw
4182        );
4183        assert_eq!(
4184            viewer.file_tree.target(),
4185            Some(FileTreeTarget::Directory(PathBuf::from("src/lib")))
4186        );
4187    }
4188
4189    #[test]
4190    fn left_click_on_file_tree_disclosure_toggles_folder() {
4191        let area = Rect::new(0, 0, 120, 9);
4192        let mut viewer = nested_tree_viewer();
4193
4194        assert_eq!(
4195            viewer.handle_input(left_click(2, 2, Modifiers::NONE), area),
4196            Control::Redraw
4197        );
4198        assert_eq!(viewer.file_tree.target(), None);
4199        viewer.handle_input(Event::Key(Key::Char('J')), area);
4200        assert_eq!(
4201            viewer.file_tree.target(),
4202            Some(FileTreeTarget::File(FileId::new(2)))
4203        );
4204
4205        viewer.handle_input(Event::Key(Key::Char('K')), area);
4206        assert_eq!(
4207            viewer.handle_input(left_click(2, 2, Modifiers::NONE), area),
4208            Control::Redraw
4209        );
4210        viewer.handle_input(Event::Key(Key::Char('J')), area);
4211
4212        assert_eq!(
4213            viewer.file_tree.target(),
4214            Some(FileTreeTarget::File(FileId::new(0)))
4215        );
4216    }
4217
4218    #[test]
4219    fn left_click_on_file_tree_disclosure_keeps_current_selection() {
4220        let area = Rect::new(0, 0, 120, 8);
4221        let mut viewer = nested_tree_viewer();
4222
4223        viewer.handle_input(left_click(4, 4, Modifiers::NONE), area);
4224        assert_eq!(
4225            viewer.file_tree.target(),
4226            Some(FileTreeTarget::File(FileId::new(1)))
4227        );
4228
4229        assert_eq!(
4230            viewer.handle_input(left_click(2, 2, Modifiers::NONE), area),
4231            Control::Redraw
4232        );
4233
4234        assert_eq!(
4235            viewer.file_tree.target(),
4236            Some(FileTreeTarget::File(FileId::new(1)))
4237        );
4238    }
4239
4240    #[test]
4241    fn mouse_wheel_inputs_move_three_rows() {
4242        let area = Rect::new(0, 0, 80, 9);
4243        let mut viewer = scroll_viewer();
4244        let down = Event::Mouse(Mouse::Press {
4245            button: MouseButton::WheelDown,
4246            at: Point::new(0, 0),
4247            modifiers: Modifiers::NONE,
4248        });
4249        let up = Event::Mouse(Mouse::Press {
4250            button: MouseButton::WheelUp,
4251            at: Point::new(0, 0),
4252            modifiers: Modifiers::NONE,
4253        });
4254
4255        viewer.handle_input(down.clone(), area);
4256        assert_eq!(viewer.state().scroll.offset, 3);
4257        viewer.handle_input(down, area);
4258        assert_eq!(viewer.state().scroll.offset, 6);
4259        viewer.handle_input(up, area);
4260        assert_eq!(viewer.state().scroll.offset, 3);
4261    }
4262
4263    #[test]
4264    fn control_scrolls_like_vim() {
4265        let area = Rect::new(0, 0, 80, 10);
4266        let mut viewer = scroll_viewer();
4267
4268        viewer.handle_input(Event::Key(Key::Ctrl('d')), area);
4269        assert_eq!(viewer.state().scroll.offset, 5);
4270        viewer.handle_input(Event::Key(Key::Ctrl('u')), area);
4271        assert_eq!(viewer.state().scroll.offset, 0);
4272    }
4273
4274    #[test]
4275    fn space_pages_down_like_less() {
4276        let area = Rect::new(0, 0, 80, 10);
4277        let mut viewer = scroll_viewer();
4278
4279        viewer.handle_input(Event::Key(Key::Char(' ')), area);
4280        assert_eq!(viewer.state().scroll.offset, 10);
4281    }
4282
4283    #[test]
4284    fn highlight_requests_include_next_page_uncached_rows() {
4285        let mut viewer = sample_viewer();
4286        let area = Rect::new(0, 0, 64, 5);
4287
4288        let first = viewer.highlight_requests(area);
4289        let second = viewer.highlight_requests(area);
4290
4291        assert_eq!(first.len(), 5);
4292        assert!(second.is_empty());
4293        assert_eq!(
4294            first[0].source.line(first[0].key.source_line),
4295            Some("context")
4296        );
4297        assert_eq!(first[1].source.line(first[1].key.source_line), Some("old"));
4298        assert_eq!(first[4].source.line(first[4].key.source_line), Some("tail"));
4299        assert_eq!(first[0].key.theme, "auto");
4300    }
4301
4302    #[test]
4303    fn visible_and_lookahead_highlight_requests_partition_combined_requests() {
4304        let area = Rect::new(0, 0, 64, 5);
4305        let mut combined = scroll_viewer();
4306        let mut split = scroll_viewer();
4307
4308        let combined_requests = combined.highlight_requests(area);
4309        let mut split_requests = split.visible_highlight_requests(area);
4310        let visible_len = split_requests.len();
4311        split_requests.extend(split.lookahead_highlight_requests(area));
4312
4313        assert!(visible_len > 0);
4314        assert!(visible_len < split_requests.len());
4315        assert_eq!(split_requests, combined_requests);
4316    }
4317
4318    #[test]
4319    fn cancelled_highlight_requests_can_be_requested_again() {
4320        let mut viewer = sample_viewer();
4321        let area = Rect::new(0, 0, 64, 5);
4322
4323        let first = viewer.highlight_requests(area);
4324        assert!(!first.is_empty());
4325        viewer.cancel_highlights(first.clone());
4326        let second = viewer.highlight_requests(area);
4327
4328        assert_eq!(second, first);
4329    }
4330
4331    #[test]
4332    fn pending_highlight_requests_can_all_be_retried() {
4333        let mut viewer = sample_viewer();
4334        let area = Rect::new(0, 0, 64, 5);
4335
4336        let first = viewer.highlight_requests(area);
4337        assert!(!first.is_empty());
4338        viewer.retry_pending_highlights();
4339        let second = viewer.highlight_requests(area);
4340
4341        assert_eq!(second, first);
4342    }
4343
4344    #[test]
4345    fn highlight_requests_use_hunk_side_sources() {
4346        let mut viewer = two_hunk_viewer();
4347
4348        let request = viewer
4349            .highlight_requests(Rect::new(0, 0, 64, 20))
4350            .into_iter()
4351            .find(|request| request.hunk == HunkId::new(1))
4352            .unwrap();
4353
4354        assert_eq!(request.source.head, 10);
4355        assert_eq!(request.source.text.as_ref(), "keep\nafter");
4356        assert_eq!(request.source.line(10), Some("keep"));
4357        assert_eq!(request.source.line(11), Some("after"));
4358        assert_eq!(request.source.line(12), None);
4359    }
4360
4361    #[cfg(feature = "builtins")]
4362    #[test]
4363    fn repo_highlight_results_style_css_custom_properties_from_real_context() {
4364        let document = DiffDocument::decode_str(
4365            "\
4366diff --git a/assets/css/style.css b/assets/css/style.css
4367index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
4368--- a/assets/css/style.css
4369+++ b/assets/css/style.css
4370@@ -12,7 +12,8 @@
4371   --color-foreground: #112;
4372   --color-headers: #222;
4373   --color-background: #d3d1d1;
4374-  --color-background-light: #dedddd;
4375+  --color-background-light: #dad8d8;
4376+  --color-background-dark: #cecccc;
4377   --color-dim: #334;
4378   --color-dimmer: #666;
4379   --color-subtle: #888;
4380",
4381        )
4382        .unwrap();
4383        let mut viewer = DiffViewer::new(document, DiffOptions::default());
4384        let full = DiffDocument::decode_str(
4385            "\
4386diff --git a/assets/css/style.css b/assets/css/style.css
4387index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
4388--- a/assets/css/style.css
4389+++ b/assets/css/style.css
4390@@ -1,19 +1,20 @@
4391 html {
4392   box-sizing: border-box;
4393 }
4394 *, *::before, *::after {
4395   box-sizing: inherit;
4396 }
4397 body {
4398   margin: 0;
4399 }
4400 :root {
4401   color-scheme: light;
4402   --color-foreground: #112;
4403   --color-headers: #222;
4404   --color-background: #d3d1d1;
4405-  --color-background-light: #dedddd;
4406+  --color-background-light: #dad8d8;
4407+  --color-background-dark: #cecccc;
4408   --color-dim: #334;
4409   --color-dimmer: #666;
4410   --color-subtle: #888;
4411 }
4412",
4413        )
4414        .unwrap();
4415        let mut registry = syntax::Registry::default();
4416        registry.add_theme(
4417            syntax::Theme::parse(include_str!("themes/rustik-catppuccin-mocha.json")).unwrap(),
4418        );
4419        registry.add_grammar(syntax::Grammar::from_str(syntax::syntaxes::CSS).unwrap());
4420        let mut highlighter = crate::BuiltinHighlighter::new(registry, "rustik-catppuccin-mocha");
4421
4422        // Enrich the visible requests with source context, as the pager
4423        // worker does, so the highlighter sees the CSS rule in context.
4424        let source = full.files[0].highlight_source(DiffSide::New).unwrap();
4425        let mut requests = viewer.highlight_requests(Rect::new(0, 0, 80, 20));
4426        for request in &mut requests {
4427            if request.key.side == DiffSide::New {
4428                request.source = source.clone();
4429            }
4430        }
4431        let result = highlighter
4432            .highlight_requests(requests)
4433            .into_iter()
4434            .find(|result| {
4435                result.key.text_hash == {
4436                    use std::collections::hash_map::DefaultHasher;
4437                    use std::hash::{Hash, Hasher};
4438
4439                    let mut hasher = DefaultHasher::new();
4440                    "  --color-background-light: #dad8d8;".hash(&mut hasher);
4441                    hasher.finish()
4442                }
4443            })
4444            .unwrap();
4445
4446        let color = Color::RGB(137, 180, 250);
4447        let variable = result
4448            .line
4449            .labels()
4450            .iter()
4451            .find(|label| label.content().contains("--color-background-light"))
4452            .unwrap();
4453
4454        assert_eq!(variable.paint.style().fg_color(), color);
4455    }
4456
4457    #[test]
4458    fn metadata_lookup_matches_rendered_diff_rows() {
4459        let viewer = sample_viewer();
4460        for row in 0..viewer.index.rows {
4461            assert_eq!(
4462                viewer.diff_meta_at(row),
4463                viewer.render_row(row, 64).and_then(|row| row.diff)
4464            );
4465        }
4466    }
4467
4468    #[test]
4469    fn highlight_results_replace_pending_with_cached_lines() {
4470        let mut viewer = sample_viewer();
4471        let area = Rect::new(0, 0, 64, 5);
4472        let request = viewer.highlight_requests(area).into_iter().next().unwrap();
4473        let fresh = HighlightResult::new(request, Line::new(Label::new("fresh").fg(Color::Red)));
4474        assert!(viewer.apply_highlights([fresh]));
4475        assert_eq!(viewer.highlights.len(), 1);
4476    }
4477
4478    #[test]
4479    fn empty_highlight_result_does_not_replace_nonempty_source() {
4480        let mut viewer = sample_viewer();
4481        let area = Rect::new(0, 0, 64, 5);
4482        let request = viewer
4483            .highlight_requests(area)
4484            .into_iter()
4485            .find(|request| {
4486                viewer
4487                    .document
4488                    .files
4489                    .iter()
4490                    .flat_map(|file| file.hunks.iter().flat_map(|hunk| hunk.lines.iter()))
4491                    .any(|line| line.id == request.row && !line.text.is_empty())
4492            })
4493            .unwrap();
4494        let key = request.key.clone();
4495        let empty = HighlightResult::new(request, Line::blank());
4496
4497        assert!(!viewer.apply_highlights([empty]));
4498        assert!(!viewer.highlights.contains_key(&key));
4499    }
4500
4501    #[test]
4502    fn for_hunks_highlight_requests_use_hunk_side_sources() {
4503        // The single-hunk document keeps the original file id, so the source
4504        // lookup must resolve files by id rather than by position.
4505        let full = DiffDocument::decode_str(
4506            "\
4507diff --git a/first.rs b/first.rs
4508index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
4509--- a/first.rs
4510+++ b/first.rs
4511@@ -1 +1 @@
4512-old
4513+new
4514diff --git a/second.rs b/second.rs
4515index 3333333333333333333333333333333333333333..4444444444444444444444444444444444444444 100644
4516--- a/second.rs
4517+++ b/second.rs
4518@@ -10,3 +10,3 @@
4519 keep
4520-before
4521+after
4522 tail
4523",
4524        )
4525        .unwrap();
4526        let file = &full.files[1];
4527        let single = DiffDocument::for_hunks(file, [file.hunks[0].clone()]);
4528        let mut viewer = DiffViewer::new(single, DiffOptions::default());
4529
4530        let requests = viewer.highlight_requests(Rect::new(0, 0, 64, 20));
4531
4532        assert_eq!(requests.len(), 4);
4533        for request in &requests {
4534            let side_text = match request.key.side {
4535                DiffSide::Old => "keep\nbefore\ntail",
4536                DiffSide::New => "keep\nafter\ntail",
4537            };
4538            assert_eq!(request.source.head, 10);
4539            assert_eq!(request.source.text.as_ref(), side_text);
4540        }
4541    }
4542
4543    #[test]
4544    fn single_hunk_viewer_highlights_each_visible_source_row() {
4545        let full = DiffDocument::decode_str(
4546            "\
4547diff --git a/a.rs b/a.rs
4548index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
4549--- a/a.rs
4550+++ b/a.rs
4551@@ -1 +1,5 @@
4552-old
4553+fn main() {
4554+    let value = true;
4555+    if value {
4556+        return;
4557+    }
4558",
4559        )
4560        .unwrap();
4561        let single = DiffDocument::for_hunks(&full.files[0], [full.files[0].hunks[0].clone()]);
4562        let mut viewer = DiffViewer::new(single.clone(), DiffOptions::default());
4563        let mut highlighter = crate::Builtins::highlighter(&single).unwrap();
4564
4565        assert!(viewer.apply_visible_highlights(Rect::new(0, 0, 80, 20), &mut highlighter));
4566
4567        let rendered = (0..viewer.index.rows)
4568            .filter_map(|row| viewer.render_row(row, 80))
4569            .map(|row| row.line)
4570            .collect::<Vec<_>>();
4571        for token in ["fn", "let", "if", "return"] {
4572            assert!(
4573                rendered.iter().any(|line| {
4574                    line.labels().iter().any(|label| {
4575                        label.content() == token && label.paint.style().fg_color() != Color::Unset
4576                    })
4577                }),
4578                "missing highlighted token {token}: {rendered:#?}"
4579            );
4580        }
4581    }
4582
4583    #[test]
4584    fn apply_visible_highlights_runs_one_visible_batch() {
4585        let mut viewer = sample_viewer();
4586        let area = Rect::new(0, 0, 64, 5);
4587        let mut highlighter = RecordingHighlighter::default();
4588
4589        assert!(viewer.apply_visible_highlights(area, &mut highlighter));
4590        assert_eq!(highlighter.batches, 1);
4591        assert_eq!(viewer.highlights.len(), 5);
4592
4593        assert!(!viewer.apply_visible_highlights(area, &mut highlighter));
4594        assert_eq!(highlighter.batches, 1);
4595    }
4596
4597    #[test]
4598    fn apply_highlights_populates_word_diff_cache() {
4599        // Word-diff ranges are computed on demand when the first highlight
4600        // result lands for a hunk, so the cached overlaid `Line` can be built.
4601        let mut viewer = word_diff_viewer();
4602        let area = Rect::new(0, 0, 80, 20);
4603        let request = viewer.highlight_requests(area).into_iter().next().unwrap();
4604        let hunk_id = request.hunk;
4605        let result = HighlightResult::new(request, Line::new("highlighted"));
4606        viewer.apply_highlights([result]);
4607
4608        let changes = viewer.word_diffs.get(&hunk_id).unwrap();
4609        let added = viewer.document.files[0].hunks[0]
4610            .lines
4611            .iter()
4612            .find(|line| line.kind == DiffLineKind::Addition)
4613            .unwrap()
4614            .id;
4615        assert!(
4616            changes.get(&added).is_some_and(|ranges| !ranges.is_empty()),
4617            "expected new-side row to have changed ranges"
4618        );
4619    }
4620
4621    #[test]
4622    fn apply_highlights_bakes_word_diff_overlay_into_cache() {
4623        // The overlay should be applied at insert time, so the cached `Line`
4624        // already carries the bright bg and the render path performs no merge.
4625        let mut viewer = word_diff_viewer();
4626        let area = Rect::new(0, 0, 80, 20);
4627        let request = viewer
4628            .highlight_requests(area)
4629            .into_iter()
4630            .find(|request| request.key.side == DiffSide::New)
4631            .unwrap();
4632        let key = request.key.clone();
4633        let plain_text = viewer
4634            .document
4635            .files
4636            .iter()
4637            .flat_map(|file| file.hunks.iter().flat_map(|hunk| hunk.lines.iter()))
4638            .find(|line| line.id == request.row)
4639            .unwrap()
4640            .text
4641            .clone();
4642        let result = HighlightResult::new(request, Line::new(Label::new(plain_text.as_str())));
4643        assert!(viewer.apply_highlights([result]));
4644
4645        let cached = viewer.highlights.get(&key).unwrap();
4646        let bright = viewer.options.diff_palette.positive_word_bg;
4647        assert!(
4648            cached
4649                .labels()
4650                .iter()
4651                .any(|label| label.paint.style.bg_color() == bright),
4652            "expected the cached line to already include the bright word-diff bg"
4653        );
4654    }
4655
4656    fn word_diff_viewer() -> DiffViewer {
4657        // A similar-enough pair: only "mut " and ", opts: Options" change, so
4658        // the similarity gate is satisfied and word-diff ranges are emitted.
4659        let document = DiffDocument::decode_str(
4660            "\
4661diff --git a/a.rs b/a.rs
4662index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
4663--- a/a.rs
4664+++ b/a.rs
4665@@ -1 +1 @@
4666-fn render(view: &View) {
4667+fn render(view: &mut View, opts: Options) {
4668",
4669        )
4670        .unwrap();
4671        DiffViewer::new(document, DiffOptions::default())
4672    }
4673
4674    /// A [`DiffRepository`] that returns a canned patch and records refetch requests.
4675    struct FakeRepo {
4676        /// Raw unified-diff bytes handed back from every refetch.
4677        patch: Vec<u8>,
4678        /// Context width and paths of each `diff` call, in call order.
4679        calls: std::cell::RefCell<Vec<(usize, Vec<PathBuf>)>>,
4680    }
4681
4682    impl FakeRepo {
4683        /// Builds a repo whose refetches return `patch` as raw diff bytes.
4684        fn new(patch: &str) -> Self {
4685            Self {
4686                patch: patch.as_bytes().to_vec(),
4687                calls: std::cell::RefCell::new(Vec::new()),
4688            }
4689        }
4690    }
4691
4692    impl DiffRepository for FakeRepo {
4693        fn diff(
4694            &self,
4695            context_lines: usize,
4696            paths: &[&std::path::Path],
4697        ) -> Result<Vec<u8>, RepoError> {
4698            let paths = paths.iter().map(|path| path.to_path_buf()).collect();
4699            self.calls.borrow_mut().push((context_lines, paths));
4700            Ok(self.patch.clone())
4701        }
4702    }
4703
4704    #[test]
4705    fn full_file_state_belongs_to_the_viewer_context() {
4706        let area = Rect::new(0, 0, 64, 9);
4707        let patch = "\
4708diff --git a/a.rs b/a.rs
4709index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
4710--- a/a.rs
4711+++ b/a.rs
4712@@ -1,3 +1,4 @@ fn main
4713 context
4714-old
4715+new
4716+extra
4717 tail
4718";
4719        let mut viewers = [sample_viewer(), sample_viewer()];
4720
4721        let update = viewers[0]
4722            .context_request(ContextChange::ToggleFile)
4723            .unwrap()
4724            .decode(patch.as_bytes())
4725            .unwrap()
4726            .unwrap();
4727        viewers[0].apply_context_update(update, area);
4728
4729        assert!(viewers[0].is_full_file());
4730        assert!(!viewers[1].is_full_file());
4731
4732        let update = viewers[1]
4733            .context_request(ContextChange::ToggleFile)
4734            .unwrap()
4735            .decode(patch.as_bytes())
4736            .unwrap()
4737            .unwrap();
4738        viewers[1].apply_context_update(update, area);
4739
4740        assert!(viewers[1].is_full_file());
4741
4742        let mut pathless = sample_viewer();
4743        pathless.document.files[0].header.old_path = None;
4744        pathless.document.files[0].header.new_path = None;
4745        assert!(
4746            pathless
4747                .context_request(ContextChange::ToggleFile)
4748                .is_none()
4749        );
4750        assert!(!pathless.is_full_file());
4751    }
4752
4753    #[test]
4754    fn async_context_request_decodes_and_applies_update() {
4755        let mut viewer = sample_viewer();
4756        viewer.options.hunk_focus = HunkFocus::DimUnfocused;
4757        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
4758        let area = Rect::new(0, 0, 64, 9);
4759        let repo = FakeRepo::new(
4760            "\
4761diff --git a/a.rs b/a.rs
4762index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
4763--- a/a.rs
4764+++ b/a.rs
4765@@ -1,5 +1,6 @@ fn main
4766 lead
4767 context
4768-old
4769+new
4770+extra
4771 tail
4772 trail
4773",
4774        );
4775        let request = viewer.context_request(ContextChange::Increase).unwrap();
4776        let paths = request.paths().collect::<Vec<_>>();
4777        let patch = repo.diff(request.context_lines(), &paths).unwrap();
4778        drop(paths);
4779        let update = request.decode(&patch).unwrap().unwrap();
4780
4781        viewer.apply_context_update(update, area);
4782        let calls = repo.calls.borrow();
4783        assert_eq!(calls.len(), 1);
4784        assert_eq!(calls[0].0, 4);
4785        assert_eq!(calls[0].1, vec![PathBuf::from("a.rs")]);
4786        assert_eq!(viewer.document.files[0].hunks[0].header.old_size, 5);
4787        let expanded = viewer.render_row(HUNK_BODY_START, 64).unwrap().line;
4788        let changed = viewer.render_row(HUNK_BODY_START + 2, 64).unwrap().line;
4789        assert!(format!("{}", expanded.styled()).contains("\x1b[2m"));
4790        assert!(!format!("{}", changed.styled()).contains("\x1b[2m"));
4791    }
4792
4793    #[test]
4794    fn context_update_keeps_focused_hunk_at_its_screen_row() {
4795        let mut viewer = two_hunk_viewer();
4796        let area = Rect::new(0, 0, 64, 4);
4797        let focus = DiffFocus::Hunk(HunkId::new(1));
4798        viewer.set_focus(Some(focus));
4799        viewer.set_scroll(5);
4800        let old_row = viewer
4801            .focus_targets(FocusFilter::HunkNavigation)
4802            .into_iter()
4803            .find(|target| target.focus == focus)
4804            .unwrap()
4805            .row
4806            - viewer.state.scroll.offset;
4807        let request = viewer.context_request(ContextChange::Increase).unwrap();
4808        let update = request
4809            .decode(include_bytes!("../tests/golden/expanded_context.diff"))
4810            .unwrap()
4811            .unwrap();
4812
4813        viewer.apply_context_update(update, area);
4814
4815        let new_row = viewer
4816            .focus_targets(FocusFilter::HunkNavigation)
4817            .into_iter()
4818            .find(|target| target.focus == focus)
4819            .unwrap()
4820            .row
4821            - viewer.state.scroll.offset;
4822        assert_eq!(new_row, old_row);
4823    }
4824
4825    #[test]
4826    fn file_replacement_keeps_focused_hunk_at_its_screen_row() {
4827        let mut viewer = two_hunk_viewer();
4828        let area = Rect::new(0, 0, 64, 4);
4829        let focus = DiffFocus::Hunk(HunkId::new(1));
4830        viewer.set_focus(Some(focus));
4831        viewer.set_scroll(5);
4832        let old_row = viewer
4833            .focus_targets(FocusFilter::HunkNavigation)
4834            .into_iter()
4835            .find(|target| target.focus == focus)
4836            .unwrap()
4837            .row
4838            - viewer.state.scroll.offset;
4839        let mut file = viewer.document.files[0].clone();
4840        file.hunks.remove(0);
4841
4842        viewer.replace_file_diffs_anchored([file], area);
4843
4844        let new_row = viewer
4845            .focus_targets(FocusFilter::HunkNavigation)
4846            .into_iter()
4847            .find(|target| target.focus == focus)
4848            .unwrap()
4849            .row
4850            - viewer.state.scroll.offset;
4851        assert_eq!(new_row, old_row);
4852    }
4853
4854    #[test]
4855    fn file_replacement_selects_hunk_before_removed_last_hunk() {
4856        let mut viewer = two_hunk_viewer();
4857        let area = Rect::new(0, 0, 64, 20);
4858        let mut third = viewer.document.files[0].hunks[1].clone();
4859        third.id = HunkId::new(2);
4860        viewer.document.files[0].hunks.push(third);
4861        viewer.rebuild_index();
4862        viewer.set_scroll(100);
4863        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(2))));
4864        let mut file = viewer.document.files[0].clone();
4865        file.hunks.remove(2);
4866
4867        viewer.replace_file_diffs_anchored([file], area);
4868
4869        assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
4870    }
4871
4872    #[test]
4873    fn file_replacement_skips_hidden_hunk_predecessors() {
4874        let mut viewer = commit_viewer();
4875        let area = Rect::new(0, 0, 64, 20);
4876        let mut third = viewer.document.files[0].hunks[1].clone();
4877        third.id = HunkId::new(2);
4878        viewer.document.files[0].hunks.push(third);
4879        viewer.rebuild_index();
4880        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(2))));
4881        let mut file = viewer.document.files[0].clone();
4882        file.hunks.clear();
4883
4884        viewer.replace_file_diffs_anchored([file], area);
4885
4886        assert_eq!(viewer.state().focus, Some(DiffFocus::Commit));
4887    }
4888
4889    #[test]
4890    fn context_request_targets_focused_file() {
4891        let mut viewer = two_file_viewer();
4892        viewer.set_focus(Some(DiffFocus::File(FileId::new(1))));
4893
4894        let repo = FakeRepo::new(
4895            "\
4896diff --git a/a.rs b/a.rs
4897index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
4898--- a/a.rs
4899+++ b/a.rs
4900@@ -1,3 +1,4 @@ fn a
4901 context
4902-old
4903+new
4904+extra
4905 tail
4906diff --git a/b.rs b/b.rs
4907index 3333333333333333333333333333333333333333..4444444444444444444444444444444444444444 100644
4908--- a/b.rs
4909+++ b/b.rs
4910@@ -1,3 +1,3 @@ fn b
4911 keep
4912-before
4913+after
4914 trail
4915",
4916        );
4917
4918        let request = viewer.context_request(ContextChange::Increase).unwrap();
4919        let paths = request.paths().collect::<Vec<_>>();
4920        let patch = repo.diff(request.context_lines(), &paths).unwrap();
4921        drop(paths);
4922        let update = request.decode(&patch).unwrap().unwrap();
4923        viewer.apply_context_update(update, Rect::new(0, 0, 64, 20));
4924
4925        let calls = repo.calls.borrow();
4926        assert_eq!(calls.len(), 1);
4927        assert_eq!(calls[0].1, vec![PathBuf::from("b.rs")]);
4928    }
4929
4930    /// Test decorator marking every file and hunk with fixed decorations.
4931    #[derive(Clone, Debug, Default)]
4932    struct TestDecorator;
4933
4934    impl DiffDecorator for TestDecorator {
4935        fn file(&self, _file: FileId) -> FileDecoration {
4936            FileDecoration {
4937                status: Some(rustik_tui::Paint::new('โœ”')),
4938                annotations: vec![Line::new("2 c")],
4939                progress: None,
4940                stats: None,
4941            }
4942        }
4943
4944        fn hunk(&self, _file: FileId, _hunk: HunkId) -> HunkDecoration {
4945            HunkDecoration {
4946                gutter: Some(tui::Paint::new('โ–').fg(colors::rgb::GREEN)),
4947                corner: Line::new("โ—†"),
4948                style: Some(Style::default().bg(Color::Fixed(99))),
4949            }
4950        }
4951    }
4952
4953    #[test]
4954    fn hunk_decoration_does_not_change_size() {
4955        let constraints = Constraint::tight(80);
4956        let plain = sample_viewer().size(constraints);
4957
4958        let mut decorated = sample_viewer();
4959        decorated.set_decorator(TestDecorator);
4960
4961        assert_eq!(decorated.size(constraints), plain);
4962    }
4963
4964    #[test]
4965    fn hunk_gutter_draws_beside_changed_rows_only() {
4966        let area = Rect::new(0, 0, 80, 12);
4967        let mut viewer = sample_viewer();
4968        viewer.set_decorator(TestDecorator);
4969        let mut buffer = Buffer::empty(area);
4970
4971        viewer.render(area, &mut buffer);
4972
4973        for row in [
4974            HUNK_BODY_START + 1,
4975            HUNK_BODY_START + 2,
4976            HUNK_BODY_START + 3,
4977        ] {
4978            let gutter = buffer.get(2, row).unwrap();
4979            assert_eq!(gutter.glyph(), "โ–");
4980            assert_eq!(gutter.style().fg_color(), colors::rgb::GREEN);
4981        }
4982        for row in [HUNK_BODY_START, HUNK_BODY_START + 4] {
4983            assert_eq!(buffer.get(2, row).unwrap().glyph(), " ");
4984        }
4985    }
4986
4987    #[test]
4988    fn file_decoration_renders_status_and_annotation_in_header() {
4989        let area = Rect::new(0, 0, 80, 12);
4990        let mut viewer = sample_viewer();
4991        viewer.set_decorator(TestDecorator);
4992        let mut buffer = Buffer::empty(area);
4993
4994        viewer.render(area, &mut buffer);
4995
4996        // Row 0 is the card's top border; row 1 is the file header.
4997        let header = buffer.line(1);
4998        assert!(header.contains('โœ”'), "header: {header:?}");
4999        assert!(header.contains("2 c"), "header: {header:?}");
5000        assert!(header.contains("2 c  ยท"), "header: {header:?}");
5001    }
5002
5003    #[test]
5004    fn file_header_uses_file_kind_marker() {
5005        let area = Rect::new(0, 0, 80, 12);
5006        let document = sample_viewer().document().clone();
5007        let mut viewer = DiffViewer::new(document, DiffOptions::default());
5008        let mut buffer = Buffer::empty(area);
5009
5010        viewer.render(area, &mut buffer);
5011
5012        let header = buffer.line(1);
5013        assert!(header.contains('โŠ™'), "header: {header:?}");
5014    }
5015
5016    #[test]
5017    fn file_header_prefers_decoration_status() {
5018        let area = Rect::new(0, 0, 80, 12);
5019        let document = sample_viewer().document().clone();
5020        let mut viewer = DiffViewer::new(document, DiffOptions::default());
5021        viewer.set_decorator(TestDecorator);
5022        let mut buffer = Buffer::empty(area);
5023
5024        viewer.render(area, &mut buffer);
5025
5026        let header = buffer.line(1);
5027        assert!(header.contains('โœ”'), "header: {header:?}");
5028        assert!(!header.contains('โŠ™'), "header: {header:?}");
5029    }
5030
5031    #[test]
5032    fn file_decoration_renders_status_in_file_tree() {
5033        let area = Rect::new(0, 0, 100, 12);
5034        let mut viewer = tree_viewer();
5035        viewer.set_decorator(TestDecorator);
5036        let mut buffer = Buffer::empty(area);
5037
5038        viewer.render(area, &mut buffer);
5039
5040        let tree = (0..area.rows)
5041            .map(|row| buffer.line(row).chars().take(28).collect::<String>())
5042            .collect::<Vec<_>>()
5043            .join("\n");
5044        assert!(tree.contains('โœ”'), "tree: {tree:?}");
5045    }
5046
5047    #[test]
5048    fn hunk_decoration_renders_corner_on_first_body_row_only() {
5049        let area = Rect::new(0, 0, 80, 12);
5050        let mut viewer = sample_viewer();
5051        viewer.set_decorator(TestDecorator);
5052        let mut buffer = Buffer::empty(area);
5053
5054        viewer.render(area, &mut buffer);
5055
5056        let first_body = HUNK_BODY_START;
5057        let column = (0..area.cols).find(|&x| {
5058            buffer
5059                .get(x, first_body)
5060                .is_some_and(|cell| cell.glyph() == "โ—†")
5061        });
5062        assert!(column.is_some(), "row: {:?}", buffer.line(first_body));
5063        // The corner sits flush against the card's right edge.
5064        assert!(
5065            column.unwrap() >= area.cols / 2,
5066            "corner column: {column:?}"
5067        );
5068        // Later body rows carry no corner marker.
5069        assert!(!buffer.line(first_body + 1).contains('โ—†'));
5070    }
5071
5072    #[test]
5073    fn hunk_decoration_style_composes_onto_body_rows() {
5074        let area = Rect::new(0, 0, 80, 12);
5075        let mut viewer = sample_viewer();
5076        viewer.set_decorator(TestDecorator);
5077        let mut buffer = Buffer::empty(area);
5078
5079        viewer.render(area, &mut buffer);
5080
5081        let first_body = HUNK_BODY_START;
5082        // Content cells of a hunk body row carry the decoration background.
5083        let decorated = (0..area.cols)
5084            .filter(|&x| {
5085                buffer
5086                    .get(x, first_body)
5087                    .is_some_and(|cell| cell.style().bg_color() == Color::Fixed(99))
5088            })
5089            .count();
5090        assert!(decorated > 0, "row: {:?}", buffer.line(first_body));
5091
5092        // A plain viewer renders no decoration background on the same row.
5093        let mut plain = sample_viewer();
5094        let mut plain_buffer = Buffer::empty(area);
5095        plain.render(area, &mut plain_buffer);
5096        assert!((0..area.cols).all(|x| {
5097            plain_buffer
5098                .get(x, first_body)
5099                .is_none_or(|cell| cell.style().bg_color() != Color::Fixed(99))
5100        }));
5101    }
5102
5103    #[test]
5104    fn selected_hunk_ignores_inactive_decoration_style() {
5105        let area = Rect::new(0, 0, 80, 12);
5106        let mut viewer = sample_viewer();
5107        viewer.set_decorator(TestDecorator);
5108        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
5109        let mut buffer = Buffer::empty(area);
5110
5111        viewer.render(area, &mut buffer);
5112
5113        assert!((0..area.cols).all(|x| {
5114            buffer
5115                .get(x, HUNK_BODY_START)
5116                .is_none_or(|cell| cell.style().bg_color() != Color::Fixed(99))
5117        }));
5118        assert_eq!(buffer.get(2, HUNK_BODY_START + 1).unwrap().glyph(), "โ–");
5119    }
5120
5121    #[test]
5122    fn hunk_focus_dims_other_hunk_source_without_replacing_foreground() {
5123        let document = two_hunk_viewer().document().clone();
5124        let mut viewer = DiffViewer::new(
5125            document,
5126            DiffOptions {
5127                hunk_focus: HunkFocus::DimUnfocused,
5128                ..DiffOptions::default()
5129            },
5130        );
5131
5132        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
5133
5134        let focused = viewer.render_row(3, 64).unwrap().line;
5135        let muted = viewer.render_row(7, 64).unwrap().line;
5136        let muted_deletion = viewer.render_row(8, 64).unwrap().line;
5137        let muted_addition = viewer.render_row(9, 64).unwrap().line;
5138        let focused_number = focused
5139            .labels()
5140            .iter()
5141            .find(|label| label.content().contains('1'))
5142            .unwrap();
5143        let focused_source = focused
5144            .labels()
5145            .iter()
5146            .find(|label| label.content().contains("keep"))
5147            .unwrap();
5148        let muted_source = muted
5149            .labels()
5150            .iter()
5151            .find(|label| label.content().contains("keep"))
5152            .unwrap();
5153        let muted_deletion_source = muted_deletion
5154            .labels()
5155            .iter()
5156            .find(|label| label.content().contains("before"))
5157            .unwrap();
5158        let muted_addition_source = muted_addition
5159            .labels()
5160            .iter()
5161            .find(|label| label.content().contains("after"))
5162            .unwrap();
5163
5164        assert_eq!(
5165            focused_number.paint.style().fg_color(),
5166            SELECTED_LINE_NUMBER_FG
5167        );
5168        assert_eq!(focused_source.paint.style().fg_color(), Color::Unset);
5169        assert_eq!(muted_source.paint.style().fg_color(), Color::Unset);
5170        assert_eq!(
5171            muted_deletion_source.background(),
5172            DiffViewer::muted_background(viewer.options.diff_palette.negative_row_bg)
5173        );
5174        assert_eq!(
5175            muted_addition_source.background(),
5176            DiffViewer::muted_background(viewer.options.diff_palette.positive_row_bg)
5177        );
5178        assert!(format!("{}", muted.styled()).contains("\x1b[2m"));
5179    }
5180
5181    #[test]
5182    fn hunk_focus_requests_unfocused_highlights() {
5183        let document = two_hunk_viewer().document().clone();
5184        let mut viewer = DiffViewer::new(
5185            document,
5186            DiffOptions {
5187                hunk_focus: HunkFocus::DimUnfocused,
5188                ..DiffOptions::default()
5189            },
5190        );
5191
5192        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
5193        let requests = viewer.highlight_requests(Rect::new(0, 0, 64, 20));
5194
5195        assert!(!requests.is_empty());
5196        assert!(
5197            requests
5198                .iter()
5199                .any(|request| request.hunk == HunkId::new(0))
5200        );
5201        assert!(
5202            requests
5203                .iter()
5204                .any(|request| request.hunk == HunkId::new(1))
5205        );
5206    }
5207
5208    #[test]
5209    fn hunk_focus_uses_cached_unfocused_highlights() {
5210        let document = two_hunk_viewer().document().clone();
5211        let mut viewer = DiffViewer::new(
5212            document,
5213            DiffOptions {
5214                hunk_focus: HunkFocus::DimUnfocused,
5215                ..DiffOptions::default()
5216            },
5217        );
5218        let mut highlighted = two_hunk_viewer();
5219        let results: Vec<_> = highlighted
5220            .highlight_requests(Rect::new(0, 0, 64, 20))
5221            .into_iter()
5222            .map(|request| HighlightResult::new(request, Line::new("highlighted")))
5223            .collect();
5224
5225        viewer.apply_highlights(results);
5226        viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
5227
5228        let focused = viewer.render_row(3, 64).unwrap().line;
5229        let muted = viewer.render_row(7, 64).unwrap().line;
5230
5231        assert!(focused.to_string().contains("highlighted"));
5232        assert!(muted.to_string().contains("highlighted"));
5233        assert!(format!("{}", muted.styled()).contains("\x1b[2m"));
5234    }
5235
5236    /// Returns a viewer over a hunk that begins partway into its file.
5237    fn mid_file_viewer() -> DiffViewer {
5238        let document = DiffDocument::decode_str(concat!(
5239            "diff --git a/a.rs b/a.rs\n",
5240            "index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644\n",
5241            "--- a/a.rs\n",
5242            "+++ b/a.rs\n",
5243            "@@ -3,1 +3,1 @@\n",
5244            "-old\n",
5245            "+new\n",
5246        ))
5247        .unwrap();
5248
5249        DiffViewer::new(document, DiffOptions::default())
5250    }
5251
5252    #[test]
5253    fn highlight_sources_span_the_whole_blob() {
5254        let mut viewer = mid_file_viewer();
5255        viewer
5256            .load_file_sources(|_| Ok::<_, Infallible>(b"fn f() {\nbody\nnew\n}\n".to_vec()))
5257            .unwrap();
5258
5259        let request = viewer
5260            .highlight_requests(Rect::new(0, 0, 64, 20))
5261            .into_iter()
5262            .find(|request| request.key.side == DiffSide::New)
5263            .unwrap();
5264
5265        // Head is line 1, not the hunk head, so the tokenizer walks the lines
5266        // that establish the enclosing block before reaching the changed row.
5267        assert_eq!(request.source.head, 1);
5268        assert_eq!(request.source.line(1), Some("fn f() {"));
5269        assert_eq!(request.source.line(3), Some("new"));
5270    }
5271    #[test]
5272    fn file_sources_skip_null_blob_ids() {
5273        let document = DiffDocument::decode_str(concat!(
5274            "diff --git a/new.rs b/new.rs\n",
5275            "new file mode 100644\n",
5276            "index 0000000000000000000000000000000000000000..1111111111111111111111111111111111111111\n",
5277            "--- /dev/null\n",
5278            "+++ b/new.rs\n",
5279            "@@ -0,0 +1 @@\n",
5280            "+new\n",
5281        ))
5282        .unwrap();
5283        let mut viewer = DiffViewer::new(document, DiffOptions::default());
5284        let mut loaded = Vec::new();
5285
5286        viewer
5287            .load_file_sources(|oid| {
5288                loaded.push(oid);
5289                Ok::<_, Infallible>(b"new\n".to_vec())
5290            })
5291            .unwrap();
5292
5293        assert_eq!(loaded.len(), 1);
5294        assert!(!loaded[0].is_zero());
5295    }
5296
5297    #[test]
5298    fn each_side_highlights_against_its_own_blob() {
5299        let mut viewer = mid_file_viewer();
5300        let old_oid = viewer.document.files[0].header.old_oid.unwrap();
5301        viewer
5302            .load_file_sources(|oid| {
5303                // Each side must reproduce its own row at line 3.
5304                let text: &[u8] = if oid == old_oid {
5305                    b"one\ntwo\nold\n"
5306                } else {
5307                    b"one\ntwo\nnew\n"
5308                };
5309                Ok::<_, Infallible>(text.to_vec())
5310            })
5311            .unwrap();
5312
5313        let requests = viewer.highlight_requests(Rect::new(0, 0, 64, 20));
5314        let source = |side| {
5315            requests
5316                .iter()
5317                .find(|request| request.key.side == side)
5318                .map(|request| request.source.text.to_string())
5319        };
5320
5321        assert_eq!(source(DiffSide::Old).as_deref(), Some("one\ntwo\nold\n"));
5322        assert_eq!(source(DiffSide::New).as_deref(), Some("one\ntwo\nnew\n"));
5323    }
5324
5325    #[test]
5326    fn loaded_sources_survive_replacing_file_diffs() {
5327        // Brain hides accepted hunks by replacing the document, which happens
5328        // right after loading and would otherwise discard every source.
5329        let mut viewer = mid_file_viewer();
5330        viewer
5331            .load_file_sources(|_| Ok::<_, Infallible>(b"one\ntwo\nnew\n".to_vec()))
5332            .unwrap();
5333        let files = viewer.document.files.clone();
5334
5335        viewer.replace_file_diffs(files);
5336
5337        let request = viewer
5338            .highlight_requests(Rect::new(0, 0, 64, 20))
5339            .into_iter()
5340            .find(|request| request.key.side == DiffSide::New)
5341            .unwrap();
5342
5343        assert_eq!(request.source.head, 1);
5344    }
5345
5346    #[test]
5347    fn sources_that_disagree_with_the_diff_are_rejected() {
5348        // A worktree file edited after the diff was produced no longer contains
5349        // the patched rows; rendering from it would show text the patch lacks.
5350        let mut viewer = mid_file_viewer();
5351        viewer
5352            .load_file_sources(|_| Ok::<_, Infallible>(b"one\ntwo\ndrifted\n".to_vec()))
5353            .unwrap();
5354
5355        let request = viewer
5356            .highlight_requests(Rect::new(0, 0, 64, 20))
5357            .into_iter()
5358            .find(|request| request.key.side == DiffSide::New)
5359            .unwrap();
5360
5361        assert_eq!(request.source.head, 3);
5362        assert_eq!(request.source.line(3), Some("new"));
5363    }
5364
5365    #[test]
5366    fn sources_past_the_total_budget_are_not_retained() {
5367        let mut viewer = mid_file_viewer();
5368        viewer.source_bytes = MAX_TOTAL_SOURCE_BYTES;
5369        viewer
5370            .load_file_sources(|_| Ok::<_, Infallible>(b"one\ntwo\nnew\n".to_vec()))
5371            .unwrap();
5372
5373        let request = viewer
5374            .highlight_requests(Rect::new(0, 0, 64, 20))
5375            .into_iter()
5376            .find(|request| request.key.side == DiffSide::New)
5377            .unwrap();
5378
5379        assert!(viewer.blob_sources.is_empty());
5380        assert_eq!(request.source.head, 3);
5381    }
5382
5383    #[cfg(unix)]
5384    #[test]
5385    fn worktree_sources_are_bounded_and_confined_to_the_root() {
5386        use std::os::unix::fs::symlink;
5387
5388        let nonce = SystemTime::now()
5389            .duration_since(UNIX_EPOCH)
5390            .unwrap()
5391            .as_nanos();
5392        let base = std::env::temp_dir().join(format!(
5393            "rustik-diff-worktree-{}-{nonce}",
5394            std::process::id()
5395        ));
5396        let root = base.join("root");
5397        fs::create_dir_all(&root).unwrap();
5398        fs::write(base.join("outside"), "outside\n").unwrap();
5399        fs::write(root.join("target"), "one\ntwo\n").unwrap();
5400        fs::write(root.join("large"), vec![b'x'; MAX_SOURCE_BYTES + 1]).unwrap();
5401        symlink("target", root.join("link")).unwrap();
5402        let root = root.canonicalize().unwrap();
5403
5404        assert!(
5405            LoadedBlob::read_worktree(&root, Path::new("../outside"), FileMode::Blob).is_none()
5406        );
5407        assert!(LoadedBlob::read_worktree(&root, &root.join("target"), FileMode::Blob).is_none());
5408        assert!(LoadedBlob::read_worktree(&root, Path::new("large"), FileMode::Blob).is_none());
5409        assert!(LoadedBlob::read_worktree(&root, Path::new("link"), FileMode::Blob).is_none());
5410
5411        let link = LoadedBlob::read_worktree(&root, Path::new("link"), FileMode::Link).unwrap();
5412        assert_eq!(link.loc, 1);
5413        assert_eq!(link.source.unwrap().line(1), Some("target"));
5414
5415        fs::remove_dir_all(base).unwrap();
5416    }
5417
5418    #[test]
5419    fn hunk_sources_are_used_when_no_blob_is_loaded() {
5420        let mut viewer = mid_file_viewer();
5421
5422        let request = viewer
5423            .highlight_requests(Rect::new(0, 0, 64, 20))
5424            .into_iter()
5425            .find(|request| request.key.side == DiffSide::New)
5426            .unwrap();
5427
5428        assert_eq!(request.source.head, 3);
5429        assert_eq!(request.source.line(3), Some("new"));
5430    }
5431
5432    /// A single-row change whose hunk starts partway into `blob`.
5433    struct ContextCase {
5434        /// Grammar to highlight with, named because the bundled Rust and shell
5435        /// grammars declare no file types for path inference to match.
5436        syntax: &'static str,
5437        /// Raw grammar source registered under `syntax`.
5438        grammar: &'static str,
5439        /// Whole new-side file, of which the hunk shows only a slice.
5440        blob: &'static str,
5441        /// One-based new-side line number of the changed row.
5442        line: u32,
5443        /// Substring of the changed row whose color is returned.
5444        needle: &'static str,
5445    }
5446
5447    impl ContextCase {
5448        /// Highlights the changed row and returns the color of `needle`.
5449        ///
5450        /// With `load_blob` the row is highlighted against the whole file; without
5451        /// it, against the hunk alone, which is the state this loses context in.
5452        fn row_color(&self, load_blob: bool) -> Option<Color> {
5453            let old = self.line;
5454            let body = self.blob.lines().nth(self.line as usize - 1).unwrap();
5455            let document = DiffDocument::decode_str(&format!(
5456                "diff --git a/a b/a\n\
5457                 index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644\n\
5458                 --- a/a\n\
5459                 +++ b/a\n\
5460                 @@ -{old},1 +{old},1 @@\n\
5461                 -placeholder\n\
5462                 +{body}\n"
5463            ))
5464            .unwrap();
5465            let options = DiffOptions {
5466                syntax: Some(self.syntax.to_owned()),
5467                ..DiffOptions::default()
5468            };
5469            let mut viewer = DiffViewer::new(document, options);
5470            if load_blob {
5471                viewer
5472                    .load_file_sources(|_| Ok::<_, Infallible>(self.blob.as_bytes().to_vec()))
5473                    .unwrap();
5474            }
5475
5476            let mut registry = syntax::Registry::default();
5477            registry.add_theme(
5478                syntax::Theme::parse(include_str!("themes/rustik-catppuccin-mocha.json")).unwrap(),
5479            );
5480            registry.add_grammar(syntax::Grammar::from_str(self.grammar).unwrap());
5481            let mut highlighter =
5482                crate::BuiltinHighlighter::new(registry, "rustik-catppuccin-mocha");
5483
5484            let requests = viewer
5485                .highlight_requests(Rect::new(0, 0, 80, 20))
5486                .into_iter()
5487                .filter(|request| request.key.side == DiffSide::New)
5488                .collect::<Vec<_>>();
5489
5490            highlighter
5491                .highlight_requests(requests)
5492                .into_iter()
5493                .flat_map(|result| result.line.labels().to_vec())
5494                .find(|label| label.content().contains(self.needle))
5495                .map(|label| label.paint.style().fg_color())
5496        }
5497    }
5498
5499    #[test]
5500    fn whole_file_context_highlights_a_row_inside_a_block_comment() {
5501        let case = ContextCase {
5502            syntax: "rust",
5503            grammar: syntax::syntaxes::RUST,
5504            blob: "/*\ncommented\n*/\n",
5505            line: 2,
5506            needle: "commented",
5507        };
5508        // Catppuccin Mocha's comment foreground.
5509        let comment = Color::RGB(147, 153, 178);
5510
5511        assert_eq!(case.row_color(true), Some(comment));
5512        assert_ne!(case.row_color(false), Some(comment));
5513    }
5514
5515    #[test]
5516    fn whole_file_context_highlights_a_row_inside_a_heredoc() {
5517        // A heredoc body is only distinguishable from code by its opener, so no
5518        // amount of grammar tuning recovers this without whole-file context.
5519        let case = ContextCase {
5520            syntax: "shell",
5521            grammar: syntax::syntaxes::SHELL,
5522            blob: "cat <<EOF\nprintf is literal text here\nEOF\n",
5523            line: 2,
5524            needle: "printf",
5525        };
5526        // Catppuccin Mocha's string foreground.
5527        let string = Color::RGB(166, 227, 161);
5528
5529        assert_eq!(case.row_color(true), Some(string));
5530        assert_ne!(case.row_color(false), Some(string));
5531    }
5532
5533    #[test]
5534    fn oversized_blobs_fall_back_to_hunk_sources() {
5535        let mut viewer = mid_file_viewer();
5536        viewer
5537            .load_file_sources(|_| Ok::<_, Infallible>(vec![b'x'; MAX_SOURCE_BYTES + 1]))
5538            .unwrap();
5539
5540        let request = viewer
5541            .highlight_requests(Rect::new(0, 0, 64, 20))
5542            .into_iter()
5543            .find(|request| request.key.side == DiffSide::New)
5544            .unwrap();
5545
5546        assert_eq!(request.source.head, 3);
5547    }
5548}