mod tree;
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, BTreeSet};
use std::convert::Infallible;
use std::io::Read as _;
use std::ops::Range;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use rustik_highlight as syntax;
use rustik_tui as tui;
use tui::{
Badge, Buffer, Cell, Color, Constraint, Control, Event, HStack, Key, Label, Line, Mouse,
MouseButton, Paint, Rect, Scroll, ScrollView, ScrollbarStyle, Size, Style, Table, TableOptions,
Text, VStack, View, Viewport, Widget, colors,
};
use crate::context::{self, ContextChange, ContextState};
use crate::decorate::{DiffDecorator, FileDecoration, HunkDecoration, ReviewProgress};
use crate::highlight::{DiffHighlighter, HighlightKeyInput, HighlightResult};
use crate::word;
use crate::{
CommitHeader, Decode, DecodeError, DiffDocument, DiffLine, DiffLineKind, DiffSide, FileDiff,
FileId, FileKind, FileMode, FileStats, HighlightKey, HighlightRequest, HighlightSource, Hunk,
HunkId, Oid, RowId,
};
pub use tree::{FileTree, FileTreeMode, FileTreeTarget};
#[derive(Clone, Debug, Eq, PartialEq)]
struct HighlightWindow {
start: usize,
visible_end: usize,
lookahead_end: usize,
}
const MIN_RENDER_COLS: usize = 12;
const LINE_NUMBER_WIDTH: usize = 5;
const REVIEW_GUTTER_WIDTH: usize = 1;
const LINE_NUMBER_FG: Color = colors::fixed::DIM;
const SELECTED_LINE_NUMBER_FG: Color = colors::fixed::MUTED;
const MARKER_WIDTH: usize = 3;
const SCROLLBAR_TRACK: char = '🮘';
const SCROLLBAR_THUMB: char = '▐';
const DIVIDER: char = '─';
const FILE_KIND_BADGE_FG: Color = colors::rgb::PURPLE;
const FILE_KIND_BADGE_BG: Color = Color::RGB(32, 22, 42);
const FILE_BORDER: tui::Border = tui::Border::new(colors::FAINT);
const STICKY_DIVIDER: char = '╴';
const RENAME_ARROW: &str = "→";
const NO_NEWLINE_MARKER: &str = "\\ No newline at end of file";
const SOURCE_TAB_MARKER: &str = "· ";
const HUNK_GAP_MARKER_CELL: &str = " ⋮ ";
const FILE_HEADER_SEGMENT_SEPARATOR: &str = " · ";
const FILE_PROGRESS_BAR_WIDTH: usize = 10;
const FILE_PROGRESS_BAR_GLYPH: &str = "━";
const FILE_REVIEW_STATUS_COLS: usize = 11;
const DEFAULT_THEME: &str = "auto";
const STICKY_HEADER_ROWS: usize = 3;
const LINE_SCROLL_ROWS: isize = 1;
const WHEEL_SCROLL_ROWS: isize = 3;
const FILE_TOP_ROW: usize = 0;
const FILE_HEADER_ROW: usize = 1;
const FILE_DIVIDER_ROW: usize = 2;
const HUNK_BODY_START: usize = FILE_DIVIDER_ROW + 1;
const EMPTY_CARD_ROWS: usize = FILE_DIVIDER_ROW + 1;
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct DiffState {
pub scroll: Viewport,
pub focus: Option<DiffFocus>,
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum DiffFocus {
Commit,
File(FileId),
Hunk(HunkId),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DiffAction {
Scroll(Scroll),
Resize,
FocusNext,
FocusPrevious,
NextHunk,
PreviousHunk,
ToggleFileTree,
MoveFileTree(isize),
ShowFileTreeTarget,
ActivateFileTreeTarget,
CollapseFileTreeFolder,
ExpandFileTreeFolder,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ViewChange {
Changed,
Unchanged,
}
#[derive(Clone, Debug)]
pub struct DiffOptions {
pub syntax: Option<String>,
pub theme: String,
pub diff_palette: DiffPalette,
pub file_tree: FileTreeMode,
pub file_tree_root: String,
pub hunk_focus: HunkFocus,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum HunkFocus {
#[default]
Plain,
DimUnfocused,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DiffPalette {
pub negative_row_bg: Color,
pub positive_row_bg: Color,
pub negative_word_bg: Color,
pub positive_word_bg: Color,
pub negative_fg: Color,
pub positive_fg: Color,
}
#[derive(Clone, Debug)]
pub struct ContextRequest {
next_context: ContextState,
files: Vec<(PathBuf, FileId)>,
originals: Vec<FileDiff>,
context_lines: usize,
next_ids: (usize, usize),
}
#[derive(Clone, Debug)]
pub struct ContextUpdate {
next_context: ContextState,
files: Vec<FileDiff>,
expanded_context: BTreeSet<RowId>,
}
#[derive(Clone, Debug)]
pub struct DiffViewer {
document: DiffDocument,
summaries: BTreeMap<FileId, FileSummary>,
expanded_context: BTreeSet<RowId>,
options: DiffOptions,
state: DiffState,
hunk_focus: BTreeMap<FileId, HunkId>,
highlights: BTreeMap<HighlightKey, Line>,
pending_highlights: BTreeSet<HighlightKey>,
hunk_highlight_sources: BTreeMap<(FileId, HunkId, DiffSide), HighlightSource>,
blob_sources: BTreeMap<Oid, HighlightSource>,
worktree_sources: BTreeMap<PathBuf, HighlightSource>,
source_bytes: usize,
word_diffs: BTreeMap<HunkId, word::WordChanges>,
preamble: Vec<Line>,
file_tree: tree::FileTree,
file_tree_visibility: FileTreeVisibility,
index: RowIndex,
context: ContextState,
decorator: Option<Arc<dyn DiffDecorator>>,
}
#[derive(Clone, Debug, Default)]
struct RowIndex {
files: Vec<IndexedFileRows>,
rows: usize,
}
const MAX_SOURCE_BYTES: usize = 2 * 1024 * 1024;
const MAX_TOTAL_SOURCE_BYTES: usize = 64 * 1024 * 1024;
#[derive(Clone, Debug)]
struct LoadedBlob {
loc: usize,
source: Option<HighlightSource>,
}
impl LoadedBlob {
fn read(bytes: Vec<u8>) -> Self {
let loc = bytes
.split(|byte| *byte == b'\n')
.filter(|line| line.iter().any(|byte| !byte.is_ascii_whitespace()))
.count();
let source = (bytes.len() <= MAX_SOURCE_BYTES)
.then(|| String::from_utf8(bytes).ok())
.flatten()
.map(|text| HighlightSource::new(text, 1));
Self { loc, source }
}
fn read_worktree(root: &Path, path: &Path, mode: FileMode) -> Option<Self> {
if path.as_os_str().is_empty()
|| !path
.components()
.all(|component| matches!(component, Component::Normal(_)))
{
return None;
}
let full_path = root.join(path);
let bytes = if mode == FileMode::Link {
let parent = full_path.parent()?.canonicalize().ok()?;
if !parent.starts_with(root)
|| !std::fs::symlink_metadata(&full_path)
.ok()?
.file_type()
.is_symlink()
{
return None;
}
std::fs::read_link(full_path)
.ok()?
.into_os_string()
.into_encoded_bytes()
} else {
if !std::fs::symlink_metadata(&full_path)
.ok()?
.file_type()
.is_file()
{
return None;
}
let path = full_path.canonicalize().ok()?;
if !path.starts_with(root) {
return None;
}
let mut file = std::fs::File::open(path).ok()?;
if file.metadata().ok()?.len() > MAX_SOURCE_BYTES as u64 {
return None;
}
let mut bytes = Vec::new();
file.by_ref()
.take(MAX_SOURCE_BYTES as u64 + 1)
.read_to_end(&mut bytes)
.ok()?;
if bytes.len() > MAX_SOURCE_BYTES {
return None;
}
bytes
};
Some(Self::read(bytes))
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct FileSummary {
loc: Option<usize>,
stats: FileStats,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum HunkGaps {
Visible,
Hidden,
}
impl From<&FileDiff> for FileSummary {
fn from(file: &FileDiff) -> Self {
let stats = file.stats();
Self {
loc: (file.header.kind != FileKind::Binary).then(|| file.loc()),
stats,
}
}
}
#[derive(Clone, Copy, Debug)]
struct IndexedFileRows {
file_index: usize,
start: usize,
}
#[derive(Clone, Debug)]
struct RenderRow {
line: Line,
diff: Option<DiffLineMeta>,
}
#[derive(Clone, Copy, Debug, Default)]
struct HunkRowDecoration {
gutter: Option<Paint<char>>,
style: Option<Style>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct FileRowLocation<'a> {
file: &'a FileDiff,
start: usize,
end: usize,
local: usize,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct StickyHeaderRows {
start: usize,
rows: usize,
}
#[derive(Clone, Debug, Eq, PartialEq)]
struct DiffLineMeta {
file: FileId,
hunk: HunkId,
row: RowId,
kind: DiffLineKind,
side: DiffSide,
source_line: u32,
text: String,
path: Option<PathBuf>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct DiffLayout {
diff: Rect,
tree: Option<Rect>,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
enum FileTreeVisibility {
#[default]
Auto,
Visible,
Hidden,
}
impl Default for DiffOptions {
fn default() -> Self {
Self {
syntax: None,
theme: DEFAULT_THEME.to_owned(),
diff_palette: DiffPalette::default(),
file_tree: FileTreeMode::default(),
file_tree_root: ".".to_owned(),
hunk_focus: HunkFocus::default(),
}
}
}
impl Default for DiffPalette {
fn default() -> Self {
Self {
negative_row_bg: colors::rgb::NEGATIVE_DARK,
positive_row_bg: colors::rgb::POSITIVE_DARK,
negative_word_bg: colors::rgb::NEGATIVE,
positive_word_bg: colors::rgb::POSITIVE,
negative_fg: colors::rgb::NEGATIVE_LIGHT,
positive_fg: colors::rgb::POSITIVE_LIGHT,
}
}
}
impl From<&syntax::RawTheme> for DiffPalette {
fn from(theme: &syntax::RawTheme) -> Self {
let mut palette = Self::default();
if theme.colors.is_empty() {
return palette;
};
palette.positive_fg =
Self::theme_color(&theme.colors, "gitDecoration.addedResourceForeground")
.or_else(|| Self::theme_color(&theme.colors, "editorGutter.addedBackground"))
.unwrap_or(palette.positive_fg);
palette.negative_fg =
Self::theme_color(&theme.colors, "gitDecoration.deletedResourceForeground")
.or_else(|| Self::theme_color(&theme.colors, "editorGutter.deletedBackground"))
.unwrap_or(palette.negative_fg);
palette.positive_row_bg =
Self::theme_color(&theme.colors, "diffEditor.insertedLineBackground")
.unwrap_or(palette.positive_row_bg);
palette.negative_row_bg =
Self::theme_color(&theme.colors, "diffEditor.removedLineBackground")
.unwrap_or(palette.negative_row_bg);
palette.positive_word_bg =
Self::theme_color(&theme.colors, "diffEditor.insertedTextBackground")
.unwrap_or(palette.positive_word_bg);
palette.negative_word_bg =
Self::theme_color(&theme.colors, "diffEditor.removedTextBackground")
.unwrap_or(palette.negative_word_bg);
palette
}
}
impl DiffPalette {
fn theme_color(colors: &BTreeMap<String, String>, key: &str) -> Option<Color> {
let color = colors.get(key)?.parse::<syntax::Rgb>().ok()?;
Some(Color::RGB(color.r, color.g, color.b))
}
}
impl ContextRequest {
pub const fn context_lines(&self) -> usize {
self.context_lines
}
pub fn paths(&self) -> impl Iterator<Item = &Path> {
self.files.iter().map(|(path, _)| path.as_path())
}
pub fn decode(self, patch: &[u8]) -> Result<Option<ContextUpdate>, DecodeError> {
let document = DiffDocument::decode_bytes(patch)?.split_hunks();
let result: Result<Option<Vec<FileDiff>>, Infallible> =
context::rebuild(self.next_ids, &self.files, self.context_lines, |_, _| {
Ok(document.files)
});
let mut files = match result {
Ok(Some(files)) => files,
Ok(None) => return Ok(None),
Err(error) => match error {},
};
let mut expanded_context = BTreeSet::new();
for replacement in &mut files {
let Some(original) = self.originals.iter().find(|file| file.id == replacement.id)
else {
continue;
};
let mut matched = BTreeSet::new();
for hunk in &mut replacement.hunks {
let changed = hunk
.lines
.iter()
.filter(|line| line.kind != DiffLineKind::Context)
.map(|line| (line.kind, line.text.as_str()));
let Some(original) = original.hunks.iter().find(|original| {
!matched.contains(&original.id)
&& original
.lines
.iter()
.filter(|line| line.kind != DiffLineKind::Context)
.map(|line| (line.kind, line.text.as_str()))
.eq(changed.clone())
}) else {
continue;
};
hunk.id = original.id;
matched.insert(original.id);
let bounded = hunk.lines.windows(original.lines.len()).position(|window| {
window
.iter()
.zip(&original.lines)
.all(|(left, right)| left.kind == right.kind && left.text == right.text)
});
if let Some(start) = bounded {
let end = start + original.lines.len();
expanded_context.extend(
hunk.lines[..start]
.iter()
.chain(&hunk.lines[end..])
.filter(|line| line.kind == DiffLineKind::Context)
.map(|line| line.id),
);
}
}
}
Ok(Some(ContextUpdate {
next_context: self.next_context,
files,
expanded_context,
}))
}
}
impl ContextUpdate {
pub fn files_mut(&mut self) -> &mut [FileDiff] {
&mut self.files
}
pub fn files(&self) -> &[FileDiff] {
&self.files
}
}
impl DiffViewer {
pub fn new(document: DiffDocument, options: DiffOptions) -> Self {
let preamble = Self::preamble(document.commit.as_ref(), MIN_RENDER_COLS);
let file_tree = tree::FileTree::new(&document, options.file_tree_root.clone());
let summaries = document
.files
.iter()
.map(|file| (file.id, FileSummary::from(file)))
.collect();
let state = DiffState {
focus: document.commit.is_some().then_some(DiffFocus::Commit),
..DiffState::default()
};
let mut viewer = Self {
document,
summaries,
expanded_context: BTreeSet::new(),
options,
state,
hunk_focus: BTreeMap::new(),
highlights: BTreeMap::new(),
pending_highlights: BTreeSet::new(),
hunk_highlight_sources: BTreeMap::new(),
blob_sources: BTreeMap::new(),
worktree_sources: BTreeMap::new(),
source_bytes: 0,
word_diffs: BTreeMap::new(),
preamble,
file_tree,
file_tree_visibility: FileTreeVisibility::default(),
index: RowIndex::default(),
context: ContextState::new(),
decorator: None,
};
viewer.rebuild_index();
viewer
}
pub fn set_decorator(&mut self, decorator: impl DiffDecorator + 'static) {
self.decorator = Some(Arc::new(decorator));
}
pub fn clear_decorator(&mut self) {
self.decorator = None;
}
fn file_decoration(&self, file: FileId) -> FileDecoration {
self.decorator
.as_ref()
.map_or_else(FileDecoration::default, |decorator| decorator.file(file))
}
fn hunk_decoration(&self, file: FileId, hunk: HunkId) -> HunkDecoration {
self.decorator
.as_ref()
.map_or_else(HunkDecoration::default, |decorator| {
decorator.hunk(file, hunk)
})
}
pub const fn document(&self) -> &DiffDocument {
&self.document
}
pub fn load_file_sources<E>(
&mut self,
mut read_blob: impl FnMut(Oid) -> Result<Vec<u8>, E>,
) -> Result<(), E> {
let mut blobs: BTreeMap<Oid, usize> = BTreeMap::new();
for file in &self.document.files {
if file.header.kind == FileKind::Binary {
continue;
}
for oid in [file.header.old_oid, file.header.new_oid]
.into_iter()
.flatten()
.filter(|oid| !oid.is_zero())
{
if let Entry::Vacant(entry) = blobs.entry(oid) {
let blob = LoadedBlob::read(read_blob(oid)?);
entry.insert(blob.loc);
if let Some(source) = blob.source.filter(|source| {
self.source_bytes.saturating_add(source.retained_bytes())
<= MAX_TOTAL_SOURCE_BYTES
}) {
self.source_bytes += source.retained_bytes();
self.blob_sources.insert(oid, source);
}
}
}
let oid = if file.header.kind == FileKind::Deleted {
file.header.old_oid
} else {
file.header.new_oid.or(file.header.old_oid)
};
let Some(loc) = oid.and_then(|oid| blobs.get(&oid)).copied() else {
continue;
};
if let Some(summary) = self.summaries.get_mut(&file.id) {
summary.loc = Some(loc);
}
}
Ok(())
}
pub fn load_worktree_sources(&mut self, root: &Path) {
let Ok(root) = root.canonicalize() else {
return;
};
for file in &self.document.files {
if file.header.kind == FileKind::Binary
|| file.header.kind == FileKind::Deleted
|| file.header.new_oid.is_some()
{
continue;
}
let Some(path) = file.header.new_path.as_ref() else {
continue;
};
let mode = file.header.new_mode.unwrap_or(FileMode::Blob);
let Some(blob) = LoadedBlob::read_worktree(&root, path, mode) else {
continue;
};
if let Some(source) = blob.source.filter(|source| {
self.source_bytes.saturating_add(source.retained_bytes()) <= MAX_TOTAL_SOURCE_BYTES
}) {
self.source_bytes += source.retained_bytes();
self.worktree_sources.insert(path.clone(), source);
}
if let Some(summary) = self.summaries.get_mut(&file.id) {
summary.loc = Some(blob.loc);
}
}
}
pub const fn options(&self) -> &DiffOptions {
&self.options
}
pub const fn state(&self) -> &DiffState {
&self.state
}
pub fn set_state(&mut self, mut state: DiffState) {
let focus = state.focus.take();
self.state = state;
self.set_focus(focus);
}
pub fn replace_file_diffs(&mut self, files: impl IntoIterator<Item = FileDiff>) {
for replacement in files {
let existing = match self.document.files.get_mut(*replacement.id) {
Some(existing) if existing.id == replacement.id => Some(existing),
_ => self
.document
.files
.iter_mut()
.find(|file| file.id == replacement.id),
};
if let Some(existing) = existing {
*existing = replacement;
}
}
self.pending_highlights.clear();
self.hunk_highlight_sources.clear();
self.word_diffs.clear();
self.rebuild_index();
}
pub fn replace_file_diffs_anchored(
&mut self,
files: impl IntoIterator<Item = FileDiff>,
area: Rect,
) {
let hunk_focus = self.hunk_focus.clone();
let visible_rows = self.layout(area).diff.rows;
let focus = self.state.focus;
let anchor = self.focus_anchor(visible_rows);
let predecessors = self.focused_hunk_predecessors();
let active = self.active_file();
self.replace_file_diffs(files);
self.hunk_focus.extend(hunk_focus);
self.restore_view(focus, anchor, &predecessors, active, area);
}
pub fn is_full_file(&self) -> bool {
self.active_file()
.is_some_and(|file| self.context.is_expanded(file))
}
pub fn context_request(&self, change: ContextChange) -> Option<ContextRequest> {
let active = self.active_file();
let file_ids = self.context_file_ids(active);
let plan = self.context.plan(change, &file_ids, &self.document)?;
if plan.files.is_empty() {
return None;
}
let originals = self
.document
.files
.iter()
.filter(|file| file_ids.contains(&file.id))
.cloned()
.collect();
Some(ContextRequest {
next_context: plan.state,
files: plan.files,
originals,
context_lines: plan.context_lines,
next_ids: context::next_ids(&self.document.files),
})
}
pub fn apply_context_update(&mut self, update: ContextUpdate, area: Rect) -> bool {
if update.files.is_empty() {
return false;
}
let before = self.state.clone();
let focus = self.state.focus;
let visible_rows = self.layout(area).diff.rows;
let focus_anchor = self.focus_anchor(visible_rows);
let predecessors = self.focused_hunk_predecessors();
let active = self.active_file();
self.context = update.next_context;
self.expanded_context = update.expanded_context;
self.replace_file_diffs(update.files);
self.restore_view(focus, focus_anchor, &predecessors, active, area);
self.state != before
}
fn restore_view(
&mut self,
focus: Option<DiffFocus>,
focus_anchor: Option<(DiffFocus, usize)>,
predecessors: &[HunkId],
active: Option<FileId>,
area: Rect,
) {
if focus.is_some_and(|focus| !self.has_focus(focus)) {
self.set_focus(
predecessors
.iter()
.rev()
.copied()
.map(DiffFocus::Hunk)
.find(|focus| self.has_focus(*focus))
.or_else(|| self.document.commit.is_some().then_some(DiffFocus::Commit))
.or_else(|| active.map(DiffFocus::File)),
);
}
let layout = self.layout(area);
let visible_rows = layout.diff.rows;
let offset = focus_anchor
.and_then(|anchor| self.focus_anchor_offset(anchor))
.unwrap_or(self.state.scroll.offset);
self.state
.scroll
.set_offset(offset, self.scroll_rows(visible_rows), visible_rows);
if layout.tree.is_some() {
self.sync_file_tree();
}
}
fn focused_hunk_predecessors(&self) -> Vec<HunkId> {
let Some(DiffFocus::Hunk(focused)) = self.state.focus else {
return Vec::new();
};
self.document
.files
.iter()
.flat_map(|file| file.hunks.iter())
.map(|hunk| hunk.id)
.take_while(|hunk| *hunk != focused)
.collect()
}
fn focus_anchor(&self, visible_rows: usize) -> Option<(DiffFocus, usize)> {
let focus = self.state.focus?;
self.focus_targets(FocusFilter::HunkNavigation)
.into_iter()
.find(|target| target.focus == focus)
.and_then(|target| target.row.checked_sub(self.state.scroll.offset))
.filter(|screen_row| *screen_row < visible_rows)
.map(|screen_row| (focus, screen_row))
}
fn focus_anchor_offset(&self, anchor: (DiffFocus, usize)) -> Option<usize> {
let (focus, screen_row) = anchor;
self.focus_targets(FocusFilter::HunkNavigation)
.into_iter()
.find(|target| target.focus == focus)
.map(|target| target.row.saturating_sub(screen_row))
}
fn has_focus(&self, focus: DiffFocus) -> bool {
match focus {
DiffFocus::Commit => self.document.commit.is_some(),
DiffFocus::File(file) => self.index.files.iter().any(|indexed| {
self.document
.files
.get(indexed.file_index)
.is_some_and(|candidate| candidate.id == file)
}),
DiffFocus::Hunk(hunk) => self.index.files.iter().any(|indexed| {
self.document
.files
.get(indexed.file_index)
.is_some_and(|file| file.hunks.iter().any(|candidate| candidate.id == hunk))
}),
}
}
fn context_file_ids(&self, active: Option<FileId>) -> Vec<FileId> {
active
.filter(|id| self.document.files.iter().any(|file| file.id == *id))
.or_else(|| self.document.files.first().map(|file| file.id))
.into_iter()
.collect()
}
pub fn set_scroll(&mut self, scroll: usize) {
self.state.scroll = Viewport::from_offset(scroll);
}
pub fn set_focus(&mut self, focus: Option<DiffFocus>) {
let focus = focus.filter(|focus| self.has_focus(*focus));
if let Some(DiffFocus::Hunk(hunk)) = focus
&& let Some(file) = self
.document
.files
.iter()
.find(|file| file.hunks.iter().any(|candidate| candidate.id == hunk))
{
self.hunk_focus.insert(file.id, hunk);
}
self.state.focus = focus;
}
pub fn focused_file(&self) -> Option<FileId> {
match self.state.focus? {
DiffFocus::Commit => None,
DiffFocus::File(file) => Some(file),
DiffFocus::Hunk(hunk) => self
.document
.files
.iter()
.find(|file| file.hunks.iter().any(|candidate| candidate.id == hunk))
.map(|file| file.id),
}
}
fn active_file(&self) -> Option<FileId> {
self.focused_file().or_else(|| self.visible_file())
}
fn visible_file(&self) -> Option<FileId> {
self.file_row_location(self.state.scroll.offset)
.map(|location| location.file.id)
.or_else(|| self.document.files.first().map(|file| file.id))
}
fn scroll_rows(&self, visible_rows: usize) -> usize {
let last_file_start = self.index.files.last().map_or(0, |file| file.start);
self.index
.rows
.max(last_file_start.saturating_add(visible_rows))
}
fn render_rows_for(&self, scroll: usize, visible_rows: usize) -> usize {
self.index.rows.max(scroll.saturating_add(visible_rows))
}
fn show_file(&mut self, file: FileId, visible_rows: usize) {
let Some(row) = self.index.files.iter().find_map(|indexed| {
let candidate = self.document.files.get(indexed.file_index)?;
(candidate.id == file).then_some(indexed.start)
}) else {
return;
};
self.set_focus(Some(DiffFocus::File(file)));
self.state
.scroll
.set_offset(row, self.scroll_rows(visible_rows), visible_rows);
}
fn focus_file(&mut self, file: FileId, visible_rows: usize) {
let was_hunk_focused = matches!(self.state.focus, Some(DiffFocus::Hunk(_)));
let remembered = self.hunk_focus.get(&file).copied();
let focus = self
.document
.files
.iter()
.find(|candidate| candidate.id == file)
.and_then(|file| {
remembered
.filter(|hunk| file.hunks.iter().any(|candidate| candidate.id == *hunk))
.or_else(|| file.hunks.first().map(|hunk| hunk.id))
})
.map_or(DiffFocus::File(file), DiffFocus::Hunk);
let filter = if matches!(focus, DiffFocus::Hunk(_)) {
FocusFilter::HunkNavigation
} else {
FocusFilter::File
};
let Some(target) = self
.focus_targets(filter)
.into_iter()
.find(|target| target.focus == focus)
else {
return;
};
self.set_focus(Some(focus));
let current = self.state.scroll.offset;
let preserved = target.scroll_offset(current, visible_rows, HunkScroll::Preserve);
let placement = if preserved == current || was_hunk_focused {
HunkScroll::Preserve
} else {
HunkScroll::Center
};
let next = target.scroll_offset(current, visible_rows, placement);
self.state
.scroll
.set_offset(next, self.scroll_rows(visible_rows), visible_rows);
}
fn sync_file_tree(&mut self) {
if let Some(file) = self.active_file() {
self.file_tree.select_file(file);
}
}
pub fn render(&mut self, area: Rect, buf: &mut Buffer) {
if area.is_empty() {
return;
}
let layout = self.layout(area);
if let Some(tree) = layout.tree {
self.render_file_tree(tree, buf);
}
self.render_diff(layout.diff, buf);
}
fn layout(&self, area: Rect) -> DiffLayout {
if self.options.file_tree != FileTreeMode::Auto
|| self.file_tree_visibility == FileTreeVisibility::Hidden
|| self.document.files.is_empty()
{
return DiffLayout {
diff: area,
tree: None,
};
}
let tree_cols = self.file_tree.cols(area.cols);
if self.file_tree_visibility == FileTreeVisibility::Auto
&& area
.cols
.saturating_sub(tree_cols.saturating_add(tree::GAP_COLS))
< tree::MIN_DIFF_COLS
{
return DiffLayout {
diff: area,
tree: None,
};
}
let [tree, _, diff] = tui::layout::Layout::new(tui::Direction::Horizontal)
.child(tui::Length::Fixed(tree_cols))
.child(tui::Length::Fixed(tree::GAP_COLS))
.child(tui::Length::Fill(1))
.areas(area);
DiffLayout {
diff,
tree: Some(tree),
}
}
fn render_file_tree(&mut self, area: Rect, buf: &mut Buffer) {
let active_file = self.visible_file();
self.file_tree.draw(
active_file,
self.options.diff_palette,
self.decorator.as_deref(),
area,
buf,
);
}
fn render_diff(&mut self, area: Rect, buf: &mut Buffer) {
let body_cols = ScrollView::body_cols(area);
let preamble_rows = self.preamble.len();
self.preamble = Self::preamble(self.document.commit.as_ref(), body_cols);
if self.preamble.len() != preamble_rows {
self.rebuild_index();
}
let scroll = self.state.scroll.offset;
let sticky = self.sticky_rows(scroll, area.rows, body_cols);
let body_offset = scroll.saturating_add(sticky.len().min(area.rows));
let render_rows = self.render_rows_for(scroll, area.rows);
ScrollView::virtualized(render_rows, body_offset, |row, cols| {
self.render_row(row, cols)
.map(|row| row.line)
.unwrap_or_default()
})
.sticky(sticky)
.scrollbar_view(View::new(scroll, render_rows, area.rows))
.scrollbar(Self::scrollbar_style())
.render(area, buf);
}
pub fn apply(&mut self, action: DiffAction, area: Rect) -> ViewChange {
let before = self.state.clone();
let before_visibility = self.file_tree_visibility;
let before_file_tree = self.file_tree.state().clone();
let layout = self.layout(area);
let diff = layout.diff;
if layout.tree.is_none()
&& matches!(
action,
DiffAction::MoveFileTree(_)
| DiffAction::ShowFileTreeTarget
| DiffAction::ActivateFileTreeTarget
| DiffAction::CollapseFileTreeFolder
| DiffAction::ExpandFileTreeFolder,
)
{
return ViewChange::Unchanged;
}
match action {
DiffAction::Scroll(scroll) => {
let previous = self.state.scroll.offset;
self.state
.scroll
.scroll(scroll, self.scroll_rows(diff.rows), diff.rows);
if self.state.scroll.offset != previous
&& let Some(file) = self.visible_file()
{
if !matches!(self.state.focus, Some(DiffFocus::Hunk(_))) {
self.set_focus(Some(DiffFocus::File(file)));
}
if layout.tree.is_some() {
self.file_tree.select_file(file);
}
}
}
DiffAction::Resize => {
self.state
.scroll
.clamp(self.scroll_rows(diff.rows), diff.rows);
if layout.tree.is_some() {
self.sync_file_tree();
}
}
DiffAction::FocusNext => {
self.focus(diff.rows, 1, FocusFilter::File);
self.sync_file_tree();
}
DiffAction::FocusPrevious => {
self.focus(diff.rows, -1, FocusFilter::File);
self.sync_file_tree();
}
DiffAction::NextHunk => {
self.focus(diff.rows, 1, FocusFilter::HunkNavigation);
if self.state.focus != before.focus {
self.sync_file_tree();
}
}
DiffAction::PreviousHunk => {
self.focus(diff.rows, -1, FocusFilter::HunkNavigation);
if self.state.focus != before.focus {
self.sync_file_tree();
}
}
DiffAction::ToggleFileTree => match self.file_tree_visibility {
FileTreeVisibility::Hidden => {
self.file_tree_visibility = FileTreeVisibility::Visible;
if self.layout(area).tree.is_some() {
self.sync_file_tree();
}
}
FileTreeVisibility::Auto | FileTreeVisibility::Visible if layout.tree.is_some() => {
self.file_tree_visibility = FileTreeVisibility::Hidden;
}
FileTreeVisibility::Auto => {
self.file_tree_visibility = FileTreeVisibility::Visible;
if self.layout(area).tree.is_some() {
self.sync_file_tree();
}
}
FileTreeVisibility::Visible => {
self.file_tree_visibility = FileTreeVisibility::Hidden;
}
},
DiffAction::MoveFileTree(delta) => {
if self.file_tree.state().selected().is_none() {
self.file_tree.enter(self.visible_file());
}
if let Some(file) = self.file_tree.select(delta) {
self.show_file(file, diff.rows);
}
}
DiffAction::ShowFileTreeTarget => {
if let Some(file) = self.file_tree.selected_file() {
self.focus_file(file, diff.rows);
}
}
DiffAction::ActivateFileTreeTarget => {
if let Some(file) = self.file_tree.activate_target() {
self.show_file(file, diff.rows);
}
}
DiffAction::CollapseFileTreeFolder => {
self.file_tree.collapse_folder();
}
DiffAction::ExpandFileTreeFolder => {
self.file_tree.expand_folder();
}
}
if self.state == before
&& self.file_tree_visibility == before_visibility
&& *self.file_tree.state() == before_file_tree
{
ViewChange::Unchanged
} else {
ViewChange::Changed
}
}
pub fn handle_input(&mut self, event: Event<()>, area: Rect) -> Control {
let action = match event {
Event::Key(Key::Char('q')) => return Control::Quit,
Event::Key(Key::Char('`')) => DiffAction::ToggleFileTree,
Event::Resize(_) => DiffAction::Resize,
Event::Mouse(Mouse::Press {
button: MouseButton::WheelDown,
..
}) => DiffAction::Scroll(Scroll::Lines(WHEEL_SCROLL_ROWS)),
Event::Mouse(Mouse::Press {
button: MouseButton::WheelUp,
..
}) => DiffAction::Scroll(Scroll::Lines(-WHEEL_SCROLL_ROWS)),
Event::Mouse(Mouse::Press {
button: MouseButton::Left,
at,
..
}) => {
let Some(tree) = self.layout(area).tree else {
return Control::Continue;
};
let action = match self.file_tree.select_at(tree, at) {
Some(tree::FileTreeClick::Disclosure) => return Control::Redraw,
Some(tree::FileTreeClick::Row) => DiffAction::ShowFileTreeTarget,
None => return Control::Continue,
};
self.apply(action, area);
return Control::Redraw;
}
Event::Key(Key::Esc) => return Control::Quit,
Event::Key(Key::Char('n')) => DiffAction::FocusNext,
Event::Key(Key::Char('p')) => DiffAction::FocusPrevious,
Event::Key(Key::Char('j') | Key::Down) => {
DiffAction::Scroll(Scroll::Lines(LINE_SCROLL_ROWS))
}
Event::Key(Key::Char('k') | Key::Up) => {
DiffAction::Scroll(Scroll::Lines(-LINE_SCROLL_ROWS))
}
Event::Key(Key::Char('J')) => DiffAction::MoveFileTree(1),
Event::Key(Key::Char('K')) => DiffAction::MoveFileTree(-1),
Event::Key(Key::Char('H')) => DiffAction::ExpandFileTreeFolder,
Event::Key(Key::Char('L')) => DiffAction::CollapseFileTreeFolder,
Event::Key(Key::Char(' ') | Key::PageDown) => DiffAction::Scroll(Scroll::Pages(1)),
Event::Key(Key::PageUp) => DiffAction::Scroll(Scroll::Pages(-1)),
Event::Key(Key::Ctrl('d')) => {
DiffAction::Scroll(Scroll::Lines((area.rows / 2).max(1) as isize))
}
Event::Key(Key::Ctrl('u')) => {
DiffAction::Scroll(Scroll::Lines(-((area.rows / 2).max(1) as isize)))
}
Event::Key(Key::Char('g') | Key::Home) => DiffAction::Scroll(Scroll::Top),
Event::Key(Key::Char('G') | Key::End) => DiffAction::Scroll(Scroll::Bottom),
_ => return Control::Continue,
};
match self.apply(action, area) {
ViewChange::Changed => Control::Redraw,
ViewChange::Unchanged => Control::Continue,
}
}
pub fn visible_highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
let window = self.highlight_window(area);
self.highlight_requests_in(window.start..window.visible_end)
}
pub fn lookahead_highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
let window = self.highlight_window(area);
self.highlight_requests_in(window.visible_end..window.lookahead_end)
}
pub fn highlight_requests(&mut self, area: Rect) -> Vec<HighlightRequest> {
let window = self.highlight_window(area);
self.highlight_requests_in(window.start..window.lookahead_end)
}
fn highlight_window(&self, area: Rect) -> HighlightWindow {
let diff = self.layout(area).diff;
let view = View::new(
self.state.scroll.offset,
self.render_rows_for(self.state.scroll.offset, diff.rows),
diff.rows,
);
let start = view
.offset
.saturating_add(self.sticky_row_count(view.offset, diff.rows));
let visible_end = view.offset.saturating_add(diff.rows);
HighlightWindow {
start,
visible_end,
lookahead_end: visible_end.saturating_add(diff.rows),
}
}
fn highlight_requests_in(&mut self, rows: Range<usize>) -> Vec<HighlightRequest> {
let mut requests = Vec::new();
for row in rows {
let Some(meta) = self.diff_meta_at(row) else {
continue;
};
let key = self.key_for(&meta);
if self.highlights.contains_key(&key) || self.pending_highlights.contains(&key) {
continue;
}
self.pending_highlights.insert(key.clone());
let source = self.highlight_source_for(&meta);
requests.push(HighlightRequest {
key,
hunk: meta.hunk,
row: meta.row,
path: meta.path,
source,
});
}
requests
}
pub fn cancel_highlights(&mut self, requests: impl IntoIterator<Item = HighlightRequest>) {
for request in requests {
self.pending_highlights.remove(&request.key);
}
}
pub fn retry_pending_highlights(&mut self) {
self.pending_highlights.clear();
}
fn key_for(&self, meta: &DiffLineMeta) -> HighlightKey {
HighlightKey::new(HighlightKeyInput {
file: meta.file,
side: meta.side,
source_line: meta.source_line,
text: &meta.text,
syntax: self.options.syntax.as_deref(),
theme: &self.options.theme,
})
}
fn highlight_source_for(&mut self, meta: &DiffLineMeta) -> HighlightSource {
if meta.kind == DiffLineKind::NoNewline {
return meta.single_row_source();
}
let key = (meta.file, meta.hunk, meta.side);
if let Some(source) = self.hunk_highlight_sources.get(&key) {
return source.clone();
}
let source = self.build_highlight_source(meta);
self.hunk_highlight_sources.insert(key, source.clone());
source
}
fn build_highlight_source(&self, meta: &DiffLineMeta) -> HighlightSource {
let Some(file) = self.document.files.iter().find(|file| file.id == meta.file) else {
return meta.single_row_source();
};
let Some(hunk) = file.hunks.iter().find(|hunk| hunk.id == meta.hunk) else {
return meta.single_row_source();
};
if let Some(source) = self.file_source(file, meta.side) {
if source.matches_hunk(hunk, meta.side) {
return source.clone();
}
}
hunk.highlight_source(meta.side)
}
fn file_source(&self, file: &FileDiff, side: DiffSide) -> Option<&HighlightSource> {
let oid = match side {
DiffSide::Old => file.header.old_oid,
DiffSide::New => file.header.new_oid,
};
if let Some(text) = oid.and_then(|oid| self.blob_sources.get(&oid)) {
return Some(text);
}
if side == DiffSide::New && oid.is_none() {
return file
.header
.new_path
.as_ref()
.and_then(|path| self.worktree_sources.get(path));
}
None
}
pub fn apply_highlights(&mut self, results: impl IntoIterator<Item = HighlightResult>) -> bool {
let mut changed = false;
for result in results {
self.pending_highlights.remove(&result.key);
let Some(hunk) = self
.document
.files
.iter()
.find(|f| f.id == result.key.file)
.and_then(|f| f.hunks.iter().find(|h| h.id == result.hunk))
else {
continue;
};
let Some(source) = hunk.lines.iter().find(|line| line.id == result.row) else {
continue;
};
if !source.text.is_empty() && result.line.width() == 0 {
continue;
}
if let Entry::Vacant(slot) = self.word_diffs.entry(result.hunk) {
slot.insert(crate::word::compute(hunk));
}
let bg = match result.key.side {
DiffSide::New => self.options.diff_palette.positive_word_bg,
DiffSide::Old => self.options.diff_palette.negative_word_bg,
};
let line = if let Some(ranges) = self
.word_diffs
.get(&result.hunk)
.and_then(|changes| changes.get(&result.row))
{
result.line.overlay_ranges(ranges, Style::default().bg(bg))
} else {
result.line
};
self.highlights.insert(result.key, line);
changed = true;
}
changed
}
pub fn apply_visible_highlights<H>(&mut self, area: Rect, highlighter: &mut H) -> bool
where
H: DiffHighlighter + ?Sized,
{
let requests = self.highlight_requests(area);
if requests.is_empty() {
return false;
}
self.apply_highlights(highlighter.highlight_batch(requests))
}
fn file_rows(&self, file: &FileDiff) -> usize {
file.rendered_rows(self.hunk_gaps(file.id))
}
fn hunk_gaps(&self, file: FileId) -> HunkGaps {
if self.context.is_expanded(file) {
HunkGaps::Hidden
} else {
HunkGaps::Visible
}
}
fn render_row(&self, row: usize, cols: usize) -> Option<RenderRow> {
let cols = cols.max(MIN_RENDER_COLS);
if let Some(line) = self.preamble.get(row) {
let line = line.clone();
let line = if self.dims_unfocused(DiffFocus::Commit) {
Self::muted_line(line)
} else {
line
};
return Some(RenderRow { line, diff: None });
}
self.file_row_location(row)
.map(|location| self.render_file_row(location, cols))
}
fn render_file_row(&self, location: FileRowLocation<'_>, cols: usize) -> RenderRow {
let file = location.file;
let border = FILE_BORDER;
let inner_cols = cols.saturating_sub(2);
let child_cols = cols.saturating_sub(4);
let local = location.local;
let bottom = location.end - location.start - 1;
let wrap_child = |mut line: Line| {
Line::truncate(&mut line, child_cols, "…");
Line::pad(&mut line, child_cols);
Line::new(border.left(1)).extend(line).item(border.right(1))
};
let hunk_gap_line = Line::blank()
.extend(Line::blank().padded(REVIEW_GUTTER_WIDTH))
.extend(Line::blank().padded(LINE_NUMBER_WIDTH))
.extend(Line::blank().padded(LINE_NUMBER_WIDTH))
.extend(Self::marker_cell(HUNK_GAP_MARKER_CELL, colors::rgb::DIM));
match local {
FILE_TOP_ROW => {
return RenderRow {
line: border.top(inner_cols),
diff: None,
};
}
FILE_HEADER_ROW => {
let decoration = self.file_decoration(file.id);
let summary = self
.summaries
.get(&file.id)
.copied()
.unwrap_or_else(|| FileSummary::from(file));
return RenderRow {
line: wrap_child(file.header_line(
child_cols,
self.options.diff_palette,
&decoration,
summary,
)),
diff: None,
};
}
row if row == bottom => {
return RenderRow {
line: border.bottom(inner_cols),
diff: None,
};
}
_ if !file.has_body() => {
return RenderRow {
line: border.bottom(inner_cols),
diff: None,
};
}
FILE_DIVIDER_ROW => {
return RenderRow {
line: border.divider(inner_cols, DIVIDER),
diff: None,
};
}
_ => {}
}
let mut body_rows = file.hunk_body_rows(self.hunk_gaps(file.id)).peekable();
while let Some(&(hunk, body_start)) = body_rows.peek() {
let body_end = body_start + hunk.lines.len();
if local < body_start {
return RenderRow {
line: wrap_child(hunk_gap_line),
diff: None,
};
}
if local < body_end {
let decoration = self.hunk_decoration(file.id, hunk.id);
let mut row =
self.hunk_row_at(file, hunk, local - body_start, child_cols, &decoration);
if local == body_start {
row.line = Self::overlay_corner(row.line, &decoration.corner, child_cols);
}
let expanded = row
.diff
.as_ref()
.is_some_and(|meta| self.expanded_context.contains(&meta.row));
if expanded || self.dims_unfocused(DiffFocus::Hunk(hunk.id)) {
row.line = Self::muted_line(row.line);
}
return RenderRow {
line: wrap_child(row.line),
diff: row.diff,
};
}
body_rows.next();
}
RenderRow {
line: border.bottom(inner_cols),
diff: None,
}
}
fn diff_meta_at(&self, row: usize) -> Option<DiffLineMeta> {
let location = self.file_row_location(row)?;
for (hunk, body_start) in location
.file
.hunk_body_rows(self.hunk_gaps(location.file.id))
{
let body_end = body_start + hunk.lines.len();
if location.local < body_start {
return None;
}
if location.local < body_end {
return Some(self.hunk_meta_at(location.file, hunk, location.local - body_start));
}
}
None
}
fn file_row_location(&self, row: usize) -> Option<FileRowLocation<'_>> {
let files = &self.index.files;
let index = files
.partition_point(|indexed| indexed.start <= row)
.checked_sub(1)?;
let indexed = files[index];
let end = files
.get(index + 1)
.map_or(self.index.rows, |next| next.start);
if row >= end {
return None;
}
let file = self.document.files.get(indexed.file_index)?;
Some(FileRowLocation {
file,
start: indexed.start,
end,
local: row - indexed.start,
})
}
fn rebuild_index(&mut self) {
let mut rows = self.preamble.len();
let mut files = Vec::new();
for (file_index, file) in self.document.files.iter().enumerate() {
files.push(IndexedFileRows {
file_index,
start: rows,
});
rows += self.file_rows(file);
}
self.index = RowIndex { files, rows };
let document = &self.document;
self.hunk_focus.retain(|file, hunk| {
document.files.iter().any(|candidate| {
candidate.id == *file
&& candidate
.hunks
.iter()
.any(|candidate| candidate.id == *hunk)
})
});
let focus = self.state.focus;
self.set_focus(focus);
}
fn preamble(commit: Option<&CommitHeader>, cols: usize) -> Vec<Line> {
let Some(commit) = commit else {
return Vec::new();
};
let message_lines = commit
.message
.split('\n')
.map(|raw| {
let trimmed = raw.trim_end();
trimmed.strip_prefix(" ").unwrap_or(trimmed)
})
.collect::<Vec<_>>();
let message = {
let first_non_empty = message_lines.iter().position(|text| !text.is_empty());
let last_non_empty = message_lines.iter().rposition(|text| !text.is_empty());
if let (Some(start), Some(end)) = (first_non_empty, last_non_empty) {
let lines = &message_lines[start..=end];
let trailer_start = lines
.iter()
.rposition(|text| text.is_empty())
.map(|index| index + 1)
.filter(|&index| {
index < lines.len()
&& lines[index..]
.iter()
.try_fold(false, |has_trailer, text| {
if text.as_bytes().first().is_some_and(u8::is_ascii_whitespace)
{
has_trailer.then_some(true)
} else {
text.split_once(':')
.is_some_and(|(key, value)| {
!key.is_empty()
&& !value.trim().is_empty()
&& key.chars().all(|character| {
character.is_ascii_alphanumeric()
|| character == '-'
})
})
.then_some(true)
}
})
.is_some()
});
lines
.iter()
.enumerate()
.map(|(index, &text)| {
let line = if text.is_empty() {
Line::blank()
} else {
Line::new(text.to_owned())
};
if index == 0 {
line.style(Style::default().bold())
} else if trailer_start.is_some_and(|start| index >= start) {
line.style(Style::new(colors::rgb::DIM))
} else {
line
}
})
.collect()
} else {
Vec::new()
}
};
let hash = commit.hash.to_string();
let hash_width = hash.width() + commit.decoration.as_deref().map_or(0, |d| 1 + d.width());
let value_width = std::iter::once(hash_width)
.chain(commit.signature.iter().map(|line| line.as_str().width()))
.chain(commit.headers.iter().map(|h| h.value.as_str().width()))
.max()
.unwrap_or_default();
let hash_line = Line::new(Label::new(hash.as_str()).fg(colors::rgb::ORANGE));
let hash_value = if let Some(decoration) = commit.decoration.as_deref() {
HStack::default()
.child(hash_line)
.spacer()
.child(Line::new(Label::new(decoration).fg(colors::rgb::DIM)))
.to_line(Constraint::tight(value_width))
} else {
hash_line
};
let mut table = Table::<2, Line>::new(TableOptions {
overflow: true,
spacing: 2,
..TableOptions::default()
})
.row([
Line::new(Label::new("commit").fg(colors::rgb::DIM)),
hash_value,
]);
for (index, signature) in commit.signature.iter().enumerate() {
let key = if index == 0 { "signature" } else { "" };
table.push([
Line::new(Label::new(key).fg(colors::rgb::DIM)),
Line::new(signature.as_str()),
]);
}
for header in &commit.headers {
let key = header.key.to_ascii_lowercase();
let header_value = if header.key.eq_ignore_ascii_case("date") {
Line::new(header.value.as_str()).style(Style::new(colors::rgb::DIM))
} else {
Line::new(header.value.as_str())
};
table.push([
Line::new(Label::new(&key).fg(colors::rgb::DIM)),
header_value,
]);
}
let mut stack = VStack::default()
.bordered(tui::Border::new(colors::FAINT))
.padding(1)
.child(table);
if !message.is_empty() {
stack = stack.divider_cell(Cell::new(DIVIDER, Style::new(colors::FAINT)));
for line in message {
stack.push(line);
}
}
stack.lines(Constraint::tight(cols))
}
fn sticky_rows(&self, scroll: usize, visible_rows: usize, cols: usize) -> Vec<Line> {
self.sticky_header_rows(scroll, visible_rows)
.map(|sticky| {
(STICKY_HEADER_ROWS - sticky.rows..STICKY_HEADER_ROWS)
.map(|index| {
if index == STICKY_HEADER_ROWS - 1 {
FILE_BORDER.divider(cols.saturating_sub(2), STICKY_DIVIDER)
} else {
self.render_row(sticky.start + index, cols)
.map(|row| row.line)
.unwrap_or_default()
}
})
.collect()
})
.unwrap_or_default()
}
fn sticky_row_count(&self, scroll: usize, visible_rows: usize) -> usize {
self.sticky_header_rows(scroll, visible_rows)
.map_or(0, |sticky| sticky.rows)
}
#[cfg(test)]
fn sticky_start(&self, scroll: usize, visible_rows: usize) -> Option<usize> {
self.sticky_header_rows(scroll, visible_rows)
.map(|sticky| sticky.start)
}
fn sticky_header_rows(&self, scroll: usize, visible_rows: usize) -> Option<StickyHeaderRows> {
let scroll = scroll.min(
self.render_rows_for(scroll, visible_rows)
.saturating_sub(visible_rows),
);
if scroll == 0 {
return None;
}
let location = self.file_row_location(scroll)?;
if scroll <= location.start {
return None;
}
let file_bottom = location.end.saturating_sub(location.start + 1);
let rows = file_bottom
.saturating_sub(location.local)
.min(STICKY_HEADER_ROWS)
.min(visible_rows);
if rows == 0 {
return None;
}
Some(StickyHeaderRows {
start: location.start,
rows,
})
}
fn focus(&mut self, visible_rows: usize, delta: isize, filter: FocusFilter) {
let targets = self.focus_targets(filter);
if targets.is_empty() {
return;
}
let current = self
.state
.focus
.and_then(|focus| targets.iter().position(|target| target.focus == focus))
.or_else(|| {
if filter != FocusFilter::File {
return None;
}
self.focused_file().and_then(|file| {
targets
.iter()
.position(|target| target.focus == DiffFocus::File(file))
})
});
let next = match (current, filter, delta.is_negative()) {
(Some(index), _, true) => index.checked_sub(1),
(Some(index), _, false) => index.checked_add(1).filter(|index| *index < targets.len()),
(None, FocusFilter::HunkNavigation, true) => targets
.partition_point(|target| target.row <= self.state.scroll.offset)
.checked_sub(1),
(None, FocusFilter::HunkNavigation, false) => {
let index = targets.partition_point(|target| target.row < self.state.scroll.offset);
(index < targets.len()).then_some(index)
}
(None, FocusFilter::File, true) => targets.len().checked_sub(1),
(None, FocusFilter::File, false) => Some(0),
};
let Some(target) = next.and_then(|next| targets.get(next)) else {
return;
};
if filter == FocusFilter::File {
let DiffFocus::File(file) = target.focus else {
return;
};
self.focus_file(file, visible_rows);
return;
}
let was_hunk_focused = matches!(self.state.focus, Some(DiffFocus::Hunk(_)));
let focus = target.focus;
self.set_focus(Some(focus));
let current = self.state.scroll.offset;
let preserved = target.scroll_offset(current, visible_rows, HunkScroll::Preserve);
let placement = if preserved == current || was_hunk_focused {
HunkScroll::Preserve
} else {
HunkScroll::Center
};
let next = target.scroll_offset(current, visible_rows, placement);
self.state
.scroll
.set_offset(next, self.scroll_rows(visible_rows), visible_rows);
}
fn focus_targets(&self, filter: FocusFilter) -> Vec<FocusTarget> {
let mut targets = Vec::new();
if filter == FocusFilter::HunkNavigation && self.document.commit.is_some() {
targets.push(FocusTarget {
focus: DiffFocus::Commit,
row: 0,
height: self.preamble.len(),
file_start: 0,
});
}
for indexed in &self.index.files {
let Some(file) = self.document.files.get(indexed.file_index) else {
continue;
};
if filter == FocusFilter::File {
targets.push(FocusTarget {
focus: DiffFocus::File(file.id),
row: indexed.start,
height: 1,
file_start: indexed.start,
});
}
if filter == FocusFilter::HunkNavigation {
for (hunk, local) in file.hunk_body_rows(self.hunk_gaps(file.id)) {
let leading = hunk
.lines
.iter()
.take_while(|line| self.expanded_context.contains(&line.id))
.count();
let trailing = hunk
.lines
.iter()
.rev()
.take_while(|line| self.expanded_context.contains(&line.id))
.count();
targets.push(FocusTarget {
focus: DiffFocus::Hunk(hunk.id),
row: indexed.start + local + leading,
height: hunk.lines.len().saturating_sub(leading + trailing),
file_start: indexed.start,
});
}
}
}
targets
}
fn hunk_row_at(
&self,
file: &FileDiff,
hunk: &crate::Hunk,
line_index: usize,
inner: usize,
decoration: &HunkDecoration,
) -> RenderRow {
let (old_line, new_line) = Self::hunk_line_numbers(hunk, line_index);
let line = &hunk.lines[line_index];
let meta = DiffLineMeta::new(file, hunk.id, line, old_line, new_line);
self.hunk_row(meta, line, old_line, inner, decoration)
}
fn hunk_meta_at(&self, file: &FileDiff, hunk: &crate::Hunk, line_index: usize) -> DiffLineMeta {
let (old_line, new_line) = Self::hunk_line_numbers(hunk, line_index);
DiffLineMeta::new(file, hunk.id, &hunk.lines[line_index], old_line, new_line)
}
fn hunk_line_numbers(hunk: &crate::Hunk, line_index: usize) -> (u32, u32) {
let mut old_line = hunk.header.old_line_no;
let mut new_line = hunk.header.new_line_no;
for line in &hunk.lines[..line_index] {
old_line = old_line.saturating_add(line.kind.old_len());
new_line = new_line.saturating_add(line.kind.new_len());
}
(old_line, new_line)
}
fn hunk_row(
&self,
meta: DiffLineMeta,
line: &DiffLine,
old_line: u32,
row_cols: usize,
decoration: &HunkDecoration,
) -> RenderRow {
let line_number_fg = if matches!(self.state.focus, Some(DiffFocus::Hunk(focused)) if focused == meta.hunk)
{
SELECTED_LINE_NUMBER_FG
} else {
LINE_NUMBER_FG
};
let (cells, source, row_style, source_style) = match line.kind {
DiffLineKind::Addition => (
[
Self::blank_number(self.options.diff_palette.positive_row_bg),
Self::number_cell(
meta.source_line,
line_number_fg,
self.options.diff_palette.positive_row_bg,
),
Self::marker_cell(" + ", self.options.diff_palette.positive_fg),
],
self.rendered_source(&meta),
Style::default().bg(self.options.diff_palette.positive_row_bg),
Style::default().bg(self.options.diff_palette.positive_row_bg),
),
DiffLineKind::Deletion => (
[
Self::number_cell(
meta.source_line,
line_number_fg,
self.options.diff_palette.negative_row_bg,
),
Self::blank_number(self.options.diff_palette.negative_row_bg),
Self::marker_cell(" - ", self.options.diff_palette.negative_fg),
],
self.rendered_source(&meta),
Style::default().bg(self.options.diff_palette.negative_row_bg),
Style::default()
.bg(self.options.diff_palette.negative_row_bg)
.dim(),
),
DiffLineKind::Context => (
[
Self::number_cell(old_line, line_number_fg, Color::Unset),
Self::number_cell(meta.source_line, line_number_fg, Color::Unset),
Self::marker_cell(" ", Color::Unset),
],
self.rendered_source(&meta),
Style::default(),
Style::default(),
),
DiffLineKind::NoNewline => (
[
Line::blank().padded(LINE_NUMBER_WIDTH),
Line::blank().padded(LINE_NUMBER_WIDTH),
Self::marker_cell(" ", Color::Unset),
],
Line::new(NO_NEWLINE_MARKER).style(Style::default().fg(colors::rgb::DIM)),
Style::default(),
Style::default(),
),
};
let decoration = HunkRowDecoration {
gutter: if matches!(line.kind, DiffLineKind::Addition | DiffLineKind::Deletion) {
decoration.gutter
} else {
None
},
style: if matches!(self.state.focus, Some(DiffFocus::Hunk(hunk)) if hunk == meta.hunk) {
None
} else {
decoration.style
},
};
let rendered = self.hunk_line(cells, source, row_cols, row_style, source_style, decoration);
RenderRow {
line: rendered,
diff: Some(meta),
}
}
fn hunk_line(
&self,
cells: [Line; 3],
mut source: Line,
row_cols: usize,
row_style: Style,
source_style: Style,
decoration: HunkRowDecoration,
) -> Line {
let source_cols =
row_cols.saturating_sub(REVIEW_GUTTER_WIDTH + LINE_NUMBER_WIDTH * 2 + MARKER_WIDTH);
if source_cols > 0 {
Line::truncate(&mut source, source_cols, "…");
let source_width = source.width();
if source_width < source_cols {
let padding = " ".repeat(source_cols - source_width);
source.push(Label::new(&padding));
}
}
let source = source.style(source_style);
let body_cols = row_cols.saturating_sub(REVIEW_GUTTER_WIDTH);
let mut body = Line::blank()
.extend(cells[0].clone())
.extend(cells[1].clone())
.extend(cells[2].clone())
.extend(source);
Line::pad(&mut body, body_cols);
Line::truncate(&mut body, body_cols, "…");
body = body.style(row_style);
if let Some(style) = decoration.style {
body = body.style(style);
}
let gutter = decoration.gutter.map_or_else(
|| Line::blank().padded(REVIEW_GUTTER_WIDTH),
|paint| Line::new(Label::from_char(paint.item).style(paint.style)),
);
gutter.extend(body)
}
fn rendered_source(&self, meta: &DiffLineMeta) -> Line {
if let Some(line) = self.highlights.get(&self.key_for(meta)) {
let line = line.clone();
return if meta.text.contains('\t') {
Self::expand_source_tabs(line)
} else {
line
};
}
Self::plain_source_line(meta)
}
fn plain_source_line(meta: &DiffLineMeta) -> Line {
if meta.text.contains('\t') {
Self::expand_source_tabs(Line::new(meta.text.as_str()))
} else {
Line::new(meta.text.as_str())
}
}
fn expand_source_tabs(line: Line) -> Line {
let mut expanded = Line::blank();
for label in line {
if !label.content().contains('\t') {
expanded.push(label);
continue;
}
let style = label.paint.style();
let tab_style = style.fg(colors::FAINT);
let mut start = 0;
for (index, _) in label.content().match_indices('\t') {
if start < index {
expanded.push(Label::new(&label.content()[start..index]).style(style));
}
expanded.push(Label::new(SOURCE_TAB_MARKER).style(tab_style));
start = index + 1;
}
if start < label.content().len() {
expanded.push(Label::new(&label.content()[start..]).style(style));
}
}
expanded
}
fn number_cell(value: u32, foreground: Color, background: Color) -> Line {
Line::new(Label::new(&value.to_string()).fg(foreground).bg(background))
.padded(LINE_NUMBER_WIDTH)
}
fn blank_number(background: Color) -> Line {
Line::new(Label::space().bg(background)).padded(LINE_NUMBER_WIDTH)
}
fn marker_cell(marker: &str, foreground: Color) -> Line {
Line::new(Label::new(marker).fg(foreground)).padded(MARKER_WIDTH)
}
fn dims_unfocused(&self, target: DiffFocus) -> bool {
self.options.hunk_focus == HunkFocus::DimUnfocused
&& matches!(self.state.focus, Some(focus) if focus != target)
}
fn muted_line(line: Line) -> Line {
line.into_iter()
.map(|label| {
let style = label
.paint
.style()
.bg(Self::muted_background(label.paint.style().bg_color()))
.dim();
Label::new(label.content()).style(style)
})
.collect::<Vec<_>>()
.into()
}
fn muted_background(color: Color) -> Color {
match color {
Color::RGB(r, g, b) => Color::RGB(r / 2, g / 2, b / 2),
color => color,
}
}
fn overlay_corner(mut line: Line, corner: &Line, cols: usize) -> Line {
let width = corner.width();
if width == 0 || width >= cols {
return line;
}
let left = cols - width;
Line::truncate(&mut line, left, "…");
Line::pad(&mut line, left);
line.extend(corner.clone())
}
pub fn scrollbar_style() -> ScrollbarStyle {
ScrollbarStyle::new(
Cell::new(SCROLLBAR_TRACK, Style::default().fg(colors::FAINT)),
Cell::new(SCROLLBAR_THUMB, Style::default().fg(colors::FAINT)),
)
}
}
impl Widget for DiffViewer {
fn size(&self, parent: Constraint) -> Size {
let cols = if parent.max.cols == usize::MAX {
MIN_RENDER_COLS
} else {
parent.max.cols
};
Size::new(cols, self.index.rows).constrain(parent)
}
fn render(&mut self, area: Rect, buf: &mut Buffer) {
DiffViewer::render(self, area, buf);
}
fn to_buffer(&mut self, constraints: Constraint) -> Buffer {
let size = self.size(constraints);
let area = Rect::from_size(size);
let mut buffer = Buffer::empty(area);
DiffViewer::render(self, area, &mut buffer);
buffer
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct FocusTarget {
focus: DiffFocus,
row: usize,
height: usize,
file_start: usize,
}
impl FocusTarget {
fn sticky_rows(self, scroll: usize) -> usize {
if scroll > self.file_start {
STICKY_HEADER_ROWS
} else {
0
}
}
fn scroll_offset(self, current: usize, visible_rows: usize, placement: HunkScroll) -> usize {
if visible_rows == 0 {
return current;
}
let height = self.height.max(1);
let top = self.row.saturating_sub(self.sticky_rows(self.row));
let leading = self.row.saturating_sub(top);
let available = visible_rows.saturating_sub(leading);
if height > available {
return top;
}
match placement {
HunkScroll::Center => {
let screen_row = leading + available.saturating_sub(height) / 2;
self.row.saturating_sub(screen_row)
}
HunkScroll::Preserve => {
let top = self.sticky_rows(current).saturating_add(1);
let bottom = visible_rows.saturating_sub(1);
let screen_top = self.row.saturating_sub(current);
let screen_bottom = screen_top.saturating_add(height);
if screen_top < top {
self.row.saturating_sub(top)
} else if screen_bottom > bottom {
self.row.saturating_add(height).saturating_sub(bottom)
} else {
current
}
}
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum FocusFilter {
File,
HunkNavigation,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum HunkScroll {
Center,
Preserve,
}
impl FileDiff {
fn has_body(&self) -> bool {
!self.hunks.is_empty()
}
fn rendered_rows(&self, gaps: HunkGaps) -> usize {
if !self.has_body() {
return EMPTY_CARD_ROWS;
}
let gaps = match gaps {
HunkGaps::Visible => self.hunks.len().saturating_sub(1),
HunkGaps::Hidden => 0,
};
let body: usize = self.hunks.iter().map(|hunk| hunk.lines.len()).sum();
HUNK_BODY_START + body + gaps + 1
}
fn hunk_body_rows(&self, gaps: HunkGaps) -> impl Iterator<Item = (&Hunk, usize)> + '_ {
self.hunks
.iter()
.enumerate()
.scan(HUNK_BODY_START, move |local, (index, hunk)| {
if index > 0 && gaps == HunkGaps::Visible {
*local += 1;
}
let row = *local;
*local += hunk.lines.len();
Some((hunk, row))
})
}
fn header_line(
&self,
cols: usize,
palette: DiffPalette,
decoration: &FileDecoration,
summary: FileSummary,
) -> Line {
let mut left = Line::blank();
if let Some(status) = &decoration.status {
left.push(Label::from_char(status.item).style(status.style));
} else {
let fg = match self.header.kind {
FileKind::Added => palette.positive_fg,
FileKind::Deleted => palette.negative_fg,
FileKind::Renamed => FILE_KIND_BADGE_FG,
FileKind::Modified
| FileKind::Copied
| FileKind::ModeChanged
| FileKind::Binary => Color::Yellow,
};
left.push(Label::from_char(self.header.kind.marker()).fg(fg));
}
left.push(Label::space());
left = left.extend(self.path_line());
if let Some(loc) = summary.loc {
left.push(Label::space());
left.push(Label::new(&format!("{loc} LOC")).fg(colors::rgb::DIM));
}
if let Some(badge) = self.badge(palette) {
left.push(Label::space());
left = left.extend(badge.line());
}
let mut right = decoration.annotations.clone();
let stats = decoration.stats.unwrap_or(summary.stats);
if let Some(progress) = decoration.progress {
let mut progress_line = Self::progress_bar(progress, palette);
if !progress.is_complete()
&& let Some(stats) = Self::diffstat_line(stats.additions, stats.deletions, palette)
{
progress_line.push(Label::space());
progress_line =
progress_line.extend(Self::review_status_line(stats).labels().iter().cloned());
}
right.push(progress_line);
} else if let Some(stats) = Self::diffstat_line(stats.additions, stats.deletions, palette) {
right.push(stats);
}
let mut header = HStack::default().child(left).spacer();
for (index, segment) in right.into_iter().enumerate() {
if index > 0 {
header = header.child(Line::new(
Label::new(FILE_HEADER_SEGMENT_SEPARATOR).fg(colors::rgb::DIM),
));
}
header = header.child(segment);
}
header.to_line(Constraint::tight(cols))
}
fn path_line(&self) -> Line {
match self.header.kind {
FileKind::Renamed | FileKind::Copied => Line::spaced([
Label::from(Self::display_path(self.header.old_path.as_ref())),
Label::from(RENAME_ARROW),
Label::from(Self::display_path(self.header.new_path.as_ref())),
]),
_ => Line::new(Self::display_path(self.header.display_path())),
}
}
fn diffstat_line(additions: usize, deletions: usize, palette: DiffPalette) -> Option<Line> {
if additions == 0 && deletions == 0 {
return None;
}
let mut line = Line::blank();
if additions > 0 {
line.push(Label::new(&format!("+{additions}")).fg(palette.positive_fg));
}
if additions > 0 && deletions > 0 {
line.push(Label::space());
}
if deletions > 0 {
line.push(Label::new(&format!("-{deletions}")).fg(palette.negative_fg));
}
Some(line)
}
fn review_status_line(line: Line) -> Line {
let padding = FILE_REVIEW_STATUS_COLS.saturating_sub(line.width());
Line::new(Label::new(&" ".repeat(padding))).extend(line.labels().iter().cloned())
}
fn progress_bar(progress: ReviewProgress, palette: DiffPalette) -> Line {
let filled = progress.filled(FILE_PROGRESS_BAR_WIDTH);
let empty = FILE_PROGRESS_BAR_WIDTH - filled;
Line::blank()
.item(Label::new(&FILE_PROGRESS_BAR_GLYPH.repeat(filled)).fg(palette.positive_fg))
.item(Label::new(&FILE_PROGRESS_BAR_GLYPH.repeat(empty)).fg(colors::FAINT))
}
fn loc(&self) -> usize {
let deleted = self.header.kind == FileKind::Deleted;
self.hunks
.iter()
.flat_map(|hunk| &hunk.lines)
.filter(|line| {
let displayed = match line.kind {
DiffLineKind::Context => true,
DiffLineKind::Addition => !deleted,
DiffLineKind::Deletion => deleted,
DiffLineKind::NoNewline => false,
};
displayed && !line.text.trim().is_empty()
})
.count()
}
fn badge(&self, palette: DiffPalette) -> Option<Badge> {
match self.header.kind {
FileKind::Added => Some(Self::change_badge(
"created",
palette.positive_fg,
palette.positive_row_bg,
)),
FileKind::Deleted => Some(Self::change_badge(
"deleted",
palette.negative_fg,
palette.negative_row_bg,
)),
FileKind::Renamed => Some(Self::change_badge(
"moved",
FILE_KIND_BADGE_FG,
FILE_KIND_BADGE_BG,
)),
FileKind::Copied => Some(Self::change_badge(
"copied",
FILE_KIND_BADGE_FG,
FILE_KIND_BADGE_BG,
)),
FileKind::ModeChanged => Some(Self::change_badge(
"mode changed",
FILE_KIND_BADGE_FG,
FILE_KIND_BADGE_BG,
)),
FileKind::Binary => Some(Self::change_badge(
"binary",
Color::Yellow,
Color::Fixed(236),
)),
FileKind::Modified => None,
}
}
fn change_badge(text: &str, foreground: Color, background: Color) -> Badge {
let style = Style::new(foreground).bg(background);
Badge::new(text)
.caps(" ", " ")
.cap_style(style)
.style(style)
}
fn display_path(path: Option<&PathBuf>) -> String {
path.map_or_else(|| "<unknown>".to_owned(), |path| path.display().to_string())
}
}
impl DiffLineMeta {
fn new(file: &FileDiff, hunk: HunkId, line: &DiffLine, old_line: u32, new_line: u32) -> Self {
let side = match line.kind {
DiffLineKind::Deletion => DiffSide::Old,
_ => DiffSide::New,
};
let source_line = match side {
DiffSide::Old => old_line,
DiffSide::New => new_line,
};
Self {
file: file.id,
hunk,
row: line.id,
kind: line.kind,
side,
source_line,
text: line.text.clone(),
path: file.source_path(side),
}
}
fn single_row_source(&self) -> HighlightSource {
HighlightSource::new(self.text.clone(), self.source_line)
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use std::fs;
use std::path::PathBuf;
use std::str::FromStr;
use std::time::{SystemTime, UNIX_EPOCH};
use super::*;
use crate::Decode;
use crate::DiffDocument;
use rustik_repo::{DiffRepository, RepoError};
use rustik_tui::{Modifiers, Point};
fn left_click(x: usize, y: usize, modifiers: Modifiers) -> Event<()> {
Event::Mouse(Mouse::Press {
button: MouseButton::Left,
at: Point::new(x, y),
modifiers,
})
}
fn sample_viewer() -> DiffViewer {
let document = DiffDocument::decode_str(
"\
diff --git a/a.rs b/a.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.rs
+++ b/a.rs
@@ -1,3 +1,4 @@ fn main
context
-old
+new
+extra
tail
",
)
.unwrap();
DiffViewer::new(document, DiffOptions::default())
}
#[test]
fn binary_file_header_omits_loc() {
let document = DiffDocument::decode_str(
"\
diff --git a/image.png b/image.png
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
Binary files a/image.png and b/image.png differ
",
)
.unwrap();
let viewer = DiffViewer::new(document, DiffOptions::default());
let header = viewer.render_row(0, 80).unwrap().line;
assert!(!header.to_string().contains("LOC"));
}
#[derive(Default)]
struct RecordingHighlighter {
batches: usize,
}
impl DiffHighlighter for RecordingHighlighter {
fn highlight_batch(&mut self, requests: Vec<HighlightRequest>) -> Vec<HighlightResult> {
self.batches += 1;
requests
.into_iter()
.map(|request| HighlightResult::new(request, Line::new("highlighted")))
.collect()
}
}
fn two_file_viewer() -> DiffViewer {
let document = DiffDocument::decode_str(
"\
diff --git a/a.rs b/a.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.rs
+++ b/a.rs
@@ -1,3 +1,4 @@ fn a
context
-old
+new
+extra
tail
diff --git a/b.rs b/b.rs
index 3333333333333333333333333333333333333333..4444444444444444444444444444444444444444 100644
--- a/b.rs
+++ b/b.rs
@@ -1,2 +1,2 @@ fn b
keep
-before
+after
",
)
.unwrap();
DiffViewer::new(document, DiffOptions::default())
}
fn two_hunk_viewer() -> DiffViewer {
let document = DiffDocument::decode_str(
"\
diff --git a/a.rs b/a.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.rs
+++ b/a.rs
@@ -1,2 +1,2 @@ fn first
keep
-old
+new
@@ -10,2 +10,2 @@ fn second
keep
-before
+after
",
)
.unwrap();
DiffViewer::new(document, DiffOptions::default())
}
fn commit_viewer() -> DiffViewer {
let document = DiffDocument::decode_str(
"\
commit 1234567890abcdef1234567890abcdef12345678
Author: A <a@example.com>
Summary
diff --git a/a.rs b/a.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.rs
+++ b/a.rs
@@ -1,2 +1,2 @@ fn first
keep
-old
+new
@@ -10,2 +10,2 @@ fn second
keep
-before
+after
",
)
.unwrap();
DiffViewer::new(
document,
DiffOptions {
hunk_focus: HunkFocus::DimUnfocused,
..DiffOptions::default()
},
)
}
fn scroll_viewer() -> DiffViewer {
let document = DiffDocument::decode_str(
"\
diff --git a/a.rs b/a.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.rs
+++ b/a.rs
@@ -1,20 +1,20 @@ fn main
line 01
line 02
line 03
line 04
line 05
line 06
line 07
line 08
line 09
line 10
line 11
line 12
line 13
line 14
line 15
line 16
line 17
line 18
line 19
line 20
",
)
.unwrap();
DiffViewer::new(document, DiffOptions::default())
}
fn tree_viewer() -> DiffViewer {
let document = DiffDocument::decode_str(
"\
diff --git a/a.rs b/a.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.rs
+++ b/a.rs
@@ -1 +1 @@
-old
+new
diff --git a/b.rs b/b.rs
index 3333333333333333333333333333333333333333..4444444444444444444444444444444444444444 100644
--- a/b.rs
+++ b/b.rs
@@ -1 +1 @@
-before
+after
",
)
.unwrap();
DiffViewer::new(
document,
DiffOptions {
file_tree: FileTreeMode::Auto,
file_tree_root: "rustik".to_owned(),
..DiffOptions::default()
},
)
}
fn long_file_tree_viewer() -> DiffViewer {
let document = DiffDocument::decode_str(
"\
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
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/crates/diff/tests/golden/sticky_header_before_next_file_64x5.txt
+++ b/crates/diff/tests/golden/sticky_header_before_next_file_64x5.txt
@@ -1 +1 @@
-old
+new
",
)
.unwrap();
DiffViewer::new(
document,
DiffOptions {
file_tree: FileTreeMode::Auto,
file_tree_root: "rustik".to_owned(),
..DiffOptions::default()
},
)
}
fn nested_tree_viewer() -> DiffViewer {
let document = DiffDocument::decode_str(
"\
diff --git a/src/a.rs b/src/a.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/src/a.rs
+++ b/src/a.rs
@@ -1 +1 @@
-old
+new
diff --git a/src/b.rs b/src/b.rs
index 3333333333333333333333333333333333333333..4444444444444444444444444444444444444444 100644
--- a/src/b.rs
+++ b/src/b.rs
@@ -1 +1 @@
-before
+after
diff --git a/README.md b/README.md
index 5555555555555555555555555555555555555555..6666666666666666666666666666666666666666 100644
--- a/README.md
+++ b/README.md
@@ -1 +1 @@
-old readme
+new readme
",
)
.unwrap();
DiffViewer::new(
document,
DiffOptions {
file_tree: FileTreeMode::Auto,
file_tree_root: "rustik".to_owned(),
..DiffOptions::default()
},
)
}
fn deep_tree_viewer() -> DiffViewer {
let document = DiffDocument::decode_str(
"\
diff --git a/src/app/a.rs b/src/app/a.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/src/app/a.rs
+++ b/src/app/a.rs
@@ -1 +1 @@
-old
+new
diff --git a/src/lib/b.rs b/src/lib/b.rs
index 3333333333333333333333333333333333333333..4444444444444444444444444444444444444444 100644
--- a/src/lib/b.rs
+++ b/src/lib/b.rs
@@ -1 +1 @@
-before
+after
diff --git a/README.md b/README.md
index 5555555555555555555555555555555555555555..6666666666666666666666666666666666666666 100644
--- a/README.md
+++ b/README.md
@@ -1 +1 @@
-old readme
+new readme
",
)
.unwrap();
DiffViewer::new(
document,
DiffOptions {
file_tree: FileTreeMode::Auto,
file_tree_root: "rustik".to_owned(),
..DiffOptions::default()
},
)
}
#[test]
fn hunk_focus_does_not_change_rendered_row_count() {
let viewer = sample_viewer();
let mut focused = sample_viewer();
focused.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
assert_eq!(focused.index.rows, viewer.index.rows);
}
#[test]
fn multi_hunk_file_counts_gap_row() {
let viewer = two_hunk_viewer();
assert_eq!(viewer.index.rows, 11);
}
#[test]
fn commit_is_initial_hunk_navigation_target() {
let mut viewer = commit_viewer();
let area = Rect::new(0, 0, 64, 6);
let targets = viewer
.focus_targets(FocusFilter::HunkNavigation)
.into_iter()
.map(|target| target.focus)
.collect::<Vec<_>>();
assert_eq!(
targets,
vec![
DiffFocus::Commit,
DiffFocus::Hunk(HunkId::new(0)),
DiffFocus::Hunk(HunkId::new(1)),
]
);
assert_eq!(viewer.state().focus, Some(DiffFocus::Commit));
assert_eq!(
viewer.apply(DiffAction::PreviousHunk, area),
ViewChange::Unchanged
);
viewer.apply(DiffAction::NextHunk, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
viewer.apply(DiffAction::PreviousHunk, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Commit));
assert_eq!(
viewer.apply(DiffAction::PreviousHunk, area),
ViewChange::Unchanged
);
}
#[test]
fn state_restore_accepts_commit_focus_only_with_commit_header() {
let state = DiffState {
focus: Some(DiffFocus::Commit),
..DiffState::default()
};
let mut commit = commit_viewer();
commit.set_focus(None);
commit.set_state(state.clone());
assert_eq!(commit.state().focus, Some(DiffFocus::Commit));
let mut patch = sample_viewer();
patch.set_state(state);
assert_eq!(patch.state().focus, None);
}
#[test]
fn hiding_first_hunk_restores_commit_boundary() {
let mut viewer = commit_viewer();
let area = Rect::new(0, 0, 64, 6);
let visible = viewer.document.files[0].clone();
let mut hidden = visible.clone();
hidden.hunks.remove(0);
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
viewer.replace_file_diffs_anchored([hidden], area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Commit));
viewer.replace_file_diffs_anchored([visible], area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Commit));
viewer.apply(DiffAction::NextHunk, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
}
#[test]
fn dim_unfocused_follows_commit_and_hunk_selection() {
let mut viewer = commit_viewer();
let summary = viewer
.preamble
.iter()
.position(|line| line.to_string().contains("Summary"))
.unwrap();
let hunk = viewer
.focus_targets(FocusFilter::HunkNavigation)
.into_iter()
.find(|target| target.focus == DiffFocus::Hunk(HunkId::new(0)))
.unwrap()
.row;
let is_dimmed = |viewer: &DiffViewer, row| {
let line = viewer.render_row(row, 80).unwrap().line;
format!("{}", line.styled()).contains("\x1b[2m")
};
assert!(!is_dimmed(&viewer, summary));
assert!(is_dimmed(&viewer, hunk));
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
assert!(is_dimmed(&viewer, summary));
assert!(!is_dimmed(&viewer, hunk));
viewer.set_focus(Some(DiffFocus::Commit));
assert!(!is_dimmed(&viewer, summary));
}
#[test]
fn patch_only_viewer_keeps_unset_focus_and_plain_hunks() {
let document = two_hunk_viewer().document().clone();
let mut viewer = DiffViewer::new(
document,
DiffOptions {
hunk_focus: HunkFocus::DimUnfocused,
..DiffOptions::default()
},
);
let area = Rect::new(0, 0, 64, 6);
let target = viewer.focus_targets(FocusFilter::HunkNavigation)[0];
let line = viewer.render_row(target.row, 64).unwrap().line;
assert_eq!(viewer.state().focus, None);
assert_eq!(target.focus, DiffFocus::Hunk(HunkId::new(0)));
assert!(!format!("{}", line.styled()).contains("\x1b[2m"));
viewer.apply(DiffAction::NextHunk, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
}
#[test]
fn focus_next_and_previous_visit_files_only() {
let mut viewer = two_file_viewer();
let area = Rect::new(0, 0, 64, 6);
viewer.apply(DiffAction::FocusNext, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
viewer.apply(DiffAction::FocusNext, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
viewer.apply(DiffAction::FocusPrevious, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
}
#[test]
fn file_navigation_restores_each_files_last_focused_hunk() {
let mut viewer = two_file_viewer();
let area = Rect::new(0, 0, 64, 6);
let mut second_a = viewer.document.files[0].hunks[0].clone();
second_a.id = HunkId::new(2);
viewer.document.files[0].hunks.push(second_a);
let mut second_b = viewer.document.files[1].hunks[0].clone();
second_b.id = HunkId::new(3);
viewer.document.files[1].hunks.push(second_b);
viewer.rebuild_index();
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(2))));
viewer.apply(DiffAction::FocusNext, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(3))));
viewer.apply(DiffAction::FocusPrevious, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(2))));
let target = viewer
.focus_targets(FocusFilter::HunkNavigation)
.into_iter()
.find(|target| target.focus == DiffFocus::Hunk(HunkId::new(2)))
.unwrap();
assert_ne!(viewer.state.scroll.offset, target.file_start);
assert!(
(viewer.state.scroll.offset..viewer.state.scroll.offset + area.rows)
.contains(&target.row)
);
viewer.apply(DiffAction::FocusNext, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(3))));
}
#[test]
fn file_navigation_forgets_replaced_hunks() {
let mut viewer = two_file_viewer();
let area = Rect::new(0, 0, 64, 6);
let mut hidden = viewer.document.files[0].hunks[0].clone();
hidden.id = HunkId::new(2);
viewer.document.files[0].hunks.push(hidden);
viewer.rebuild_index();
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(2))));
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(1))));
let mut file = viewer.document.files[0].clone();
file.hunks.remove(1);
viewer.replace_file_diffs([file]);
viewer.apply(DiffAction::FocusPrevious, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
}
#[test]
fn file_navigation_restores_hunk_after_visibility_replacement() {
let mut viewer = two_file_viewer();
let area = Rect::new(0, 0, 64, 6);
let mut later = viewer.document.files[0].hunks[0].clone();
later.id = HunkId::new(2);
viewer.document.files[0].hunks.push(later);
viewer.rebuild_index();
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(2))));
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(1))));
let visible = viewer.document.files[0].clone();
let mut hidden = visible.clone();
hidden.hunks.remove(1);
viewer.replace_file_diffs_anchored([hidden], area);
viewer.replace_file_diffs_anchored([visible], area);
viewer.apply(DiffAction::FocusPrevious, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(2))));
}
#[test]
fn restored_predecessor_replaces_stale_hidden_hunk_focus() {
let mut viewer = two_file_viewer();
let area = Rect::new(0, 0, 64, 6);
let mut later = viewer.document.files[0].hunks[0].clone();
later.id = HunkId::new(2);
viewer.document.files[0].hunks.push(later);
viewer.rebuild_index();
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(2))));
let visible = viewer.document.files[0].clone();
let mut hidden = visible.clone();
hidden.hunks.remove(1);
viewer.replace_file_diffs_anchored([hidden], area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
viewer.replace_file_diffs_anchored([visible], area);
viewer.apply(DiffAction::FocusNext, area);
viewer.apply(DiffAction::FocusPrevious, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
}
#[test]
fn standalone_input_navigates_files() {
let mut viewer = two_file_viewer();
let area = Rect::new(0, 0, 64, 6);
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('n')), area),
Control::Redraw
);
assert_eq!(viewer.focused_file(), Some(FileId::new(0)));
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('n')), area),
Control::Redraw
);
assert_eq!(viewer.focused_file(), Some(FileId::new(1)));
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('p')), area),
Control::Redraw
);
assert_eq!(viewer.focused_file(), Some(FileId::new(0)));
}
#[test]
fn initial_next_file_navigation_selects_first_file() {
let mut viewer = two_file_viewer();
let area = Rect::new(0, 0, 64, 6);
viewer.apply(DiffAction::FocusNext, area);
assert_eq!(viewer.focused_file(), Some(FileId::new(0)));
viewer.apply(DiffAction::FocusNext, area);
assert_eq!(viewer.focused_file(), Some(FileId::new(1)));
viewer.apply(DiffAction::FocusPrevious, area);
assert_eq!(viewer.focused_file(), Some(FileId::new(0)));
}
#[test]
fn commit_message_trailers_are_dimmed() {
let commit = CommitHeader::from_str(
"\
commit 1234567890abcdef1234567890abcdef12345678
Commit summary
Body text.
Assisted-by: Codex:gpt-5.6
continued trailer value
Signed-off-by: A <a@example.com>
",
)
.unwrap();
let lines = DiffViewer::preamble(Some(&commit), 80);
let color = |text| {
lines
.iter()
.flat_map(Line::labels)
.find(|label| label.content().contains(text))
.map(|label| label.paint.style().fg_color())
};
assert_eq!(color("Body text."), Some(Color::Unset));
assert_eq!(color("Assisted-by: Codex:gpt-5.6"), Some(colors::rgb::DIM));
assert_eq!(color("continued trailer value"), Some(colors::rgb::DIM));
assert_eq!(
color("Signed-off-by: A <a@example.com>"),
Some(colors::rgb::DIM)
);
}
#[test]
fn initial_next_file_navigation_selects_first_file_from_preamble() {
let document = DiffDocument::decode_str(
"\
commit 1234567890abcdef1234567890abcdef12345678
Author: A <a@example.com>
Commit summary
diff --git a/a.rs b/a.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.rs
+++ b/a.rs
@@ -1 +1 @@ fn a
-old
+new
diff --git a/b.rs b/b.rs
index 3333333333333333333333333333333333333333..4444444444444444444444444444444444444444 100644
--- a/b.rs
+++ b/b.rs
@@ -1 +1 @@ fn b
-before
+after
",
)
.unwrap();
let mut viewer = DiffViewer::new(document, DiffOptions::default());
let area = Rect::new(0, 0, 64, 6);
assert_eq!(
viewer.apply(DiffAction::FocusNext, area),
ViewChange::Changed
);
assert_eq!(viewer.focused_file(), Some(FileId::new(0)));
}
#[test]
fn next_hunk_visits_hunks_only() {
let mut viewer = two_file_viewer();
let area = Rect::new(0, 0, 64, 6);
viewer.apply(DiffAction::NextHunk, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
viewer.apply(DiffAction::NextHunk, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
}
#[test]
fn next_hunk_from_file_focus_uses_visible_position() {
let mut viewer = two_hunk_viewer();
let area = Rect::new(0, 0, 64, 5);
viewer.set_focus(Some(DiffFocus::File(FileId::new(0))));
viewer.set_scroll(7);
viewer.apply(DiffAction::NextHunk, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
assert_eq!(viewer.state().scroll.offset, 4);
}
#[test]
fn previous_hunk_from_file_focus_uses_visible_position() {
let mut viewer = two_hunk_viewer();
let area = Rect::new(0, 0, 64, 5);
viewer.set_focus(Some(DiffFocus::File(FileId::new(0))));
viewer.set_scroll(7);
viewer.apply(DiffAction::PreviousHunk, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
assert_eq!(viewer.state().scroll.offset, 4);
}
#[test]
fn scroll_clamps_after_resize() {
let mut viewer = sample_viewer();
let small = Rect::new(0, 0, 64, 3);
let large = Rect::new(0, 0, 64, 30);
viewer.apply(DiffAction::Scroll(Scroll::Bottom), small);
assert!(viewer.state().scroll.offset > 0);
viewer.apply(DiffAction::Resize, large);
assert_eq!(viewer.state().scroll.offset, 0);
}
#[test]
fn sticky_header_renders_when_scrolled_inside_file() {
let mut viewer = sample_viewer();
let area = Rect::new(0, 0, 64, 5);
viewer.apply(DiffAction::Scroll(Scroll::Lines(4)), area);
assert_eq!(
viewer.sticky_row_count(viewer.state().scroll.offset, area.rows),
3
);
}
#[test]
fn sticky_header_starts_before_header_scrolls_off() {
let mut viewer = sample_viewer();
let area = Rect::new(0, 0, 64, 5);
viewer.apply(DiffAction::Scroll(Scroll::Lines(1)), area);
assert_eq!(
viewer.sticky_start(viewer.state().scroll.offset, area.rows),
Some(0)
);
}
#[test]
fn sticky_header_replaces_scrolled_file_chrome() {
let mut viewer = sample_viewer();
let area = Rect::new(0, 0, 64, 5);
viewer.apply(DiffAction::Scroll(Scroll::Lines(3)), area);
assert_eq!(
viewer.sticky_start(viewer.state().scroll.offset, area.rows),
Some(0)
);
}
#[test]
fn sticky_header_cuts_before_next_file_card() {
let mut viewer = two_file_viewer();
let area = Rect::new(0, 0, 64, 5);
viewer.apply(DiffAction::Scroll(Scroll::Lines(8)), area);
assert_eq!(
viewer.sticky_start(viewer.state().scroll.offset, area.rows),
None
);
}
#[test]
fn sticky_header_stays_visible_until_next_file_reaches_body() {
let mut viewer = two_file_viewer();
let area = Rect::new(0, 0, 64, 5);
viewer.apply(DiffAction::Scroll(Scroll::Lines(5)), area);
assert_eq!(
viewer.sticky_start(viewer.state().scroll.offset, area.rows),
Some(0)
);
}
#[test]
fn sticky_header_stays_visible_at_file_end_boundary() {
let mut viewer = two_file_viewer();
let area = Rect::new(0, 0, 64, 5);
viewer.apply(DiffAction::Scroll(Scroll::Lines(6)), area);
assert_eq!(
viewer.sticky_start(viewer.state().scroll.offset, area.rows),
Some(0)
);
assert_eq!(
viewer.sticky_row_count(viewer.state().scroll.offset, area.rows),
2
);
}
#[test]
fn sticky_header_stays_visible_at_file_bottom() {
let mut viewer = sample_viewer();
let area = Rect::new(0, 0, 64, 5);
viewer.apply(DiffAction::Scroll(Scroll::Bottom), area);
assert_eq!(
viewer.sticky_start(viewer.state().scroll.offset, area.rows),
Some(0)
);
}
#[test]
fn oversized_hunk_navigation_shows_its_first_line() {
let target = FocusTarget {
focus: DiffFocus::Hunk(HunkId::new(0)),
row: 10,
height: 20,
file_start: 0,
};
assert_eq!(target.scroll_offset(15, 5, HunkScroll::Preserve), 7);
let fitting = FocusTarget {
height: 2,
..target
};
assert_eq!(fitting.scroll_offset(0, 5, HunkScroll::Center), 7);
}
#[test]
fn hunk_navigation_preserves_scroll_with_one_line_margin() {
let top = FocusTarget {
focus: DiffFocus::Hunk(HunkId::new(0)),
row: 11,
height: 2,
file_start: 10,
};
let bottom = FocusTarget { row: 19, ..top };
assert_eq!(top.scroll_offset(10, 12, HunkScroll::Preserve), 10);
assert_eq!(bottom.scroll_offset(10, 12, HunkScroll::Preserve), 10);
}
#[test]
fn next_hunk_preserves_scroll_with_one_line_top_margin() {
let mut viewer = two_file_viewer();
let mut tail = viewer.document.files[1].clone();
tail.id = FileId::new(2);
tail.hunks[0].id = HunkId::new(2);
viewer.document.files.push(tail);
viewer.rebuild_index();
let area = Rect::new(0, 0, 64, 16);
let targets = viewer.focus_targets(FocusFilter::HunkNavigation);
let target = targets[1];
let offset = target.file_start;
viewer.set_focus(Some(targets[0].focus));
viewer.set_scroll(offset);
viewer.apply(DiffAction::NextHunk, area);
assert_eq!(viewer.state().focus, Some(target.focus));
assert_eq!(viewer.state().scroll.offset, offset);
viewer.set_focus(None);
viewer.set_scroll(offset);
viewer.apply(DiffAction::NextHunk, area);
assert_eq!(viewer.state().focus, Some(target.focus));
assert_eq!(viewer.state().scroll.offset, offset);
}
#[test]
fn hunk_navigation_scrolls_focus_out_of_viewport_edge() {
let mut viewer = two_file_viewer();
let area = Rect::new(0, 0, 64, 5);
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
viewer.set_scroll(6);
viewer.apply(DiffAction::NextHunk, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
assert_eq!(viewer.state().scroll.offset, 9);
}
#[test]
fn keyboard_line_scroll_inputs_move_one_row() {
let area = Rect::new(0, 0, 80, 9);
let mut viewer = scroll_viewer();
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('j')), area),
Control::Redraw
);
assert_eq!(viewer.state().scroll.offset, 1);
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('j')), area),
Control::Redraw
);
assert_eq!(viewer.state().scroll.offset, 2);
assert_eq!(
viewer.handle_input(Event::Key(Key::Down), area),
Control::Redraw
);
assert_eq!(viewer.state().scroll.offset, 3);
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('k')), area),
Control::Redraw
);
assert_eq!(viewer.state().scroll.offset, 2);
assert_eq!(
viewer.handle_input(Event::Key(Key::Up), area),
Control::Redraw
);
assert_eq!(viewer.state().scroll.offset, 1);
}
#[test]
fn scroll_preserves_hunk_focus() {
let area = Rect::new(0, 0, 64, 5);
let mut viewer = two_hunk_viewer();
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
viewer.handle_input(Event::Key(Key::Char('j')), area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(0))));
assert_eq!(viewer.state().scroll.offset, 1);
}
#[test]
fn boundary_scroll_inputs_do_not_redraw() {
let area = Rect::new(0, 0, 80, 9);
let mut viewer = scroll_viewer();
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('k')), area),
Control::Continue
);
assert_eq!(viewer.state().scroll.offset, 0);
viewer.apply(DiffAction::Scroll(Scroll::Bottom), area);
let bottom = viewer.state().scroll.offset;
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('j')), area),
Control::Continue
);
assert_eq!(viewer.state().scroll.offset, bottom);
}
#[test]
fn escape_quits_when_no_file_is_focused() {
let area = Rect::new(0, 0, 100, 9);
let mut viewer = tree_viewer();
assert_eq!(
viewer.handle_input(Event::Key(Key::Esc), area),
Control::Quit
);
assert_eq!(viewer.file_tree.target(), None);
}
#[test]
fn plain_h_and_l_are_unmapped() {
let area = Rect::new(0, 0, 100, 9);
let mut viewer = tree_viewer();
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('h')), area),
Control::Continue
);
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('l')), area),
Control::Continue
);
assert_eq!(viewer.file_tree.target(), None);
}
#[test]
fn shift_j_moves_file_tree_cursor_and_jumps_to_file() {
let area = Rect::new(0, 0, 120, 4);
let mut viewer = tree_viewer();
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('J')), area),
Control::Redraw
);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::File(FileId::new(1)))
);
assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(1))));
assert_eq!(viewer.state().scroll.offset, 6);
}
#[test]
fn shift_k_moves_file_tree_cursor_to_folder_first_file() {
let area = Rect::new(0, 0, 120, 9);
let mut viewer = nested_tree_viewer();
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('K')), area),
Control::Redraw
);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::Directory(PathBuf::from("src")))
);
assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(0))));
assert_eq!(viewer.state().scroll.offset, 0);
}
#[test]
fn j_scrolls_after_file_tree_mouse_selection() {
let area = Rect::new(0, 0, 120, 4);
let mut viewer = tree_viewer();
viewer.handle_input(left_click(2, 3, Modifiers::NONE), area);
assert_eq!(viewer.state().scroll.offset, 6);
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('j')), area),
Control::Redraw
);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::File(FileId::new(1)))
);
assert_eq!(viewer.state().scroll.offset, 7);
}
#[test]
fn mouse_wheel_scroll_updates_file_tree_cursor() {
let area = Rect::new(0, 0, 120, 4);
let mut viewer = tree_viewer();
let down = Event::Mouse(Mouse::Press {
button: MouseButton::WheelDown,
at: Point::new(50, 1),
modifiers: Modifiers::NONE,
});
viewer.handle_input(down.clone(), area);
viewer.handle_input(down, area);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::File(FileId::new(1)))
);
assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(1))));
}
#[test]
fn left_click_on_file_tree_file_keeps_all_files_visible() {
let area = Rect::new(0, 0, 120, 9);
let mut viewer = tree_viewer();
let rows = viewer.index.rows;
assert_eq!(
viewer.handle_input(left_click(2, 3, Modifiers::NONE), area),
Control::Redraw
);
assert_eq!(viewer.index.rows, rows);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
}
#[test]
fn file_navigation_updates_file_tree_cursor() {
let area = Rect::new(0, 0, 120, 4);
let mut viewer = tree_viewer();
viewer.apply(DiffAction::FocusNext, area);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::File(FileId::new(0)))
);
}
#[test]
fn hunk_navigation_updates_file_tree_to_focused_file() {
let area = Rect::new(0, 0, 120, 20);
let mut viewer = tree_viewer();
viewer.apply(DiffAction::NextHunk, area);
viewer.apply(DiffAction::NextHunk, area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::File(FileId::new(1)))
);
}
#[test]
fn backtick_toggles_file_tree_visibility() {
let area = Rect::new(0, 0, 120, 9);
let mut viewer = tree_viewer();
assert!(viewer.layout(area).tree.is_some());
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('`')), area),
Control::Redraw
);
assert!(viewer.layout(area).tree.is_none());
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('`')), area),
Control::Redraw
);
assert!(viewer.layout(area).tree.is_some());
}
#[test]
fn file_tree_hides_when_dynamic_width_would_starve_diff() {
let area = Rect::new(0, 0, 100, 9);
let mut viewer = long_file_tree_viewer();
assert_eq!(
viewer.layout(area),
DiffLayout {
diff: area,
tree: None
}
);
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('`')), area),
Control::Redraw
);
assert!(viewer.layout(area).tree.is_some());
}
#[test]
fn file_tree_hides_when_source_view_would_be_too_narrow() {
let viewer = tree_viewer();
let tree_cols = viewer.file_tree.cols(usize::MAX);
let one_column_short = tree_cols + tree::GAP_COLS + tree::MIN_DIFF_COLS - 1;
let exactly_enough = tree_cols + tree::GAP_COLS + tree::MIN_DIFF_COLS;
let diff_start = tree_cols + tree::GAP_COLS;
assert_eq!(
viewer.layout(Rect::new(0, 0, one_column_short, 9)),
DiffLayout {
diff: Rect::new(0, 0, one_column_short, 9),
tree: None
}
);
assert_eq!(
viewer.layout(Rect::new(0, 0, exactly_enough, 9)),
DiffLayout {
diff: Rect::new(diff_start, 0, tree::MIN_DIFF_COLS, 9),
tree: Some(Rect::new(0, 0, tree_cols, 9))
}
);
}
#[test]
fn file_tree_resyncs_when_shown_after_hidden_scroll() {
let area = Rect::new(0, 0, 120, 4);
let mut viewer = tree_viewer();
viewer.handle_input(Event::Key(Key::Char('`')), area);
viewer.apply(DiffAction::Scroll(Scroll::Lines(6)), area);
assert_eq!(viewer.file_tree.target(), None);
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('`')), area),
Control::Redraw
);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::File(FileId::new(1)))
);
}
#[test]
fn escape_keeps_quit_behavior_when_tree_is_hidden() {
let area = Rect::new(0, 0, 80, 9);
let mut viewer = tree_viewer();
assert_eq!(
viewer.handle_input(Event::Key(Key::Esc), area),
Control::Quit
);
}
#[test]
fn shift_l_and_shift_h_collapse_and_expand_file_tree_folders() {
let area = Rect::new(0, 0, 120, 9);
let mut viewer = nested_tree_viewer();
viewer.handle_input(Event::Key(Key::Char('K')), area);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::Directory(PathBuf::from("src")))
);
viewer.handle_input(Event::Key(Key::Char('L')), area);
viewer.handle_input(Event::Key(Key::Char('J')), area);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::File(FileId::new(2)))
);
viewer.handle_input(Event::Key(Key::Char('K')), area);
viewer.handle_input(Event::Key(Key::Char('H')), area);
viewer.handle_input(Event::Key(Key::Char('J')), area);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::File(FileId::new(0)))
);
}
#[test]
fn arrow_keys_do_not_operate_file_tree_folders() {
let area = Rect::new(0, 0, 120, 9);
let mut viewer = nested_tree_viewer();
viewer.handle_input(Event::Key(Key::Char('K')), area);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::Directory(PathBuf::from("src")))
);
assert_eq!(
viewer.handle_input(Event::Key(Key::Left), area),
Control::Continue
);
assert_eq!(
viewer.handle_input(Event::Key(Key::Right), area),
Control::Continue
);
}
#[test]
fn left_click_on_file_tree_file_activates_it() {
let area = Rect::new(0, 0, 120, 9);
let mut viewer = tree_viewer();
assert_eq!(
viewer.handle_input(left_click(2, 3, Modifiers::NONE), area),
Control::Redraw
);
assert_eq!(viewer.index.rows, 12);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
}
#[test]
fn left_click_on_file_tree_file_restores_its_hunk_focus() {
let area = Rect::new(0, 0, 120, 4);
let mut viewer = tree_viewer();
let mut later = viewer.document.files[1].hunks[0].clone();
later.id = HunkId::new(2);
viewer.document.files[1].hunks.push(later);
viewer.rebuild_index();
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(2))));
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
viewer.handle_input(left_click(2, 3, Modifiers::NONE), area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(2))));
let target = viewer
.focus_targets(FocusFilter::HunkNavigation)
.into_iter()
.find(|target| target.focus == DiffFocus::Hunk(HunkId::new(2)))
.unwrap();
assert!(
(viewer.state.scroll.offset..viewer.state.scroll.offset + area.rows)
.contains(&target.row)
);
}
#[test]
fn file_tree_selection_can_anchor_final_file() {
let area = Rect::new(0, 0, 120, 9);
let mut viewer = tree_viewer();
assert_eq!(
viewer.handle_input(Event::Key(Key::Char('J')), area),
Control::Redraw
);
assert_eq!(viewer.state().focus, Some(DiffFocus::File(FileId::new(1))));
assert_eq!(viewer.state().scroll.offset, 6);
}
#[test]
fn control_left_click_on_file_tree_file_jumps_to_it() {
let area = Rect::new(0, 0, 120, 9);
let mut viewer = tree_viewer();
let rows = viewer.index.rows;
assert_eq!(
viewer.handle_input(left_click(2, 3, Modifiers::CONTROL), area),
Control::Redraw
);
assert_eq!(viewer.index.rows, rows);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
}
#[test]
fn left_click_outside_visible_file_tree_is_ignored() {
let mut viewer = tree_viewer();
assert_eq!(
viewer.handle_input(left_click(50, 1, Modifiers::NONE), Rect::new(0, 0, 120, 9)),
Control::Continue
);
assert_eq!(
viewer.handle_input(left_click(2, 1, Modifiers::NONE), Rect::new(0, 0, 80, 9)),
Control::Continue
);
assert_eq!(viewer.state().focus, None);
}
#[test]
fn left_click_on_file_tree_folder_selects_without_toggling() {
let area = Rect::new(0, 0, 120, 9);
let mut viewer = nested_tree_viewer();
assert_eq!(
viewer.handle_input(left_click(4, 2, Modifiers::NONE), area),
Control::Redraw
);
viewer.handle_input(Event::Key(Key::Char('J')), area);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::File(FileId::new(0)))
);
}
#[test]
fn selected_folder_background_is_dimmer_than_active_file_background() {
let area = Rect::new(0, 0, 120, 9);
let mut viewer = nested_tree_viewer();
let mut buffer = Buffer::empty(area);
viewer.handle_input(left_click(4, 2, Modifiers::NONE), area);
viewer.render(area, &mut buffer);
assert_eq!(
buffer.get(0, 2).map(|cell| cell.style().bg_color()),
Some(Color::Fixed(234))
);
assert_eq!(
buffer.get(0, 3).map(|cell| cell.style().bg_color()),
Some(Color::Fixed(235))
);
}
#[test]
fn left_click_can_select_parent_and_child_folders_after_folder_selection() {
let area = Rect::new(0, 0, 120, 8);
let mut viewer = deep_tree_viewer();
assert_eq!(
viewer.handle_input(left_click(6, 3, Modifiers::NONE), area),
Control::Redraw
);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::Directory(PathBuf::from("src/app")))
);
assert_eq!(
viewer.handle_input(left_click(4, 2, Modifiers::NONE), area),
Control::Redraw
);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::Directory(PathBuf::from("src")))
);
assert_eq!(
viewer.handle_input(left_click(6, 5, Modifiers::NONE), area),
Control::Redraw
);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::Directory(PathBuf::from("src/lib")))
);
}
#[test]
fn left_click_on_file_tree_disclosure_toggles_folder() {
let area = Rect::new(0, 0, 120, 9);
let mut viewer = nested_tree_viewer();
assert_eq!(
viewer.handle_input(left_click(2, 2, Modifiers::NONE), area),
Control::Redraw
);
assert_eq!(viewer.file_tree.target(), None);
viewer.handle_input(Event::Key(Key::Char('J')), area);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::File(FileId::new(2)))
);
viewer.handle_input(Event::Key(Key::Char('K')), area);
assert_eq!(
viewer.handle_input(left_click(2, 2, Modifiers::NONE), area),
Control::Redraw
);
viewer.handle_input(Event::Key(Key::Char('J')), area);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::File(FileId::new(0)))
);
}
#[test]
fn left_click_on_file_tree_disclosure_keeps_current_selection() {
let area = Rect::new(0, 0, 120, 8);
let mut viewer = nested_tree_viewer();
viewer.handle_input(left_click(4, 4, Modifiers::NONE), area);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::File(FileId::new(1)))
);
assert_eq!(
viewer.handle_input(left_click(2, 2, Modifiers::NONE), area),
Control::Redraw
);
assert_eq!(
viewer.file_tree.target(),
Some(FileTreeTarget::File(FileId::new(1)))
);
}
#[test]
fn mouse_wheel_inputs_move_three_rows() {
let area = Rect::new(0, 0, 80, 9);
let mut viewer = scroll_viewer();
let down = Event::Mouse(Mouse::Press {
button: MouseButton::WheelDown,
at: Point::new(0, 0),
modifiers: Modifiers::NONE,
});
let up = Event::Mouse(Mouse::Press {
button: MouseButton::WheelUp,
at: Point::new(0, 0),
modifiers: Modifiers::NONE,
});
viewer.handle_input(down.clone(), area);
assert_eq!(viewer.state().scroll.offset, 3);
viewer.handle_input(down, area);
assert_eq!(viewer.state().scroll.offset, 6);
viewer.handle_input(up, area);
assert_eq!(viewer.state().scroll.offset, 3);
}
#[test]
fn control_scrolls_like_vim() {
let area = Rect::new(0, 0, 80, 10);
let mut viewer = scroll_viewer();
viewer.handle_input(Event::Key(Key::Ctrl('d')), area);
assert_eq!(viewer.state().scroll.offset, 5);
viewer.handle_input(Event::Key(Key::Ctrl('u')), area);
assert_eq!(viewer.state().scroll.offset, 0);
}
#[test]
fn space_pages_down_like_less() {
let area = Rect::new(0, 0, 80, 10);
let mut viewer = scroll_viewer();
viewer.handle_input(Event::Key(Key::Char(' ')), area);
assert_eq!(viewer.state().scroll.offset, 10);
}
#[test]
fn highlight_requests_include_next_page_uncached_rows() {
let mut viewer = sample_viewer();
let area = Rect::new(0, 0, 64, 5);
let first = viewer.highlight_requests(area);
let second = viewer.highlight_requests(area);
assert_eq!(first.len(), 5);
assert!(second.is_empty());
assert_eq!(
first[0].source.line(first[0].key.source_line),
Some("context")
);
assert_eq!(first[1].source.line(first[1].key.source_line), Some("old"));
assert_eq!(first[4].source.line(first[4].key.source_line), Some("tail"));
assert_eq!(first[0].key.theme, "auto");
}
#[test]
fn visible_and_lookahead_highlight_requests_partition_combined_requests() {
let area = Rect::new(0, 0, 64, 5);
let mut combined = scroll_viewer();
let mut split = scroll_viewer();
let combined_requests = combined.highlight_requests(area);
let mut split_requests = split.visible_highlight_requests(area);
let visible_len = split_requests.len();
split_requests.extend(split.lookahead_highlight_requests(area));
assert!(visible_len > 0);
assert!(visible_len < split_requests.len());
assert_eq!(split_requests, combined_requests);
}
#[test]
fn cancelled_highlight_requests_can_be_requested_again() {
let mut viewer = sample_viewer();
let area = Rect::new(0, 0, 64, 5);
let first = viewer.highlight_requests(area);
assert!(!first.is_empty());
viewer.cancel_highlights(first.clone());
let second = viewer.highlight_requests(area);
assert_eq!(second, first);
}
#[test]
fn pending_highlight_requests_can_all_be_retried() {
let mut viewer = sample_viewer();
let area = Rect::new(0, 0, 64, 5);
let first = viewer.highlight_requests(area);
assert!(!first.is_empty());
viewer.retry_pending_highlights();
let second = viewer.highlight_requests(area);
assert_eq!(second, first);
}
#[test]
fn highlight_requests_use_hunk_side_sources() {
let mut viewer = two_hunk_viewer();
let request = viewer
.highlight_requests(Rect::new(0, 0, 64, 20))
.into_iter()
.find(|request| request.hunk == HunkId::new(1))
.unwrap();
assert_eq!(request.source.head, 10);
assert_eq!(request.source.text.as_ref(), "keep\nafter");
assert_eq!(request.source.line(10), Some("keep"));
assert_eq!(request.source.line(11), Some("after"));
assert_eq!(request.source.line(12), None);
}
#[cfg(feature = "builtins")]
#[test]
fn repo_highlight_results_style_css_custom_properties_from_real_context() {
let document = DiffDocument::decode_str(
"\
diff --git a/assets/css/style.css b/assets/css/style.css
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/assets/css/style.css
+++ b/assets/css/style.css
@@ -12,7 +12,8 @@
--color-foreground: #112;
--color-headers: #222;
--color-background: #d3d1d1;
- --color-background-light: #dedddd;
+ --color-background-light: #dad8d8;
+ --color-background-dark: #cecccc;
--color-dim: #334;
--color-dimmer: #666;
--color-subtle: #888;
",
)
.unwrap();
let mut viewer = DiffViewer::new(document, DiffOptions::default());
let full = DiffDocument::decode_str(
"\
diff --git a/assets/css/style.css b/assets/css/style.css
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/assets/css/style.css
+++ b/assets/css/style.css
@@ -1,19 +1,20 @@
html {
box-sizing: border-box;
}
*, *::before, *::after {
box-sizing: inherit;
}
body {
margin: 0;
}
:root {
color-scheme: light;
--color-foreground: #112;
--color-headers: #222;
--color-background: #d3d1d1;
- --color-background-light: #dedddd;
+ --color-background-light: #dad8d8;
+ --color-background-dark: #cecccc;
--color-dim: #334;
--color-dimmer: #666;
--color-subtle: #888;
}
",
)
.unwrap();
let mut registry = syntax::Registry::default();
registry.add_theme(
syntax::Theme::parse(include_str!("themes/rustik-catppuccin-mocha.json")).unwrap(),
);
registry.add_grammar(syntax::Grammar::from_str(syntax::syntaxes::CSS).unwrap());
let mut highlighter = crate::BuiltinHighlighter::new(registry, "rustik-catppuccin-mocha");
let source = full.files[0].highlight_source(DiffSide::New).unwrap();
let mut requests = viewer.highlight_requests(Rect::new(0, 0, 80, 20));
for request in &mut requests {
if request.key.side == DiffSide::New {
request.source = source.clone();
}
}
let result = highlighter
.highlight_requests(requests)
.into_iter()
.find(|result| {
result.key.text_hash == {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
" --color-background-light: #dad8d8;".hash(&mut hasher);
hasher.finish()
}
})
.unwrap();
let color = Color::RGB(137, 180, 250);
let variable = result
.line
.labels()
.iter()
.find(|label| label.content().contains("--color-background-light"))
.unwrap();
assert_eq!(variable.paint.style().fg_color(), color);
}
#[test]
fn metadata_lookup_matches_rendered_diff_rows() {
let viewer = sample_viewer();
for row in 0..viewer.index.rows {
assert_eq!(
viewer.diff_meta_at(row),
viewer.render_row(row, 64).and_then(|row| row.diff)
);
}
}
#[test]
fn highlight_results_replace_pending_with_cached_lines() {
let mut viewer = sample_viewer();
let area = Rect::new(0, 0, 64, 5);
let request = viewer.highlight_requests(area).into_iter().next().unwrap();
let fresh = HighlightResult::new(request, Line::new(Label::new("fresh").fg(Color::Red)));
assert!(viewer.apply_highlights([fresh]));
assert_eq!(viewer.highlights.len(), 1);
}
#[test]
fn empty_highlight_result_does_not_replace_nonempty_source() {
let mut viewer = sample_viewer();
let area = Rect::new(0, 0, 64, 5);
let request = viewer
.highlight_requests(area)
.into_iter()
.find(|request| {
viewer
.document
.files
.iter()
.flat_map(|file| file.hunks.iter().flat_map(|hunk| hunk.lines.iter()))
.any(|line| line.id == request.row && !line.text.is_empty())
})
.unwrap();
let key = request.key.clone();
let empty = HighlightResult::new(request, Line::blank());
assert!(!viewer.apply_highlights([empty]));
assert!(!viewer.highlights.contains_key(&key));
}
#[test]
fn for_hunks_highlight_requests_use_hunk_side_sources() {
let full = DiffDocument::decode_str(
"\
diff --git a/first.rs b/first.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/first.rs
+++ b/first.rs
@@ -1 +1 @@
-old
+new
diff --git a/second.rs b/second.rs
index 3333333333333333333333333333333333333333..4444444444444444444444444444444444444444 100644
--- a/second.rs
+++ b/second.rs
@@ -10,3 +10,3 @@
keep
-before
+after
tail
",
)
.unwrap();
let file = &full.files[1];
let single = DiffDocument::for_hunks(file, [file.hunks[0].clone()]);
let mut viewer = DiffViewer::new(single, DiffOptions::default());
let requests = viewer.highlight_requests(Rect::new(0, 0, 64, 20));
assert_eq!(requests.len(), 4);
for request in &requests {
let side_text = match request.key.side {
DiffSide::Old => "keep\nbefore\ntail",
DiffSide::New => "keep\nafter\ntail",
};
assert_eq!(request.source.head, 10);
assert_eq!(request.source.text.as_ref(), side_text);
}
}
#[test]
fn single_hunk_viewer_highlights_each_visible_source_row() {
let full = DiffDocument::decode_str(
"\
diff --git a/a.rs b/a.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.rs
+++ b/a.rs
@@ -1 +1,5 @@
-old
+fn main() {
+ let value = true;
+ if value {
+ return;
+ }
",
)
.unwrap();
let single = DiffDocument::for_hunks(&full.files[0], [full.files[0].hunks[0].clone()]);
let mut viewer = DiffViewer::new(single.clone(), DiffOptions::default());
let mut highlighter = crate::Builtins::highlighter(&single).unwrap();
assert!(viewer.apply_visible_highlights(Rect::new(0, 0, 80, 20), &mut highlighter));
let rendered = (0..viewer.index.rows)
.filter_map(|row| viewer.render_row(row, 80))
.map(|row| row.line)
.collect::<Vec<_>>();
for token in ["fn", "let", "if", "return"] {
assert!(
rendered.iter().any(|line| {
line.labels().iter().any(|label| {
label.content() == token && label.paint.style().fg_color() != Color::Unset
})
}),
"missing highlighted token {token}: {rendered:#?}"
);
}
}
#[test]
fn apply_visible_highlights_runs_one_visible_batch() {
let mut viewer = sample_viewer();
let area = Rect::new(0, 0, 64, 5);
let mut highlighter = RecordingHighlighter::default();
assert!(viewer.apply_visible_highlights(area, &mut highlighter));
assert_eq!(highlighter.batches, 1);
assert_eq!(viewer.highlights.len(), 5);
assert!(!viewer.apply_visible_highlights(area, &mut highlighter));
assert_eq!(highlighter.batches, 1);
}
#[test]
fn apply_highlights_populates_word_diff_cache() {
let mut viewer = word_diff_viewer();
let area = Rect::new(0, 0, 80, 20);
let request = viewer.highlight_requests(area).into_iter().next().unwrap();
let hunk_id = request.hunk;
let result = HighlightResult::new(request, Line::new("highlighted"));
viewer.apply_highlights([result]);
let changes = viewer.word_diffs.get(&hunk_id).unwrap();
let added = viewer.document.files[0].hunks[0]
.lines
.iter()
.find(|line| line.kind == DiffLineKind::Addition)
.unwrap()
.id;
assert!(
changes.get(&added).is_some_and(|ranges| !ranges.is_empty()),
"expected new-side row to have changed ranges"
);
}
#[test]
fn apply_highlights_bakes_word_diff_overlay_into_cache() {
let mut viewer = word_diff_viewer();
let area = Rect::new(0, 0, 80, 20);
let request = viewer
.highlight_requests(area)
.into_iter()
.find(|request| request.key.side == DiffSide::New)
.unwrap();
let key = request.key.clone();
let plain_text = viewer
.document
.files
.iter()
.flat_map(|file| file.hunks.iter().flat_map(|hunk| hunk.lines.iter()))
.find(|line| line.id == request.row)
.unwrap()
.text
.clone();
let result = HighlightResult::new(request, Line::new(Label::new(plain_text.as_str())));
assert!(viewer.apply_highlights([result]));
let cached = viewer.highlights.get(&key).unwrap();
let bright = viewer.options.diff_palette.positive_word_bg;
assert!(
cached
.labels()
.iter()
.any(|label| label.paint.style.bg_color() == bright),
"expected the cached line to already include the bright word-diff bg"
);
}
fn word_diff_viewer() -> DiffViewer {
let document = DiffDocument::decode_str(
"\
diff --git a/a.rs b/a.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.rs
+++ b/a.rs
@@ -1 +1 @@
-fn render(view: &View) {
+fn render(view: &mut View, opts: Options) {
",
)
.unwrap();
DiffViewer::new(document, DiffOptions::default())
}
struct FakeRepo {
patch: Vec<u8>,
calls: std::cell::RefCell<Vec<(usize, Vec<PathBuf>)>>,
}
impl FakeRepo {
fn new(patch: &str) -> Self {
Self {
patch: patch.as_bytes().to_vec(),
calls: std::cell::RefCell::new(Vec::new()),
}
}
}
impl DiffRepository for FakeRepo {
fn diff(
&self,
context_lines: usize,
paths: &[&std::path::Path],
) -> Result<Vec<u8>, RepoError> {
let paths = paths.iter().map(|path| path.to_path_buf()).collect();
self.calls.borrow_mut().push((context_lines, paths));
Ok(self.patch.clone())
}
}
#[test]
fn full_file_state_belongs_to_the_viewer_context() {
let area = Rect::new(0, 0, 64, 9);
let patch = "\
diff --git a/a.rs b/a.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.rs
+++ b/a.rs
@@ -1,3 +1,4 @@ fn main
context
-old
+new
+extra
tail
";
let mut viewers = [sample_viewer(), sample_viewer()];
let update = viewers[0]
.context_request(ContextChange::ToggleFile)
.unwrap()
.decode(patch.as_bytes())
.unwrap()
.unwrap();
viewers[0].apply_context_update(update, area);
assert!(viewers[0].is_full_file());
assert!(!viewers[1].is_full_file());
let update = viewers[1]
.context_request(ContextChange::ToggleFile)
.unwrap()
.decode(patch.as_bytes())
.unwrap()
.unwrap();
viewers[1].apply_context_update(update, area);
assert!(viewers[1].is_full_file());
let mut pathless = sample_viewer();
pathless.document.files[0].header.old_path = None;
pathless.document.files[0].header.new_path = None;
assert!(
pathless
.context_request(ContextChange::ToggleFile)
.is_none()
);
assert!(!pathless.is_full_file());
}
#[test]
fn async_context_request_decodes_and_applies_update() {
let mut viewer = sample_viewer();
viewer.options.hunk_focus = HunkFocus::DimUnfocused;
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
let area = Rect::new(0, 0, 64, 9);
let repo = FakeRepo::new(
"\
diff --git a/a.rs b/a.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.rs
+++ b/a.rs
@@ -1,5 +1,6 @@ fn main
lead
context
-old
+new
+extra
tail
trail
",
);
let request = viewer.context_request(ContextChange::Increase).unwrap();
let paths = request.paths().collect::<Vec<_>>();
let patch = repo.diff(request.context_lines(), &paths).unwrap();
drop(paths);
let update = request.decode(&patch).unwrap().unwrap();
viewer.apply_context_update(update, area);
let calls = repo.calls.borrow();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].0, 4);
assert_eq!(calls[0].1, vec![PathBuf::from("a.rs")]);
assert_eq!(viewer.document.files[0].hunks[0].header.old_size, 5);
let expanded = viewer.render_row(HUNK_BODY_START, 64).unwrap().line;
let changed = viewer.render_row(HUNK_BODY_START + 2, 64).unwrap().line;
assert!(format!("{}", expanded.styled()).contains("\x1b[2m"));
assert!(!format!("{}", changed.styled()).contains("\x1b[2m"));
}
#[test]
fn context_update_keeps_focused_hunk_at_its_screen_row() {
let mut viewer = two_hunk_viewer();
let area = Rect::new(0, 0, 64, 4);
let focus = DiffFocus::Hunk(HunkId::new(1));
viewer.set_focus(Some(focus));
viewer.set_scroll(5);
let old_row = viewer
.focus_targets(FocusFilter::HunkNavigation)
.into_iter()
.find(|target| target.focus == focus)
.unwrap()
.row
- viewer.state.scroll.offset;
let request = viewer.context_request(ContextChange::Increase).unwrap();
let update = request
.decode(include_bytes!("../tests/golden/expanded_context.diff"))
.unwrap()
.unwrap();
viewer.apply_context_update(update, area);
let new_row = viewer
.focus_targets(FocusFilter::HunkNavigation)
.into_iter()
.find(|target| target.focus == focus)
.unwrap()
.row
- viewer.state.scroll.offset;
assert_eq!(new_row, old_row);
}
#[test]
fn file_replacement_keeps_focused_hunk_at_its_screen_row() {
let mut viewer = two_hunk_viewer();
let area = Rect::new(0, 0, 64, 4);
let focus = DiffFocus::Hunk(HunkId::new(1));
viewer.set_focus(Some(focus));
viewer.set_scroll(5);
let old_row = viewer
.focus_targets(FocusFilter::HunkNavigation)
.into_iter()
.find(|target| target.focus == focus)
.unwrap()
.row
- viewer.state.scroll.offset;
let mut file = viewer.document.files[0].clone();
file.hunks.remove(0);
viewer.replace_file_diffs_anchored([file], area);
let new_row = viewer
.focus_targets(FocusFilter::HunkNavigation)
.into_iter()
.find(|target| target.focus == focus)
.unwrap()
.row
- viewer.state.scroll.offset;
assert_eq!(new_row, old_row);
}
#[test]
fn file_replacement_selects_hunk_before_removed_last_hunk() {
let mut viewer = two_hunk_viewer();
let area = Rect::new(0, 0, 64, 20);
let mut third = viewer.document.files[0].hunks[1].clone();
third.id = HunkId::new(2);
viewer.document.files[0].hunks.push(third);
viewer.rebuild_index();
viewer.set_scroll(100);
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(2))));
let mut file = viewer.document.files[0].clone();
file.hunks.remove(2);
viewer.replace_file_diffs_anchored([file], area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Hunk(HunkId::new(1))));
}
#[test]
fn file_replacement_skips_hidden_hunk_predecessors() {
let mut viewer = commit_viewer();
let area = Rect::new(0, 0, 64, 20);
let mut third = viewer.document.files[0].hunks[1].clone();
third.id = HunkId::new(2);
viewer.document.files[0].hunks.push(third);
viewer.rebuild_index();
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(2))));
let mut file = viewer.document.files[0].clone();
file.hunks.clear();
viewer.replace_file_diffs_anchored([file], area);
assert_eq!(viewer.state().focus, Some(DiffFocus::Commit));
}
#[test]
fn context_request_targets_focused_file() {
let mut viewer = two_file_viewer();
viewer.set_focus(Some(DiffFocus::File(FileId::new(1))));
let repo = FakeRepo::new(
"\
diff --git a/a.rs b/a.rs
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.rs
+++ b/a.rs
@@ -1,3 +1,4 @@ fn a
context
-old
+new
+extra
tail
diff --git a/b.rs b/b.rs
index 3333333333333333333333333333333333333333..4444444444444444444444444444444444444444 100644
--- a/b.rs
+++ b/b.rs
@@ -1,3 +1,3 @@ fn b
keep
-before
+after
trail
",
);
let request = viewer.context_request(ContextChange::Increase).unwrap();
let paths = request.paths().collect::<Vec<_>>();
let patch = repo.diff(request.context_lines(), &paths).unwrap();
drop(paths);
let update = request.decode(&patch).unwrap().unwrap();
viewer.apply_context_update(update, Rect::new(0, 0, 64, 20));
let calls = repo.calls.borrow();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].1, vec![PathBuf::from("b.rs")]);
}
#[derive(Clone, Debug, Default)]
struct TestDecorator;
impl DiffDecorator for TestDecorator {
fn file(&self, _file: FileId) -> FileDecoration {
FileDecoration {
status: Some(rustik_tui::Paint::new('✔')),
annotations: vec![Line::new("2 c")],
progress: None,
stats: None,
}
}
fn hunk(&self, _file: FileId, _hunk: HunkId) -> HunkDecoration {
HunkDecoration {
gutter: Some(tui::Paint::new('▏').fg(colors::rgb::GREEN)),
corner: Line::new("◆"),
style: Some(Style::default().bg(Color::Fixed(99))),
}
}
}
#[test]
fn hunk_decoration_does_not_change_size() {
let constraints = Constraint::tight(80);
let plain = sample_viewer().size(constraints);
let mut decorated = sample_viewer();
decorated.set_decorator(TestDecorator);
assert_eq!(decorated.size(constraints), plain);
}
#[test]
fn hunk_gutter_draws_beside_changed_rows_only() {
let area = Rect::new(0, 0, 80, 12);
let mut viewer = sample_viewer();
viewer.set_decorator(TestDecorator);
let mut buffer = Buffer::empty(area);
viewer.render(area, &mut buffer);
for row in [
HUNK_BODY_START + 1,
HUNK_BODY_START + 2,
HUNK_BODY_START + 3,
] {
let gutter = buffer.get(2, row).unwrap();
assert_eq!(gutter.glyph(), "▏");
assert_eq!(gutter.style().fg_color(), colors::rgb::GREEN);
}
for row in [HUNK_BODY_START, HUNK_BODY_START + 4] {
assert_eq!(buffer.get(2, row).unwrap().glyph(), " ");
}
}
#[test]
fn file_decoration_renders_status_and_annotation_in_header() {
let area = Rect::new(0, 0, 80, 12);
let mut viewer = sample_viewer();
viewer.set_decorator(TestDecorator);
let mut buffer = Buffer::empty(area);
viewer.render(area, &mut buffer);
let header = buffer.line(1);
assert!(header.contains('✔'), "header: {header:?}");
assert!(header.contains("2 c"), "header: {header:?}");
assert!(header.contains("2 c ·"), "header: {header:?}");
}
#[test]
fn file_header_uses_file_kind_marker() {
let area = Rect::new(0, 0, 80, 12);
let document = sample_viewer().document().clone();
let mut viewer = DiffViewer::new(document, DiffOptions::default());
let mut buffer = Buffer::empty(area);
viewer.render(area, &mut buffer);
let header = buffer.line(1);
assert!(header.contains('⊙'), "header: {header:?}");
}
#[test]
fn file_header_prefers_decoration_status() {
let area = Rect::new(0, 0, 80, 12);
let document = sample_viewer().document().clone();
let mut viewer = DiffViewer::new(document, DiffOptions::default());
viewer.set_decorator(TestDecorator);
let mut buffer = Buffer::empty(area);
viewer.render(area, &mut buffer);
let header = buffer.line(1);
assert!(header.contains('✔'), "header: {header:?}");
assert!(!header.contains('⊙'), "header: {header:?}");
}
#[test]
fn file_decoration_renders_status_in_file_tree() {
let area = Rect::new(0, 0, 100, 12);
let mut viewer = tree_viewer();
viewer.set_decorator(TestDecorator);
let mut buffer = Buffer::empty(area);
viewer.render(area, &mut buffer);
let tree = (0..area.rows)
.map(|row| buffer.line(row).chars().take(28).collect::<String>())
.collect::<Vec<_>>()
.join("\n");
assert!(tree.contains('✔'), "tree: {tree:?}");
}
#[test]
fn hunk_decoration_renders_corner_on_first_body_row_only() {
let area = Rect::new(0, 0, 80, 12);
let mut viewer = sample_viewer();
viewer.set_decorator(TestDecorator);
let mut buffer = Buffer::empty(area);
viewer.render(area, &mut buffer);
let first_body = HUNK_BODY_START;
let column = (0..area.cols).find(|&x| {
buffer
.get(x, first_body)
.is_some_and(|cell| cell.glyph() == "◆")
});
assert!(column.is_some(), "row: {:?}", buffer.line(first_body));
assert!(
column.unwrap() >= area.cols / 2,
"corner column: {column:?}"
);
assert!(!buffer.line(first_body + 1).contains('◆'));
}
#[test]
fn hunk_decoration_style_composes_onto_body_rows() {
let area = Rect::new(0, 0, 80, 12);
let mut viewer = sample_viewer();
viewer.set_decorator(TestDecorator);
let mut buffer = Buffer::empty(area);
viewer.render(area, &mut buffer);
let first_body = HUNK_BODY_START;
let decorated = (0..area.cols)
.filter(|&x| {
buffer
.get(x, first_body)
.is_some_and(|cell| cell.style().bg_color() == Color::Fixed(99))
})
.count();
assert!(decorated > 0, "row: {:?}", buffer.line(first_body));
let mut plain = sample_viewer();
let mut plain_buffer = Buffer::empty(area);
plain.render(area, &mut plain_buffer);
assert!((0..area.cols).all(|x| {
plain_buffer
.get(x, first_body)
.is_none_or(|cell| cell.style().bg_color() != Color::Fixed(99))
}));
}
#[test]
fn selected_hunk_ignores_inactive_decoration_style() {
let area = Rect::new(0, 0, 80, 12);
let mut viewer = sample_viewer();
viewer.set_decorator(TestDecorator);
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
let mut buffer = Buffer::empty(area);
viewer.render(area, &mut buffer);
assert!((0..area.cols).all(|x| {
buffer
.get(x, HUNK_BODY_START)
.is_none_or(|cell| cell.style().bg_color() != Color::Fixed(99))
}));
assert_eq!(buffer.get(2, HUNK_BODY_START + 1).unwrap().glyph(), "▏");
}
#[test]
fn hunk_focus_dims_other_hunk_source_without_replacing_foreground() {
let document = two_hunk_viewer().document().clone();
let mut viewer = DiffViewer::new(
document,
DiffOptions {
hunk_focus: HunkFocus::DimUnfocused,
..DiffOptions::default()
},
);
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
let focused = viewer.render_row(3, 64).unwrap().line;
let muted = viewer.render_row(7, 64).unwrap().line;
let muted_deletion = viewer.render_row(8, 64).unwrap().line;
let muted_addition = viewer.render_row(9, 64).unwrap().line;
let focused_number = focused
.labels()
.iter()
.find(|label| label.content().contains('1'))
.unwrap();
let focused_source = focused
.labels()
.iter()
.find(|label| label.content().contains("keep"))
.unwrap();
let muted_source = muted
.labels()
.iter()
.find(|label| label.content().contains("keep"))
.unwrap();
let muted_deletion_source = muted_deletion
.labels()
.iter()
.find(|label| label.content().contains("before"))
.unwrap();
let muted_addition_source = muted_addition
.labels()
.iter()
.find(|label| label.content().contains("after"))
.unwrap();
assert_eq!(
focused_number.paint.style().fg_color(),
SELECTED_LINE_NUMBER_FG
);
assert_eq!(focused_source.paint.style().fg_color(), Color::Unset);
assert_eq!(muted_source.paint.style().fg_color(), Color::Unset);
assert_eq!(
muted_deletion_source.background(),
DiffViewer::muted_background(viewer.options.diff_palette.negative_row_bg)
);
assert_eq!(
muted_addition_source.background(),
DiffViewer::muted_background(viewer.options.diff_palette.positive_row_bg)
);
assert!(format!("{}", muted.styled()).contains("\x1b[2m"));
}
#[test]
fn hunk_focus_requests_unfocused_highlights() {
let document = two_hunk_viewer().document().clone();
let mut viewer = DiffViewer::new(
document,
DiffOptions {
hunk_focus: HunkFocus::DimUnfocused,
..DiffOptions::default()
},
);
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
let requests = viewer.highlight_requests(Rect::new(0, 0, 64, 20));
assert!(!requests.is_empty());
assert!(
requests
.iter()
.any(|request| request.hunk == HunkId::new(0))
);
assert!(
requests
.iter()
.any(|request| request.hunk == HunkId::new(1))
);
}
#[test]
fn hunk_focus_uses_cached_unfocused_highlights() {
let document = two_hunk_viewer().document().clone();
let mut viewer = DiffViewer::new(
document,
DiffOptions {
hunk_focus: HunkFocus::DimUnfocused,
..DiffOptions::default()
},
);
let mut highlighted = two_hunk_viewer();
let results: Vec<_> = highlighted
.highlight_requests(Rect::new(0, 0, 64, 20))
.into_iter()
.map(|request| HighlightResult::new(request, Line::new("highlighted")))
.collect();
viewer.apply_highlights(results);
viewer.set_focus(Some(DiffFocus::Hunk(HunkId::new(0))));
let focused = viewer.render_row(3, 64).unwrap().line;
let muted = viewer.render_row(7, 64).unwrap().line;
assert!(focused.to_string().contains("highlighted"));
assert!(muted.to_string().contains("highlighted"));
assert!(format!("{}", muted.styled()).contains("\x1b[2m"));
}
fn mid_file_viewer() -> DiffViewer {
let document = DiffDocument::decode_str(concat!(
"diff --git a/a.rs b/a.rs\n",
"index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644\n",
"--- a/a.rs\n",
"+++ b/a.rs\n",
"@@ -3,1 +3,1 @@\n",
"-old\n",
"+new\n",
))
.unwrap();
DiffViewer::new(document, DiffOptions::default())
}
#[test]
fn highlight_sources_span_the_whole_blob() {
let mut viewer = mid_file_viewer();
viewer
.load_file_sources(|_| Ok::<_, Infallible>(b"fn f() {\nbody\nnew\n}\n".to_vec()))
.unwrap();
let request = viewer
.highlight_requests(Rect::new(0, 0, 64, 20))
.into_iter()
.find(|request| request.key.side == DiffSide::New)
.unwrap();
assert_eq!(request.source.head, 1);
assert_eq!(request.source.line(1), Some("fn f() {"));
assert_eq!(request.source.line(3), Some("new"));
}
#[test]
fn file_sources_skip_null_blob_ids() {
let document = DiffDocument::decode_str(concat!(
"diff --git a/new.rs b/new.rs\n",
"new file mode 100644\n",
"index 0000000000000000000000000000000000000000..1111111111111111111111111111111111111111\n",
"--- /dev/null\n",
"+++ b/new.rs\n",
"@@ -0,0 +1 @@\n",
"+new\n",
))
.unwrap();
let mut viewer = DiffViewer::new(document, DiffOptions::default());
let mut loaded = Vec::new();
viewer
.load_file_sources(|oid| {
loaded.push(oid);
Ok::<_, Infallible>(b"new\n".to_vec())
})
.unwrap();
assert_eq!(loaded.len(), 1);
assert!(!loaded[0].is_zero());
}
#[test]
fn each_side_highlights_against_its_own_blob() {
let mut viewer = mid_file_viewer();
let old_oid = viewer.document.files[0].header.old_oid.unwrap();
viewer
.load_file_sources(|oid| {
let text: &[u8] = if oid == old_oid {
b"one\ntwo\nold\n"
} else {
b"one\ntwo\nnew\n"
};
Ok::<_, Infallible>(text.to_vec())
})
.unwrap();
let requests = viewer.highlight_requests(Rect::new(0, 0, 64, 20));
let source = |side| {
requests
.iter()
.find(|request| request.key.side == side)
.map(|request| request.source.text.to_string())
};
assert_eq!(source(DiffSide::Old).as_deref(), Some("one\ntwo\nold\n"));
assert_eq!(source(DiffSide::New).as_deref(), Some("one\ntwo\nnew\n"));
}
#[test]
fn loaded_sources_survive_replacing_file_diffs() {
let mut viewer = mid_file_viewer();
viewer
.load_file_sources(|_| Ok::<_, Infallible>(b"one\ntwo\nnew\n".to_vec()))
.unwrap();
let files = viewer.document.files.clone();
viewer.replace_file_diffs(files);
let request = viewer
.highlight_requests(Rect::new(0, 0, 64, 20))
.into_iter()
.find(|request| request.key.side == DiffSide::New)
.unwrap();
assert_eq!(request.source.head, 1);
}
#[test]
fn sources_that_disagree_with_the_diff_are_rejected() {
let mut viewer = mid_file_viewer();
viewer
.load_file_sources(|_| Ok::<_, Infallible>(b"one\ntwo\ndrifted\n".to_vec()))
.unwrap();
let request = viewer
.highlight_requests(Rect::new(0, 0, 64, 20))
.into_iter()
.find(|request| request.key.side == DiffSide::New)
.unwrap();
assert_eq!(request.source.head, 3);
assert_eq!(request.source.line(3), Some("new"));
}
#[test]
fn sources_past_the_total_budget_are_not_retained() {
let mut viewer = mid_file_viewer();
viewer.source_bytes = MAX_TOTAL_SOURCE_BYTES;
viewer
.load_file_sources(|_| Ok::<_, Infallible>(b"one\ntwo\nnew\n".to_vec()))
.unwrap();
let request = viewer
.highlight_requests(Rect::new(0, 0, 64, 20))
.into_iter()
.find(|request| request.key.side == DiffSide::New)
.unwrap();
assert!(viewer.blob_sources.is_empty());
assert_eq!(request.source.head, 3);
}
#[cfg(unix)]
#[test]
fn worktree_sources_are_bounded_and_confined_to_the_root() {
use std::os::unix::fs::symlink;
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let base = std::env::temp_dir().join(format!(
"rustik-diff-worktree-{}-{nonce}",
std::process::id()
));
let root = base.join("root");
fs::create_dir_all(&root).unwrap();
fs::write(base.join("outside"), "outside\n").unwrap();
fs::write(root.join("target"), "one\ntwo\n").unwrap();
fs::write(root.join("large"), vec![b'x'; MAX_SOURCE_BYTES + 1]).unwrap();
symlink("target", root.join("link")).unwrap();
let root = root.canonicalize().unwrap();
assert!(
LoadedBlob::read_worktree(&root, Path::new("../outside"), FileMode::Blob).is_none()
);
assert!(LoadedBlob::read_worktree(&root, &root.join("target"), FileMode::Blob).is_none());
assert!(LoadedBlob::read_worktree(&root, Path::new("large"), FileMode::Blob).is_none());
assert!(LoadedBlob::read_worktree(&root, Path::new("link"), FileMode::Blob).is_none());
let link = LoadedBlob::read_worktree(&root, Path::new("link"), FileMode::Link).unwrap();
assert_eq!(link.loc, 1);
assert_eq!(link.source.unwrap().line(1), Some("target"));
fs::remove_dir_all(base).unwrap();
}
#[test]
fn hunk_sources_are_used_when_no_blob_is_loaded() {
let mut viewer = mid_file_viewer();
let request = viewer
.highlight_requests(Rect::new(0, 0, 64, 20))
.into_iter()
.find(|request| request.key.side == DiffSide::New)
.unwrap();
assert_eq!(request.source.head, 3);
assert_eq!(request.source.line(3), Some("new"));
}
struct ContextCase {
syntax: &'static str,
grammar: &'static str,
blob: &'static str,
line: u32,
needle: &'static str,
}
impl ContextCase {
fn row_color(&self, load_blob: bool) -> Option<Color> {
let old = self.line;
let body = self.blob.lines().nth(self.line as usize - 1).unwrap();
let document = DiffDocument::decode_str(&format!(
"diff --git a/a b/a\n\
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644\n\
--- a/a\n\
+++ b/a\n\
@@ -{old},1 +{old},1 @@\n\
-placeholder\n\
+{body}\n"
))
.unwrap();
let options = DiffOptions {
syntax: Some(self.syntax.to_owned()),
..DiffOptions::default()
};
let mut viewer = DiffViewer::new(document, options);
if load_blob {
viewer
.load_file_sources(|_| Ok::<_, Infallible>(self.blob.as_bytes().to_vec()))
.unwrap();
}
let mut registry = syntax::Registry::default();
registry.add_theme(
syntax::Theme::parse(include_str!("themes/rustik-catppuccin-mocha.json")).unwrap(),
);
registry.add_grammar(syntax::Grammar::from_str(self.grammar).unwrap());
let mut highlighter =
crate::BuiltinHighlighter::new(registry, "rustik-catppuccin-mocha");
let requests = viewer
.highlight_requests(Rect::new(0, 0, 80, 20))
.into_iter()
.filter(|request| request.key.side == DiffSide::New)
.collect::<Vec<_>>();
highlighter
.highlight_requests(requests)
.into_iter()
.flat_map(|result| result.line.labels().to_vec())
.find(|label| label.content().contains(self.needle))
.map(|label| label.paint.style().fg_color())
}
}
#[test]
fn whole_file_context_highlights_a_row_inside_a_block_comment() {
let case = ContextCase {
syntax: "rust",
grammar: syntax::syntaxes::RUST,
blob: "/*\ncommented\n*/\n",
line: 2,
needle: "commented",
};
let comment = Color::RGB(147, 153, 178);
assert_eq!(case.row_color(true), Some(comment));
assert_ne!(case.row_color(false), Some(comment));
}
#[test]
fn whole_file_context_highlights_a_row_inside_a_heredoc() {
let case = ContextCase {
syntax: "shell",
grammar: syntax::syntaxes::SHELL,
blob: "cat <<EOF\nprintf is literal text here\nEOF\n",
line: 2,
needle: "printf",
};
let string = Color::RGB(166, 227, 161);
assert_eq!(case.row_color(true), Some(string));
assert_ne!(case.row_color(false), Some(string));
}
#[test]
fn oversized_blobs_fall_back_to_hunk_sources() {
let mut viewer = mid_file_viewer();
viewer
.load_file_sources(|_| Ok::<_, Infallible>(vec![b'x'; MAX_SOURCE_BYTES + 1]))
.unwrap();
let request = viewer
.highlight_requests(Rect::new(0, 0, 64, 20))
.into_iter()
.find(|request| request.key.side == DiffSide::New)
.unwrap();
assert_eq!(request.source.head, 3);
}
}