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