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