brain: Fix scroll behavior, LOCs etc.

6f044fb9e01a025ed07b3ca83476193143623b61
Alexis Sellier committed ago 1 parent 2e4e6918
crates/brain/src/backend.rs +5 -0
669 669
    pub fn hunk_patch_id(&self, file: &FileDiff, hunk: &Hunk) -> Result<PatchId, Error> {
670 670
        let patch = hunk_identity_patch(file, hunk)?;
671 671
        self.patch_id(&patch)
672 672
    }
673 673
674 +
    /// Reads one source blob for file metadata derived from complete contents.
675 +
    pub fn read_blob(&self, oid: Oid) -> Result<Vec<u8>, Error> {
676 +
        Ok(self.repository.cat_blob(oid)?)
677 +
    }
678 +
674 679
    /// Returns whether `patch_id` needs review after a review rebase.
675 680
    pub fn is_rebase_pending(&self, patch_id: &PatchId) -> bool {
676 681
        self.rebase_pending.contains(patch_id)
677 682
    }
678 683
f +0 -0
crates/brain/src/decorate.rs +62 -1
9 9
//! rebase show a rebase marker.
10 10
11 11
use std::collections::{BTreeMap, BTreeSet};
12 12
13 13
use rustik_diff::{
14 -
    DiffDecorator, DiffPalette, FileDecoration, FileId, HunkDecoration, HunkId, ReviewProgress,
14 +
    DiffDecorator, DiffPalette, FileDecoration, FileId, FileStats, HunkDecoration, HunkId,
15 +
    ReviewProgress,
15 16
};
16 17
use rustik_tui as tui;
17 18
use tui::{Label, Line, Paint, Style, colors};
18 19
19 20
use crate::comments::Comments;
35 36
    rebase_pending: BTreeSet<HunkId>,
36 37
    /// Per-hunk comment counts at snapshot time.
37 38
    comments: BTreeMap<HunkId, usize>,
38 39
    /// Original hunk ids for each file in the commit.
39 40
    file_hunks: BTreeMap<FileId, Vec<HunkId>>,
41 +
    /// Original addition and deletion counts for each hunk.
42 +
    hunk_stats: BTreeMap<HunkId, FileStats>,
40 43
    /// Diff palette the markers are drawn with.
41 44
    palette: DiffPalette,
42 45
}
43 46
44 47
impl Decorations {
45 48
    /// Captures the current review and comment state for `file_hunks`.
46 49
    pub fn snapshot(
47 50
        review: &Review,
48 51
        comments: &Comments,
49 52
        file_hunks: &BTreeMap<FileId, Vec<HunkId>>,
53 +
        hunk_stats: &BTreeMap<HunkId, FileStats>,
50 54
        palette: DiffPalette,
51 55
    ) -> Self {
52 56
        Self {
53 57
            accepted: review.accepted().clone(),
54 58
            rebase_pending: review.rebase_pending().clone(),
55 59
            comments: comments.counts(),
56 60
            file_hunks: file_hunks.clone(),
61 +
            hunk_stats: hunk_stats.clone(),
57 62
            palette,
58 63
        }
59 64
    }
65 +
66 +
    /// Returns the combined diffstat of hunks that still need review.
67 +
    fn remaining_stats(&self, hunks: &[HunkId]) -> FileStats {
68 +
        hunks
69 +
            .iter()
70 +
            .filter(|hunk| !self.accepted.contains(hunk))
71 +
            .filter_map(|hunk| self.hunk_stats.get(hunk))
72 +
            .fold(FileStats::default(), |mut total, stats| {
73 +
                total.additions += stats.additions;
74 +
                total.deletions += stats.deletions;
75 +
                total
76 +
            })
77 +
    }
60 78
}
61 79
62 80
impl DiffDecorator for Decorations {
63 81
    fn file(&self, file: FileId) -> FileDecoration {
64 82
        let hunks = self.file_hunks.get(&file).map_or(&[][..], Vec::as_slice);
73 91
            .iter()
74 92
            .filter_map(|hunk| self.comments.get(hunk))
75 93
            .sum::<usize>();
76 94
        let mut decoration = FileDecoration {
77 95
            progress,
96 +
            stats: Some(self.remaining_stats(hunks)),
78 97
            ..FileDecoration::default()
79 98
        };
80 99
        if progress.is_some_and(ReviewProgress::is_complete) {
81 100
            decoration.status = Some(Paint::new(ACCEPTED_MARK).fg(self.palette.positive_fg));
82 101
        } else if comment_count > 0 {
117 136
            corner,
118 137
            style: accepted.then(|| Style::default().dim()),
119 138
        }
120 139
    }
121 140
}
141 +
142 +
#[cfg(test)]
143 +
mod tests {
144 +
    use super::*;
145 +
146 +
    #[test]
147 +
    fn file_diffstat_excludes_accepted_hunks() {
148 +
        let first = HunkId::new(0);
149 +
        let second = HunkId::new(1);
150 +
        let decorations = Decorations {
151 +
            accepted: BTreeSet::from([first]),
152 +
            rebase_pending: BTreeSet::new(),
153 +
            comments: BTreeMap::new(),
154 +
            file_hunks: BTreeMap::from([(FileId::new(0), vec![first, second])]),
155 +
            hunk_stats: BTreeMap::from([
156 +
                (
157 +
                    first,
158 +
                    FileStats {
159 +
                        additions: 2,
160 +
                        deletions: 4,
161 +
                    },
162 +
                ),
163 +
                (
164 +
                    second,
165 +
                    FileStats {
166 +
                        additions: 3,
167 +
                        deletions: 1,
168 +
                    },
169 +
                ),
170 +
            ]),
171 +
            palette: DiffPalette::default(),
172 +
        };
173 +
174 +
        assert_eq!(
175 +
            decorations.remaining_stats(&[first, second]),
176 +
            FileStats {
177 +
                additions: 3,
178 +
                deletions: 1,
179 +
            }
180 +
        );
181 +
    }
182 +
}
crates/brain/src/session.rs +6 -3
268 268
                // A missing update still completes the in-flight request.
269 269
                self.context_fetch = ContextFetch::Idle;
270 270
                if let Some(update) = update {
271 271
                    let area = viewer_area(self.terminal.area());
272 272
                    if let Some(loaded) = &mut self.commits[self.current].loaded {
273 -
                        loaded.viewer.apply_context_update(update, area);
273 +
                        loaded.apply_context_update(update, &self.brain, area)?;
274 274
                    }
275 +
                    self.refresh_visibility()?;
275 276
                    return Ok(Update::Redraw);
276 277
                }
277 278
                Ok(Update::Continue)
278 279
            }
279 280
        }
483 484
            Some((file, focused))
484 485
        }) else {
485 486
            return Ok(());
486 487
        };
487 488
        let document = DiffDocument::for_hunks(file, [focused.clone()]);
488 -
        let viewer = DiffViewer::new(document, options);
489 +
        let mut viewer = DiffViewer::new(document, options);
490 +
        viewer.load_file_locs(|oid| self.brain.read_blob(oid))?;
489 491
490 492
        let mut view = HunkView::new(hunk, viewer, self.comments.author().to_owned());
491 493
        view.start_new();
492 494
        self.mode = Mode::Hunk(Box::new(view));
493 495
        self.restart_highlighter()?;
738 740
    ///
739 741
    /// The original decoded files are kept in `CommitReview::files`; the viewer
740 742
    /// receives a filtered copy when accepted hunks are hidden.
741 743
    fn refresh_visibility(&mut self) -> Result<(), Error> {
742 744
        let visibility = self.visibility;
745 +
        let area = viewer_area(self.terminal.area());
743 746
        let loaded = self.current()?;
744 747
745 748
        let files: Vec<FileDiff> = if visibility.show_accepted {
746 749
            loaded.files.clone()
747 750
        } else {
754 757
                        .retain(|hunk| !loaded.review.is_accepted(hunk.id));
755 758
                    file
756 759
                })
757 760
                .collect()
758 761
        };
759 -
        loaded.viewer.replace_file_diffs(files);
762 +
        loaded.viewer.replace_file_diffs_anchored(files, area);
760 763
761 764
        Ok(())
762 765
    }
763 766
764 767
    /// Reconciles per-commit review state from the hidden tree.
crates/brain/src/session/commit.rs +51 -2
1 1
//! Per-commit review state for the session.
2 2
3 3
use std::collections::BTreeMap;
4 4
5 -
use rustik_diff::{DiffDocument, DiffOptions, DiffViewer, Encode as _, FileDiff, FileId, HunkId};
5 +
use rustik_diff::{
6 +
    ContextUpdate, DiffDocument, DiffOptions, DiffViewer, Encode as _, FileDiff, FileId, FileStats,
7 +
    HunkId,
8 +
};
6 9
use rustik_repo::PatchId;
10 +
use rustik_tui::Rect;
7 11
8 12
use crate::backend::{Brain, Commit};
9 13
use crate::comments::{CommentTarget, Comments, ReviewComments};
10 14
use crate::decorate::Decorations;
11 15
use crate::error::Error;
44 48
    pub(super) patch_ids: BTreeMap<HunkId, PatchId>,
45 49
    /// Full, unfiltered file diffs used to restore hidden hunks.
46 50
    pub(super) files: Vec<FileDiff>,
47 51
    /// Original hunk ids per file, used for decoration snapshots.
48 52
    pub(super) file_hunks: BTreeMap<FileId, Vec<HunkId>>,
53 +
    /// Original diff stats per hunk, used for file-level remaining diffstats.
54 +
    pub(super) hunk_stats: BTreeMap<HunkId, FileStats>,
49 55
}
50 56
51 57
impl CommitReview {
52 58
    /// Decodes one commit's review state from its diff document.
53 59
    ///
60 66
        options: DiffOptions,
61 67
        brain: &Brain,
62 68
        store: &ReviewComments,
63 69
    ) -> Result<Self, Error> {
64 70
        let document = document.split_hunks();
65 -
        let viewer = DiffViewer::new(document, options);
71 +
        let mut viewer = DiffViewer::new(document, options);
72 +
        viewer.load_file_locs(|oid| brain.read_blob(oid))?;
66 73
        let files = viewer.document().files.clone();
67 74
        let heading = format!("{} {}", commit.id.short(), commit.summary);
68 75
        let mut hunk_patches = BTreeMap::new();
69 76
        let mut patch_ids = BTreeMap::new();
70 77
        let mut review = Review::new();
71 78
        let mut targets = BTreeMap::new();
72 79
        let mut file_hunks = BTreeMap::new();
80 +
        let mut hunk_stats = BTreeMap::new();
73 81
74 82
        for file in &files {
75 83
            let path = file.header.display_path().map(|path| path.to_path_buf());
76 84
            file_hunks.insert(
77 85
                file.id,
78 86
                file.hunks.iter().map(|hunk| hunk.id).collect::<Vec<_>>(),
79 87
            );
80 88
            for hunk in &file.hunks {
89 +
                hunk_stats.insert(hunk.id, hunk.stats());
81 90
                let patch = DiffDocument::for_hunks(file, [hunk.clone()]).to_unified_string()?;
82 91
                let patch_id = brain.hunk_patch_id(file, hunk)?;
83 92
                targets.insert(
84 93
                    hunk.id,
85 94
                    CommentTarget {
102 111
            comments,
103 112
            hunk_patches,
104 113
            patch_ids,
105 114
            files,
106 115
            file_hunks,
116 +
            hunk_stats,
107 117
        };
108 118
        loaded.refresh_decorations();
109 119
110 120
        Ok(loaded)
111 121
    }
117 127
    pub(super) fn refresh_decorations(&mut self) {
118 128
        self.viewer.set_decorator(Decorations::snapshot(
119 129
            &self.review,
120 130
            &self.comments,
121 131
            &self.file_hunks,
132 +
            &self.hunk_stats,
122 133
            self.viewer.options().diff_palette,
123 134
        ));
124 135
    }
136 +
137 +
    /// Applies a context refetch while preserving review hunk identities.
138 +
    pub(super) fn apply_context_update(
139 +
        &mut self,
140 +
        mut update: ContextUpdate,
141 +
        brain: &Brain,
142 +
        area: Rect,
143 +
    ) -> Result<(), Error> {
144 +
        let mut hunk_ids = BTreeMap::<_, Vec<_>>::new();
145 +
        for file in &self.files {
146 +
            for hunk in &file.hunks {
147 +
                if let Some(patch_id) = self.patch_ids.get(&hunk.id) {
148 +
                    hunk_ids
149 +
                        .entry((file.id, patch_id.clone()))
150 +
                        .or_default()
151 +
                        .push(hunk.id);
152 +
                }
153 +
            }
154 +
        }
155 +
        for ids in hunk_ids.values_mut() {
156 +
            ids.reverse();
157 +
        }
158 +
        for file in update.files_mut() {
159 +
            for index in 0..file.hunks.len() {
160 +
                let patch_id = brain.hunk_patch_id(file, &file.hunks[index])?;
161 +
                if let Some(id) = hunk_ids.get_mut(&(file.id, patch_id)).and_then(Vec::pop) {
162 +
                    file.hunks[index].id = id;
163 +
                }
164 +
            }
165 +
        }
166 +
        for replacement in update.files() {
167 +
            if let Some(file) = self.files.iter_mut().find(|file| file.id == replacement.id) {
168 +
                *file = replacement.clone();
169 +
            }
170 +
        }
171 +
        self.viewer.apply_context_update(update, area);
172 +
        Ok(())
173 +
    }
125 174
}
126 175
127 176
#[cfg(test)]
128 177
mod tests {
129 178
    use super::*;
a.rs +0 -0
crates/diff/src/bin/rustik-diff.rs +26 -13
10 10
use std::path::Path;
11 11
use std::process::ExitCode;
12 12
use std::{env, str};
13 13
14 14
use rustik_diff::{Builtins, Decode, DiffDocument, DiffOptions, DiffViewer, FileTreeMode};
15 -
use rustik_repo::git;
15 +
use rustik_repo::{ReadRepository as _, git};
16 16
use rustik_tui as tui;
17 17
use rustik_tui::Terminal;
18 18
use rustik_tui_termion as tui_termion;
19 19
20 20
use error::Error;
94 94
    let mut options = DiffOptions {
95 95
        diff_palette: assets.palette,
96 96
        ..DiffOptions::default()
97 97
    };
98 98
99 -
    if !io::stdout().is_terminal() {
100 -
        let mut viewer = DiffViewer::new(document, options);
99 +
    let interactive = io::stdout().is_terminal();
100 +
    if interactive {
101 +
        let root = cwd
102 +
            .file_name()
103 +
            .and_then(|name| name.to_str())
104 +
            .filter(|name| !name.is_empty())
105 +
            .map(str::to_owned)
106 +
            .unwrap_or_else(|| cwd.display().to_string());
107 +
108 +
        options.file_tree = FileTreeMode::Auto;
109 +
        options.file_tree_root = root;
110 +
    }
111 +
    let mut viewer = DiffViewer::new(document, options);
112 +
    match &repo {
113 +
        RenderRepo::Git(repository) => {
114 +
            viewer.load_file_locs(|oid| repository.cat_blob(oid))?;
115 +
        }
116 +
        RenderRepo::Stdin => {
117 +
            if let Ok(repository) = git::Repository::discover(cwd.to_path_buf()) {
118 +
                let _ = viewer.load_file_locs(|oid| repository.cat_blob(oid));
119 +
            }
120 +
        }
121 +
    }
122 +
123 +
    if !interactive {
101 124
        let constraints = tui::Constraint::max(tui::Size::new(STATIC_COLS, STATIC_MAX_ROWS));
102 125
103 126
        tui_termion::term::print_constrained(&mut viewer, constraints)?;
104 127
        return Ok(());
105 128
    }
106 -
    let root = cwd
107 -
        .file_name()
108 -
        .and_then(|name| name.to_str())
109 -
        .filter(|name| !name.is_empty())
110 -
        .map(str::to_owned)
111 -
        .unwrap_or_else(|| cwd.display().to_string());
112 -
113 -
    options.file_tree = FileTreeMode::Auto;
114 -
    options.file_tree_root = root;
115 129
116 130
    let backend = tui_termion::term::screen()?;
117 131
    let mut terminal = Terminal::new(backend)?;
118 -
    let mut viewer = DiffViewer::new(document, options);
119 132
120 133
    terminal.clear()?;
121 134
    terminal.set_cursor_visible(false)?;
122 135
123 136
    let repo = match repo {
crates/diff/src/context.rs +5 -0
54 54
            context_lines: DEFAULT_CONTEXT_LINES,
55 55
            expanded_files: BTreeSet::new(),
56 56
        }
57 57
    }
58 58
59 +
    /// Returns whether a file is expanded to its full source.
60 +
    pub(crate) fn is_expanded(&self, file: FileId) -> bool {
61 +
        self.expanded_files.contains(&file)
62 +
    }
63 +
59 64
    /// Returns the refetch needed for a context change without mutating state.
60 65
    pub(crate) fn plan(
61 66
        &self,
62 67
        change: ContextChange,
63 68
        file_ids: &[FileId],
a.txt +0 -0
a.txt +0 -0
crates/diff/src/decorate.rs +3 -3
9 9
use std::{cmp::Ordering, fmt};
10 10
11 11
use rustik_tui as tui;
12 12
use tui::{Line, Paint, Style};
13 13
14 -
use crate::{FileId, HunkId};
14 +
use crate::{FileId, FileStats, HunkId};
15 15
16 16
/// Source of per-file and per-hunk decorations overlaid on a rendered diff.
17 17
///
18 18
/// Methods are queried during rendering, so they must be cheap and free of side
19 19
/// effects. The default implementations return empty decorations, so a host
44 44
    pub status: Option<Paint<char>>,
45 45
    /// Right-aligned segments shown before the diffstat, outermost first.
46 46
    pub annotations: Vec<Line>,
47 47
    /// Review progress shown in the file header.
48 48
    pub progress: Option<ReviewProgress>,
49 -
    /// Replacement for the computed `+adds -dels` diffstat, when set.
50 -
    pub stats: Option<Line>,
49 +
    /// Replacement for the computed addition and deletion counts, when set.
50 +
    pub stats: Option<FileStats>,
51 51
}
52 52
53 53
/// Review progress over a fixed set of hunks.
54 54
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
55 55
pub struct ReviewProgress {
crates/diff/src/viewer.rs +346 -131
21 21
use crate::decorate::{DiffDecorator, FileDecoration, HunkDecoration, ReviewProgress};
22 22
use crate::highlight::{DiffHighlighter, HighlightKeyInput, HighlightResult};
23 23
use crate::word;
24 24
use crate::{
25 25
    Commit, Decode, DecodeError, DiffDocument, DiffLine, DiffLineKind, DiffSide, FileDiff, FileId,
26 -
    FileKind, HighlightKey, HighlightRequest, HighlightSource, Hunk, HunkId, RowId,
26 +
    FileKind, FileStats, HighlightKey, HighlightRequest, HighlightSource, Hunk, HunkId, Oid, RowId,
27 27
};
28 28
29 29
pub use tree::{FileTree, FileTreeMode, FileTreeTarget};
30 30
31 31
/// Visible and lookahead row ranges that should be highlighted.
203 203
/// Repo refetch request prepared by the viewer for asynchronous context updates.
204 204
#[derive(Clone, Debug)]
205 205
pub struct ContextRequest {
206 206
    /// Context state to install when the request completes.
207 207
    next_context: ContextState,
208 -
    /// File to focus after applying the fetched replacement.
209 -
    active: Option<FileId>,
210 208
    /// Paths and original file ids to replace.
211 209
    files: Vec<(PathBuf, FileId)>,
210 +
    /// Currently rendered hunks whose identities should survive the refetch.
211 +
    originals: Vec<FileDiff>,
212 212
    /// Git context width to request.
213 213
    context_lines: usize,
214 214
    /// Next hunk and row ids used to remap fetched files.
215 215
    next_ids: (usize, usize),
216 216
}
218 218
/// Decoded replacement files for an asynchronous context update.
219 219
#[derive(Clone, Debug)]
220 220
pub struct ContextUpdate {
221 221
    /// Context state prepared when the request was started.
222 222
    next_context: ContextState,
223 -
    /// File to focus after applying the fetched replacement.
224 -
    active: Option<FileId>,
225 223
    /// Replacement file diffs with ids remapped to this viewer.
226 224
    files: Vec<FileDiff>,
225 +
    /// Unchanged rows added outside the original bounded review hunks.
226 +
    expanded_context: BTreeSet<RowId>,
227 227
}
228 228
229 229
/// Pure diff viewer that renders into a caller-owned buffer.
230 230
#[derive(Clone, Debug)]
231 231
pub struct DiffViewer {
232 232
    /// Diff document being viewed.
233 233
    document: DiffDocument,
234 +
    /// File metadata that does not change with hunk visibility or context.
235 +
    summaries: BTreeMap<FileId, FileSummary>,
236 +
    /// Unchanged full-file rows outside the bounded review hunks.
237 +
    expanded_context: BTreeSet<RowId>,
234 238
    /// Viewer options.
235 239
    options: DiffOptions,
236 240
    /// Mutable viewport state.
237 241
    state: DiffState,
238 242
    /// Highlighted row cache.
271 275
    files: Vec<IndexedFileRows>,
272 276
    /// Total number of rendered rows.
273 277
    rows: usize,
274 278
}
275 279
280 +
/// Stable metadata shown in a file header.
281 +
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
282 +
struct FileSummary {
283 +
    /// Nonblank displayed-side lines, upgraded from the full blob when available.
284 +
    loc: Option<usize>,
285 +
    /// Addition and deletion counts in the original file diff.
286 +
    stats: FileStats,
287 +
}
288 +
289 +
/// Whether separate review hunks render a synthetic gap row between them.
290 +
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
291 +
enum HunkGaps {
292 +
    /// Show a vertical ellipsis where bounded diff context is omitted.
293 +
    Visible,
294 +
    /// Join contiguous full-file context without a synthetic gap.
295 +
    Hidden,
296 +
}
297 +
298 +
impl From<&FileDiff> for FileSummary {
299 +
    fn from(file: &FileDiff) -> Self {
300 +
        let stats = file.stats();
301 +
        Self {
302 +
            loc: Some(file.loc()),
303 +
            stats,
304 +
        }
305 +
    }
306 +
}
307 +
276 308
/// The rendered position of one visible file.
277 309
#[derive(Clone, Copy, Debug)]
278 310
struct IndexedFileRows {
279 311
    /// Index into the document file list.
280 312
    file_index: usize,
430 462
        self.files.iter().map(|(path, _)| path.as_path())
431 463
    }
432 464
433 465
    /// Decodes a repo patch into a viewer update.
434 466
    pub fn decode(self, patch: &[u8]) -> Result<Option<ContextUpdate>, DecodeError> {
435 -
        let document = DiffDocument::decode_bytes(patch)?;
467 +
        let document = DiffDocument::decode_bytes(patch)?.split_hunks();
436 468
        let result: Result<Option<Vec<FileDiff>>, Infallible> =
437 469
            context::rebuild(self.next_ids, &self.files, self.context_lines, |_, _| {
438 470
                Ok(document.files)
439 471
            });
440 -
        let files = match result {
472 +
        let mut files = match result {
441 473
            Ok(Some(files)) => files,
442 474
            Ok(None) => return Ok(None),
443 475
            Err(error) => match error {},
444 476
        };
477 +
        let mut expanded_context = BTreeSet::new();
478 +
        for replacement in &mut files {
479 +
            let Some(original) = self.originals.iter().find(|file| file.id == replacement.id)
480 +
            else {
481 +
                continue;
482 +
            };
483 +
            let mut matched = BTreeSet::new();
484 +
            for hunk in &mut replacement.hunks {
485 +
                let changed = hunk
486 +
                    .lines
487 +
                    .iter()
488 +
                    .filter(|line| line.kind != DiffLineKind::Context)
489 +
                    .map(|line| (line.kind, line.text.as_str()));
490 +
                let Some(original) = original.hunks.iter().find(|original| {
491 +
                    !matched.contains(&original.id)
492 +
                        && original
493 +
                            .lines
494 +
                            .iter()
495 +
                            .filter(|line| line.kind != DiffLineKind::Context)
496 +
                            .map(|line| (line.kind, line.text.as_str()))
497 +
                            .eq(changed.clone())
498 +
                }) else {
499 +
                    continue;
500 +
                };
501 +
                hunk.id = original.id;
502 +
                matched.insert(original.id);
503 +
504 +
                let bounded = hunk.lines.windows(original.lines.len()).position(|window| {
505 +
                    window
506 +
                        .iter()
507 +
                        .zip(&original.lines)
508 +
                        .all(|(left, right)| left.kind == right.kind && left.text == right.text)
509 +
                });
510 +
                if let Some(start) = bounded {
511 +
                    let end = start + original.lines.len();
512 +
                    expanded_context.extend(
513 +
                        hunk.lines[..start]
514 +
                            .iter()
515 +
                            .chain(&hunk.lines[end..])
516 +
                            .filter(|line| line.kind == DiffLineKind::Context)
517 +
                            .map(|line| line.id),
518 +
                    );
519 +
                }
520 +
            }
521 +
        }
445 522
446 523
        Ok(Some(ContextUpdate {
447 524
            next_context: self.next_context,
448 -
            active: self.active,
449 525
            files,
526 +
            expanded_context,
450 527
        }))
451 528
    }
452 529
}
453 530
531 +
impl ContextUpdate {
532 +
    /// Returns replacement files so a host can restore stable hunk identities.
533 +
    pub fn files_mut(&mut self) -> &mut [FileDiff] {
534 +
        &mut self.files
535 +
    }
536 +
537 +
    /// Returns replacement files after host identity reconciliation.
538 +
    pub fn files(&self) -> &[FileDiff] {
539 +
        &self.files
540 +
    }
541 +
}
542 +
454 543
impl DiffViewer {
455 544
    /// Creates a viewer with plain initial rendering state.
456 545
    pub fn new(document: DiffDocument, options: DiffOptions) -> Self {
457 546
        let preamble = Self::preamble(document.commit.as_ref(), MIN_RENDER_COLS);
458 547
        let file_tree = tree::FileTree::new(&document, options.file_tree_root.clone());
548 +
        let summaries = document
549 +
            .files
550 +
            .iter()
551 +
            .map(|file| (file.id, FileSummary::from(file)))
552 +
            .collect();
459 553
        let state = DiffState::default();
460 554
461 555
        let mut viewer = Self {
462 556
            document,
557 +
            summaries,
558 +
            expanded_context: BTreeSet::new(),
463 559
            options,
464 560
            state,
465 561
            highlights: BTreeMap::new(),
466 562
            pending_highlights: BTreeSet::new(),
467 563
            hunk_highlight_sources: BTreeMap::new(),
509 605
    /// Returns the viewed document.
510 606
    pub const fn document(&self) -> &DiffDocument {
511 607
        &self.document
512 608
    }
513 609
610 +
    /// Loads full-file LOC metadata from the displayed-side blob of each text file.
611 +
    pub fn load_file_locs<E>(
612 +
        &mut self,
613 +
        mut read_blob: impl FnMut(Oid) -> Result<Vec<u8>, E>,
614 +
    ) -> Result<(), E> {
615 +
        let mut locs = BTreeMap::new();
616 +
        for file in &self.document.files {
617 +
            if file.header.kind == FileKind::Binary {
618 +
                continue;
619 +
            }
620 +
            let oid = if file.header.kind == FileKind::Deleted {
621 +
                file.header.old_oid
622 +
            } else {
623 +
                file.header.new_oid.or(file.header.old_oid)
624 +
            };
625 +
            let Some(oid) = oid else {
626 +
                continue;
627 +
            };
628 +
            let loc = if let Some(loc) = locs.get(&oid) {
629 +
                *loc
630 +
            } else {
631 +
                let bytes = read_blob(oid)?;
632 +
                let loc = bytes
633 +
                    .split(|byte| *byte == b'\n')
634 +
                    .filter(|line| line.iter().any(|byte| !byte.is_ascii_whitespace()))
635 +
                    .count();
636 +
                locs.insert(oid, loc);
637 +
                loc
638 +
            };
639 +
            if let Some(summary) = self.summaries.get_mut(&file.id) {
640 +
                summary.loc = Some(loc);
641 +
            }
642 +
        }
643 +
        Ok(())
644 +
    }
645 +
514 646
    /// Returns the viewer options.
515 647
    pub const fn options(&self) -> &DiffOptions {
516 648
        &self.options
517 649
    }
518 650
547 679
        self.hunk_highlight_sources.clear();
548 680
        self.word_diffs.clear();
549 681
        self.rebuild_index();
550 682
    }
551 683
684 +
    /// Replaces file diffs while keeping a visible focused hunk on its screen row.
685 +
    pub fn replace_file_diffs_anchored(
686 +
        &mut self,
687 +
        files: impl IntoIterator<Item = FileDiff>,
688 +
        area: Rect,
689 +
    ) {
690 +
        let visible_rows = self.layout(area).diff.rows;
691 +
        let anchor = self.focus_anchor(visible_rows);
692 +
        let active = self.active_file();
693 +
        self.replace_file_diffs(files);
694 +
        self.restore_view(anchor, active, area);
695 +
    }
696 +
552 697
    /// Prepares a repo refetch request for an asynchronous context update.
553 698
    pub fn context_request(&self, change: ContextChange) -> Option<ContextRequest> {
554 699
        let active = self.active_file();
555 700
        let file_ids = self.context_file_ids(active);
556 701
        let plan = self.context.plan(change, &file_ids, &self.document)?;
557 702
        if plan.files.is_empty() {
558 703
            return None;
559 704
        }
560 705
706 +
        let originals = self
707 +
            .document
708 +
            .files
709 +
            .iter()
710 +
            .filter(|file| file_ids.contains(&file.id))
711 +
            .cloned()
712 +
            .collect();
561 713
        Some(ContextRequest {
562 714
            next_context: plan.state,
563 -
            active,
564 715
            files: plan.files,
716 +
            originals,
565 717
            context_lines: plan.context_lines,
566 718
            next_ids: context::next_ids(&self.document.files),
567 719
        })
568 720
    }
569 721
570 722
    /// Applies a completed asynchronous context update.
571 723
    pub fn apply_context_update(&mut self, update: ContextUpdate, area: Rect) -> bool {
572 724
        if update.files.is_empty() {
573 725
            return false;
574 726
        }
575 -
        let mut state = self.state.clone();
576 -
        if update.active.is_some() {
577 -
            state.focus = update.active.map(DiffFocus::File);
578 -
        }
727 +
        let before = self.state.clone();
728 +
        let visible_rows = self.layout(area).diff.rows;
729 +
        let focus_anchor = self.focus_anchor(visible_rows);
730 +
        let active = self.active_file();
579 731
        self.context = update.next_context;
732 +
        self.expanded_context = update.expanded_context;
580 733
        self.replace_file_diffs(update.files);
581 -
        self.set_state(state);
582 -
        self.apply(DiffAction::Resize, area) == ViewChange::Changed
734 +
        self.restore_view(focus_anchor, active, area);
735 +
        self.state != before
736 +
    }
737 +
738 +
    /// Restores focus and scroll after replacing rendered diff contents.
739 +
    fn restore_view(
740 +
        &mut self,
741 +
        focus_anchor: Option<(DiffFocus, usize)>,
742 +
        active: Option<FileId>,
743 +
        area: Rect,
744 +
    ) {
745 +
        if self.state.focus.is_some_and(|focus| !self.has_focus(focus)) {
746 +
            self.state.focus = active.map(DiffFocus::File);
747 +
        }
748 +
        let layout = self.layout(area);
749 +
        let visible_rows = layout.diff.rows;
750 +
        let offset = focus_anchor
751 +
            .and_then(|anchor| self.focus_anchor_offset(anchor))
752 +
            .unwrap_or(self.state.scroll.offset);
753 +
754 +
        self.state
755 +
            .scroll
756 +
            .set_offset(offset, self.scroll_rows(visible_rows), visible_rows);
757 +
        if layout.tree.is_some() {
758 +
            self.sync_file_tree();
759 +
        }
760 +
    }
761 +
762 +
    /// Returns a visible focused hunk and its current terminal row.
763 +
    fn focus_anchor(&self, visible_rows: usize) -> Option<(DiffFocus, usize)> {
764 +
        let focus = self.state.focus?;
765 +
        self.focus_targets(FocusFilter::Hunk)
766 +
            .into_iter()
767 +
            .find(|target| target.focus == focus)
768 +
            .and_then(|target| target.row.checked_sub(self.state.scroll.offset))
769 +
            .filter(|screen_row| *screen_row < visible_rows)
770 +
            .map(|screen_row| (focus, screen_row))
771 +
    }
772 +
773 +
    /// Returns the scroll offset that restores a captured focus anchor.
774 +
    fn focus_anchor_offset(&self, anchor: (DiffFocus, usize)) -> Option<usize> {
775 +
        let (focus, screen_row) = anchor;
776 +
        self.focus_targets(FocusFilter::Hunk)
777 +
            .into_iter()
778 +
            .find(|target| target.focus == focus)
779 +
            .map(|target| target.row.saturating_sub(screen_row))
780 +
    }
781 +
782 +
    /// Returns whether a focus target still exists in the current document.
783 +
    fn has_focus(&self, focus: DiffFocus) -> bool {
784 +
        match focus {
785 +
            DiffFocus::File(file) => self
786 +
                .document
787 +
                .files
788 +
                .iter()
789 +
                .any(|candidate| candidate.id == file),
790 +
            DiffFocus::Hunk(hunk) => self
791 +
                .document
792 +
                .files
793 +
                .iter()
794 +
                .flat_map(|file| &file.hunks)
795 +
                .any(|candidate| candidate.id == hunk),
796 +
        }
583 797
    }
584 798
585 799
    /// Returns the files targeted by a context change.
586 800
    fn context_file_ids(&self, active: Option<FileId>) -> Vec<FileId> {
587 801
        active
1111 1325
        self.apply_highlights(highlighter.highlight_batch(requests))
1112 1326
    }
1113 1327
1114 1328
    /// Returns the row count for one file card.
1115 1329
    fn file_rows(&self, file: &FileDiff) -> usize {
1116 -
        file.rendered_rows()
1330 +
        file.rendered_rows(self.hunk_gaps(file.id))
1331 +
    }
1332 +
1333 +
    /// Returns whether a file needs synthetic rows between review hunks.
1334 +
    fn hunk_gaps(&self, file: FileId) -> HunkGaps {
1335 +
        if self.context.is_expanded(file) {
1336 +
            HunkGaps::Hidden
1337 +
        } else {
1338 +
            HunkGaps::Visible
1339 +
        }
1117 1340
    }
1118 1341
1119 1342
    /// Returns one rendered row by global row index.
1120 1343
    fn render_row(&self, row: usize, cols: usize) -> Option<RenderRow> {
1121 1344
        let cols = cols.max(MIN_RENDER_COLS);
1156 1379
                    diff: None,
1157 1380
                };
1158 1381
            }
1159 1382
            FILE_HEADER_ROW => {
1160 1383
                let decoration = self.file_decoration(file.id);
1384 +
                let summary = self
1385 +
                    .summaries
1386 +
                    .get(&file.id)
1387 +
                    .copied()
1388 +
                    .unwrap_or_else(|| FileSummary::from(file));
1161 1389
                return RenderRow {
1162 1390
                    line: wrap_child(file.header_line(
1163 1391
                        child_cols,
1164 1392
                        self.options.diff_palette,
1165 1393
                        &decoration,
1394 +
                        summary,
1166 1395
                    )),
1167 1396
                    diff: None,
1168 1397
                };
1169 1398
            }
1170 1399
            row if row == bottom => {
1185 1414
                    diff: None,
1186 1415
                };
1187 1416
            }
1188 1417
            _ => {}
1189 1418
        }
1190 -
        let mut body_rows = file.hunk_body_rows().peekable();
1419 +
        let mut body_rows = file.hunk_body_rows(self.hunk_gaps(file.id)).peekable();
1191 1420
        while let Some(&(hunk, body_start)) = body_rows.peek() {
1192 1421
            let body_end = body_start + hunk.lines.len();
1193 1422
            if local < body_start {
1194 1423
                return RenderRow {
1195 1424
                    line: wrap_child(hunk_gap_line),
1204 1433
                }
1205 1434
                // The corner marker is drawn over the hunk's first body row.
1206 1435
                if local == body_start {
1207 1436
                    row.line = Self::overlay_corner(row.line, &decoration.corner, child_cols);
1208 1437
                }
1209 -
                if self.dims_unfocused_hunk(hunk.id) {
1438 +
                let expanded = row
1439 +
                    .diff
1440 +
                    .as_ref()
1441 +
                    .is_some_and(|meta| self.expanded_context.contains(&meta.row));
1442 +
                if expanded || self.dims_unfocused_hunk(hunk.id) {
1210 1443
                    row.line = Self::muted_hunk_line(row.line);
1211 1444
                }
1212 1445
                return RenderRow {
1213 1446
                    line: wrap_child(row.line),
1214 1447
                    diff: row.diff,
1223 1456
    }
1224 1457
1225 1458
    /// Returns source metadata for one rendered row without building UI lines.
1226 1459
    fn diff_meta_at(&self, row: usize) -> Option<DiffLineMeta> {
1227 1460
        let location = self.file_row_location(row)?;
1228 -
        for (hunk, body_start) in location.file.hunk_body_rows() {
1461 +
        for (hunk, body_start) in location
1462 +
            .file
1463 +
            .hunk_body_rows(self.hunk_gaps(location.file.id))
1464 +
        {
1229 1465
            let body_end = body_start + hunk.lines.len();
1230 1466
            if location.local < body_start {
1231 1467
                return None;
1232 1468
            }
1233 1469
            if location.local < body_end {
1473 1709
                .scroll
1474 1710
                .set_offset(target.row, self.scroll_rows(visible_rows), visible_rows);
1475 1711
            return;
1476 1712
        }
1477 1713
1478 -
        self.scroll_to_focused_hunk(
1479 -
            target,
1480 -
            visible_rows,
1481 -
            if was_hunk_focused {
1482 -
                HunkScroll::Preserve
1483 -
            } else {
1484 -
                HunkScroll::Center
1485 -
            },
1486 -
        );
1487 -
    }
1488 -
1489 -
    /// Scrolls to place a focused hunk using the review pager policy.
1490 -
    fn scroll_to_focused_hunk(
1491 -
        &mut self,
1492 -
        target: &FocusTarget,
1493 -
        visible_rows: usize,
1494 -
        scroll: HunkScroll,
1495 -
    ) {
1496 -
        let next = match scroll {
1497 -
            HunkScroll::Center => {
1498 -
                let centered = Self::centered_focus_scroll(target.row, target.height, visible_rows);
1499 -
                centered.saturating_sub(target.sticky_rows(centered))
1500 -
            }
1501 -
            HunkScroll::Preserve => Self::preserved_focus_scroll(
1502 -
                target.row,
1503 -
                target.height,
1504 -
                visible_rows,
1505 -
                self.state.scroll.offset,
1506 -
                target.sticky_rows(self.state.scroll.offset),
1507 -
            ),
1714 +
        let placement = if was_hunk_focused {
1715 +
            HunkScroll::Preserve
1716 +
        } else {
1717 +
            HunkScroll::Center
1508 1718
        };
1719 +
        let next = target.scroll_offset(self.state.scroll.offset, visible_rows, placement);
1509 1720
1510 1721
        self.state
1511 1722
            .scroll
1512 1723
            .set_offset(next, self.scroll_rows(visible_rows), visible_rows);
1513 1724
    }
1514 1725
1515 -
    /// Returns the scroll offset that centers a focused hunk when possible.
1516 -
    fn centered_focus_scroll(row: usize, height: usize, visible_rows: usize) -> usize {
1517 -
        let target = if height >= visible_rows {
1518 -
            0
1519 -
        } else {
1520 -
            visible_rows.saturating_sub(height) / 2
1521 -
        };
1522 -
1523 -
        row.saturating_sub(target)
1524 -
    }
1525 -
1526 -
    /// Returns a scroll offset that preserves middle-half focused hunk visibility.
1527 -
    fn preserved_focus_scroll(
1528 -
        row: usize,
1529 -
        height: usize,
1530 -
        visible_rows: usize,
1531 -
        scroll: usize,
1532 -
        sticky_rows: usize,
1533 -
    ) -> usize {
1534 -
        if visible_rows == 0 {
1535 -
            return scroll;
1536 -
        }
1537 -
        let height = height.max(1);
1538 -
        if height >= visible_rows {
1539 -
            return Self::large_focused_scroll(row, height, visible_rows, scroll, sticky_rows);
1540 -
        }
1541 -
1542 -
        let top = (visible_rows / 4).max(sticky_rows);
1543 -
        let bottom = visible_rows.saturating_sub(visible_rows / 4);
1544 -
        let screen_top = row.saturating_sub(scroll);
1545 -
        let screen_bottom = screen_top.saturating_add(height);
1546 -
1547 -
        if screen_top < top {
1548 -
            row.saturating_sub(top)
1549 -
        } else if screen_bottom > bottom {
1550 -
            row.saturating_add(height).saturating_sub(bottom)
1551 -
        } else {
1552 -
            scroll
1553 -
        }
1554 -
    }
1555 -
1556 -
    /// Returns scroll for a focused hunk taller than the viewport.
1557 -
    fn large_focused_scroll(
1558 -
        row: usize,
1559 -
        height: usize,
1560 -
        visible_rows: usize,
1561 -
        scroll: usize,
1562 -
        sticky_rows: usize,
1563 -
    ) -> usize {
1564 -
        let top = row.saturating_sub(sticky_rows);
1565 -
        let end = row.saturating_add(height);
1566 -
        if scroll < top {
1567 -
            return top;
1568 -
        }
1569 -
        if scroll >= end {
1570 -
            return end.saturating_sub(visible_rows);
1571 -
        }
1572 -
        scroll
1573 -
    }
1574 -
1575 1726
    /// Returns focusable targets in rendered row order.
1576 1727
    fn focus_targets(&self, filter: FocusFilter) -> Vec<FocusTarget> {
1577 1728
        let mut targets = Vec::new();
1578 1729
1579 1730
        for indexed in &self.index.files {
1587 1738
                    height: 1,
1588 1739
                    file_start: indexed.start,
1589 1740
                });
1590 1741
            }
1591 1742
            if filter == FocusFilter::Hunk {
1592 -
                for (hunk, local) in file.hunk_body_rows() {
1743 +
                for (hunk, local) in file.hunk_body_rows(self.hunk_gaps(file.id)) {
1744 +
                    let leading = hunk
1745 +
                        .lines
1746 +
                        .iter()
1747 +
                        .take_while(|line| self.expanded_context.contains(&line.id))
1748 +
                        .count();
1749 +
                    let trailing = hunk
1750 +
                        .lines
1751 +
                        .iter()
1752 +
                        .rev()
1753 +
                        .take_while(|line| self.expanded_context.contains(&line.id))
1754 +
                        .count();
1593 1755
                    targets.push(FocusTarget {
1594 1756
                        focus: DiffFocus::Hunk(hunk.id),
1595 -
                        row: indexed.start + local,
1596 -
                        height: hunk.lines.len(),
1757 +
                        row: indexed.start + local + leading,
1758 +
                        height: hunk.lines.len().saturating_sub(leading + trailing),
1597 1759
                        file_start: indexed.start,
1598 1760
                    });
1599 1761
                }
1600 1762
            }
1601 1763
        }
1910 2072
            STICKY_HEADER_ROWS
1911 2073
        } else {
1912 2074
            0
1913 2075
        }
1914 2076
    }
2077 +
2078 +
    /// Returns the scroll offset for placing this target in a viewport.
2079 +
    fn scroll_offset(self, current: usize, visible_rows: usize, placement: HunkScroll) -> usize {
2080 +
        if visible_rows == 0 {
2081 +
            return current;
2082 +
        }
2083 +
        let height = self.height.max(1);
2084 +
2085 +
        match placement {
2086 +
            HunkScroll::Center => {
2087 +
                let screen_row = visible_rows.saturating_sub(height) / 2;
2088 +
                let centered = self.row.saturating_sub(screen_row);
2089 +
2090 +
                centered.saturating_sub(self.sticky_rows(centered))
2091 +
            }
2092 +
            HunkScroll::Preserve if height >= visible_rows => {
2093 +
                let top = self.row.saturating_sub(self.sticky_rows(current));
2094 +
                let end = self.row.saturating_add(height);
2095 +
2096 +
                if current < top {
2097 +
                    top
2098 +
                } else if current >= end {
2099 +
                    end.saturating_sub(visible_rows)
2100 +
                } else {
2101 +
                    current
2102 +
                }
2103 +
            }
2104 +
            HunkScroll::Preserve => {
2105 +
                let top = (visible_rows / 4).max(self.sticky_rows(current));
2106 +
                let bottom = visible_rows.saturating_sub(visible_rows / 4);
2107 +
                let screen_top = self.row.saturating_sub(current);
2108 +
                let screen_bottom = screen_top.saturating_add(height);
2109 +
2110 +
                if screen_top < top {
2111 +
                    self.row.saturating_sub(top)
2112 +
                } else if screen_bottom > bottom {
2113 +
                    self.row.saturating_add(height).saturating_sub(bottom)
2114 +
                } else {
2115 +
                    current
2116 +
                }
2117 +
            }
2118 +
        }
2119 +
    }
1915 2120
}
1916 2121
1917 2122
/// Focus target filter.
1918 2123
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1919 2124
enum FocusFilter {
1937 2142
    fn has_body(&self) -> bool {
1938 2143
        !self.hunks.is_empty()
1939 2144
    }
1940 2145
1941 2146
    /// Returns the rendered row count for this file's card.
1942 -
    fn rendered_rows(&self) -> usize {
2147 +
    fn rendered_rows(&self, gaps: HunkGaps) -> usize {
1943 2148
        if !self.has_body() {
1944 2149
            return EMPTY_CARD_ROWS;
1945 2150
        }
1946 -
        let hunks = self.hunks.len();
2151 +
        let gaps = match gaps {
2152 +
            HunkGaps::Visible => self.hunks.len().saturating_sub(1),
2153 +
            HunkGaps::Hidden => 0,
2154 +
        };
1947 2155
        let body: usize = self.hunks.iter().map(|hunk| hunk.lines.len()).sum();
1948 2156
        // top + header + divider + body lines + gaps + bottom.
1949 -
        HUNK_BODY_START + body + hunks.saturating_sub(1) + 1
2157 +
        HUNK_BODY_START + body + gaps + 1
1950 2158
    }
1951 2159
1952 2160
    /// Returns each hunk together with the local row of its first body line.
1953 -
    fn hunk_body_rows(&self) -> impl Iterator<Item = (&Hunk, usize)> + '_ {
2161 +
    fn hunk_body_rows(&self, gaps: HunkGaps) -> impl Iterator<Item = (&Hunk, usize)> + '_ {
1954 2162
        self.hunks
1955 2163
            .iter()
1956 2164
            .enumerate()
1957 2165
            .scan(HUNK_BODY_START, move |local, (index, hunk)| {
1958 -
                if index > 0 {
2166 +
                if index > 0 && gaps == HunkGaps::Visible {
1959 2167
                    *local += 1;
1960 2168
                }
1961 2169
                let row = *local;
1962 2170
                *local += hunk.lines.len();
1963 2171
                Some((hunk, row))
1966 2174
1967 2175
    /// Returns a file header line, applying any host decoration.
1968 2176
    ///
1969 2177
    /// The leading marker is the decorated status when the host provides one,
1970 2178
    /// and the file-kind marker otherwise.
1971 -
    fn header_line(&self, cols: usize, palette: DiffPalette, decoration: &FileDecoration) -> Line {
2179 +
    fn header_line(
2180 +
        &self,
2181 +
        cols: usize,
2182 +
        palette: DiffPalette,
2183 +
        decoration: &FileDecoration,
2184 +
        summary: FileSummary,
2185 +
    ) -> Line {
1972 2186
        let mut left = Line::blank();
1973 2187
        if let Some(status) = &decoration.status {
1974 2188
            left.push(Label::from_char(status.item).style(status.style));
1975 2189
        } else {
1976 2190
            let fg = match self.header.kind {
1984 2198
            };
1985 2199
            left.push(Label::from_char(self.header.kind.marker()).fg(fg));
1986 2200
        }
1987 2201
        left.push(Label::space());
1988 2202
        left = left.extend(self.path_line());
1989 -
        left.push(Label::space());
1990 -
        left.push(Label::new(&format!("{} LOC", self.loc())).fg(colors::rgb::DIM));
2203 +
        if let Some(loc) = summary.loc {
2204 +
            left.push(Label::space());
2205 +
            left.push(Label::new(&format!("{loc} LOC")).fg(colors::rgb::DIM));
2206 +
        }
1991 2207
1992 2208
        if let Some(badge) = self.badge(palette) {
1993 2209
            left.push(Label::space());
1994 2210
            left = left.extend(badge.line());
1995 2211
        }
1996 2212
        // Right-aligned segments: host annotations first, then the diffstat (or
1997 2213
        // its decoration override), joined by a fixed gap.
1998 2214
        let mut right = decoration.annotations.clone();
2215 +
        let stats = decoration.stats.unwrap_or(summary.stats);
1999 2216
        if let Some(progress) = decoration.progress {
2000 2217
            let mut progress_line = Self::progress_bar(progress, palette);
2001 2218
            progress_line.push(Label::space());
2002 2219
            if progress.is_complete() {
2003 2220
                progress_line = progress_line.extend(
2006 2223
                    ))
2007 2224
                    .labels()
2008 2225
                    .iter()
2009 2226
                    .cloned(),
2010 2227
                );
2011 -
            } else if let Some(stats) = decoration.stats.clone().or_else(|| {
2012 -
                let stats = self.stats();
2228 +
            } else if let Some(stats) =
2013 2229
                Self::diffstat_line(stats.additions, stats.deletions, palette)
2014 -
            }) {
2230 +
            {
2015 2231
                progress_line =
2016 2232
                    progress_line.extend(Self::review_status_line(stats).labels().iter().cloned());
2017 2233
            }
2018 2234
            right.push(progress_line);
2019 -
        } else if let Some(stats) = decoration.stats.clone().or_else(|| {
2020 -
            let stats = self.stats();
2021 -
            Self::diffstat_line(stats.additions, stats.deletions, palette)
2022 -
        }) {
2235 +
        } else if let Some(stats) = Self::diffstat_line(stats.additions, stats.deletions, palette) {
2023 2236
            right.push(stats);
2024 2237
        }
2025 2238
        let mut header = HStack::default().child(left).spacer();
2026 2239
        for (index, segment) in right.into_iter().enumerate() {
2027 2240
            if index > 0 {
2078 2291
        Line::blank()
2079 2292
            .item(Label::new(&FILE_PROGRESS_BAR_GLYPH.repeat(filled)).fg(palette.positive_fg))
2080 2293
            .item(Label::new(&FILE_PROGRESS_BAR_GLYPH.repeat(empty)).fg(colors::FAINT))
2081 2294
    }
2082 2295
2083 -
    /// Returns the nonblank line count on the displayed side of this file.
2296 +
    /// Returns the nonblank displayed-side line count in this diff.
2084 2297
    fn loc(&self) -> usize {
2085 2298
        let deleted = self.header.kind == FileKind::Deleted;
2299 +
2086 2300
        self.hunks
2087 2301
            .iter()
2088 -
            .flat_map(|hunk| hunk.lines.iter())
2302 +
            .flat_map(|hunk| &hunk.lines)
2089 2303
            .filter(|line| {
2090 -
                let visible = match line.kind {
2304 +
                let displayed = match line.kind {
2091 2305
                    DiffLineKind::Context => true,
2092 2306
                    DiffLineKind::Addition => !deleted,
2093 2307
                    DiffLineKind::Deletion => deleted,
2094 2308
                    DiffLineKind::NoNewline => false,
2095 2309
                };
2096 -
                visible && !line.text.trim().is_empty()
2310 +
2311 +
                displayed && !line.text.trim().is_empty()
2097 2312
            })
2098 2313
            .count()
2099 2314
    }
2100 2315
2101 2316
    /// Returns a file-kind badge.
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
crates/diff/tests/golden/sticky_header_before_next_file_64x5.txt +0 -0
src/a.rs +0 -0
src/b.rs +0 -0
README.md +0 -0
src/app/a.rs +0 -0
src/lib/b.rs +0 -0
README.md +0 -0
a.rs +0 -0
b.rs +0 -0
assets/css/style.css +0 -0
assets/css/style.css +0 -0
first.rs +0 -0
second.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
a.rs +0 -0
b.rs +0 -0
crates/diff/tests/golden.rs +11 -2
1 1
#![allow(clippy::unwrap_used)]
2 2
3 3
use rustik_diff::{
4 -
    Decode, DiffAction, DiffDocument, DiffOptions, DiffSide, DiffViewer, FileTreeMode,
5 -
    HighlightResult,
4 +
    ContextChange, Decode, DiffAction, DiffDocument, DiffFocus, DiffOptions, DiffSide, DiffViewer,
5 +
    FileTreeMode, HighlightResult, HunkFocus, HunkId,
6 6
};
7 7
use rustik_tui::{Buffer, Color, Label, Line, Rect, Scroll, colors};
8 8
9 9
#[test]
10 10
fn expanded_file_card_matches_golden_frame() {
26 26
        64,
27 27
        12,
28 28
    );
29 29
}
30 30
31 +
#[test]
32 +
fn file_summary_ignores_visible_hunks_and_context() {
33 +
    let mut viewer = two_hunk_viewer();
34 +
    viewer
35 +
        .load_file_locs(|_| Ok::<_, ()>(b"one\ntwo\nthree\nfour\nfive\nsix\n".to_vec()))
36 +
        .unwrap();
37 +
    let mut replacement = DiffDocument::decode_str(
38 +
        "\
39 +
a.rs +0 -0
a.rs +0 -0
crates/diff/tests/golden/expanded_context.diff added +1 -0
1 +
a.rs +0 -0
crates/diff/tests/golden/expanded_context_focus_64x8.txt added +8 -0
1 +
╭─────────────────────────────────────────────────────────────╮🮘
2 +
│ ⊙ a.rs 4 LOC                                          +2 -2 │🮘
3 +
├╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴╴┤🮘
4 +
│ 9    9       nine                                           │🮘
5 +
│ 10   10      keep                                           │▗
6 +
│ 11         - before                                         │▐
7 +
│      11    + after                                          │▐
8 +
╰─────────────────────────────────────────────────────────────╯▐
crates/diff/tests/golden/stable_file_summary_64x9.txt added +9 -0
1 +
╭─────────────────────────────────────────────────────────────╮▐
2 +
│ ⊙ a.rs 6 LOC                                          +2 -2 │▐
3 +
├─────────────────────────────────────────────────────────────┤▐
4 +
│ 7    7       context1                                       │▐
5 +
│ 8    8       context2                                       │▐
6 +
│ 9    9       context3                                       │▐
7 +
│ 10   10      context4                                       │▐
8 +
│ 11         - before                                         │▐
9 +
│      11    + after                                          │🮘