use std::{iter, ops::Range};
use ansi_to_tui::IntoText;
use anyhow::{Context, Result, anyhow};
use ratatui::{
Frame,
layout::{Constraint, Layout, Rect},
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Block, Paragraph},
};
use jj_compose_core::{FileDiff, HunkId, Jj, Patch, Target, patch};
const TAB_WIDTH: usize = 4;
pub fn load(jj: &Jj, target: &Target) -> Result<DiffView> {
let stdout = jj.git_diff(target).map_err(|e| anyhow!("{e}"))?;
let empty = format!("(no changes in {})", target.change_id);
DiffView::from_output(&stdout, &empty)
}
pub struct FileEntry {
pub path: String,
pub added: usize,
pub removed: usize,
pub row: usize,
}
fn expand_tabs(bytes: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(bytes.len());
let mut column = 0;
let mut in_escape = false;
for &b in bytes {
match b {
b'\t' => {
let spaces = TAB_WIDTH - column % TAB_WIDTH;
out.extend(iter::repeat_n(b' ', spaces));
column += spaces;
continue;
}
b'\n' => column = 0,
0x1b => in_escape = true,
b'm' if in_escape => in_escape = false,
_ if !in_escape && b & 0xC0 != 0x80 => column += 1,
_ => {}
}
out.push(b);
}
out
}
#[derive(Debug, Clone)]
pub struct HunkEntry {
pub id: HunkId,
pub path: String,
pub rows: Range<usize>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mark {
Context,
Line {
commit: Option<u8>,
cursor: bool,
selected: bool,
},
}
impl Mark {
const fn is_cursor(self) -> bool {
matches!(self, Self::Line { cursor: true, .. })
}
fn apply(self, mut line: Line<'static>) -> Line<'static> {
let Self::Line {
commit,
cursor,
selected,
} = self
else {
for span in &mut line.spans {
span.style = span.style.patch(Style::new().add_modifier(Modifier::DIM));
}
return line;
};
let mut style = commit.map_or_else(
|| {
Style::new()
.add_modifier(Modifier::DIM)
.add_modifier(Modifier::CROSSED_OUT)
},
|n| Style::new().fg(crate::app::ui::box_color(n)),
);
if selected {
style = style.bg(Color::Indexed(238));
}
if cursor {
style = style.add_modifier(Modifier::REVERSED);
}
for span in &mut line.spans {
span.style = span.style.patch(style);
}
line
}
}
pub struct DiffView {
rows: Vec<Line<'static>>,
files: Vec<FileEntry>,
hunks: Vec<HunkEntry>,
patch: Patch,
scroll: usize,
pan: u16,
height: usize,
show_files: bool,
search: Option<Search>,
}
struct Search {
query: String,
rows: Vec<usize>,
current: usize,
}
impl DiffView {
pub fn from_output(output: &[u8], empty: &str) -> Result<Self> {
let expanded = expand_tabs(output);
let styled = expanded
.into_text()
.context("Failed to parse ANSI colors in diff output")?
.lines;
let plain: Vec<String> = patch::strip_ansi(&String::from_utf8_lossy(&expanded))
.lines()
.map(str::to_owned)
.collect();
let patch = Patch::new(plain);
let mut view = Self {
rows: Vec::new(),
files: Vec::new(),
hunks: Vec::new(),
patch: patch.clone(),
scroll: 0,
pan: 0,
height: 0,
show_files: false,
search: None,
};
if patch.files().is_empty() {
view.rows
.push(Line::raw(empty.to_owned()).style(Color::DarkGray));
}
for (i, file) in patch.files().iter().enumerate() {
view.push_file(i, file, &styled, &patch);
}
Ok(view)
}
#[must_use]
pub const fn patch(&self) -> &Patch {
&self.patch
}
#[must_use]
pub fn hunks(&self) -> &[HunkEntry] {
&self.hunks
}
fn push_file(
&mut self,
index: usize,
file: &FileDiff,
styled: &[Line<'static>],
patch: &Patch,
) {
if !self.rows.is_empty() {
self.rows.push(Line::default()); }
self.files.push(FileEntry {
path: file.path.clone(),
added: file.added,
removed: file.removed,
row: self.rows.len(),
});
self.rows.push(file_title(file));
let line = |i: usize| styled.get(i).cloned().unwrap_or_default();
for i in file.header.clone() {
let noise = ["diff --git ", "index ", "--- ", "+++ "];
if !noise.iter().any(|p| patch.line(i).starts_with(p)) {
self.rows.push(line(i).style(Color::DarkGray));
}
}
for (h, hunk) in file.hunks.iter().enumerate() {
let start = self.rows.len();
self.rows.push(line(hunk.header));
self.rows.extend(hunk.lines.clone().map(line));
self.hunks.push(HunkEntry {
id: HunkId {
file: index,
hunk: h,
},
path: file.path.clone(),
rows: start..self.rows.len(),
});
}
}
#[must_use]
pub fn current_file(&self) -> Option<(usize, &FileEntry)> {
let i = self.files.partition_point(|f| f.row <= self.scroll);
let i = i.checked_sub(1)?;
Some((i + 1, &self.files[i]))
}
#[must_use]
pub const fn file_count(&self) -> usize {
self.files.len()
}
#[must_use]
pub const fn half_page(&self) -> usize {
if self.height > 2 { self.height / 2 } else { 1 }
}
pub fn scroll_down(&mut self, n: usize) {
let limit = self.max_scroll().max(self.scroll);
self.scroll = self.scroll.saturating_add(n).min(limit);
}
pub const fn scroll_up(&mut self, n: usize) {
self.scroll = self.scroll.saturating_sub(n);
}
pub const fn scroll_to_top(&mut self) {
self.scroll = 0;
}
pub const fn scroll_to_bottom(&mut self) {
self.scroll = self.max_scroll();
}
pub const fn pan_right(&mut self, n: u16) {
self.pan = self.pan.saturating_add(n);
}
pub const fn pan_left(&mut self, n: u16) {
self.pan = self.pan.saturating_sub(n);
}
const fn max_scroll(&self) -> usize {
self.rows.len().saturating_sub(self.height)
}
pub fn render(&mut self, frame: &mut Frame<'_>, area: Rect, block: Block<'static>) {
let mut inner = block.inner(area);
frame.render_widget(block, area);
if self.show_files && !self.files.is_empty() {
let [list, rest] = Layout::horizontal([
Constraint::Length(self.file_list_width(inner)),
Constraint::Fill(1),
])
.areas(inner);
self.render_file_list(frame, list);
inner = rest;
}
self.height = usize::from(inner.height);
self.scroll = self.scroll.min(self.rows.len().saturating_sub(1));
let end = (self.scroll + self.height).min(self.rows.len());
let visible = (self.scroll..end)
.map(|i| self.highlighted(i))
.collect::<Vec<_>>();
frame.render_widget(Paragraph::new(visible).scroll((0, self.pan)), inner);
}
fn file_list_width(&self, area: Rect) -> u16 {
let longest = self.files.iter().map(|f| list_entry(f).width()).max();
let wanted = u16::try_from(longest.unwrap_or(0) + 2).unwrap_or(u16::MAX);
wanted.min(area.width / 3)
}
fn render_file_list(&self, frame: &mut Frame<'_>, area: Rect) {
let current = self.current_file().map_or(0, |(n, _)| n - 1);
let height = usize::from(area.height);
let first = current.saturating_sub(height.saturating_sub(1));
let rows: Vec<Line<'_>> = self.files[first..]
.iter()
.take(height)
.enumerate()
.map(|(i, file)| {
let line = list_entry(file);
if first + i == current {
line.patch_style(Modifier::REVERSED)
} else {
line
}
})
.collect();
let block = Block::new()
.borders(ratatui::widgets::Borders::RIGHT)
.border_style(Color::DarkGray);
frame.render_widget(Paragraph::new(rows).block(block), area);
}
pub const fn toggle_file_list(&mut self) {
self.show_files = !self.show_files;
}
pub fn next_file(&mut self) {
self.jump(first_after(self.files.iter().map(|f| f.row), self.scroll));
}
pub fn prev_file(&mut self) {
self.jump(last_before(self.files.iter().map(|f| f.row), self.scroll));
}
pub fn next_hunk(&mut self) {
self.jump(first_after(
self.hunks.iter().map(|h| h.rows.start),
self.scroll,
));
}
pub fn prev_hunk(&mut self) {
self.jump(last_before(
self.hunks.iter().map(|h| h.rows.start),
self.scroll,
));
}
pub fn render_hunk(
&mut self,
frame: &mut Frame<'_>,
area: Rect,
block: Block<'static>,
at: usize,
) {
let inner = block.inner(area);
frame.render_widget(block, area);
self.height = usize::from(inner.height);
let Some(hunk) = self.hunks.get(at) else {
return;
};
self.scroll = self.scroll.clamp(hunk.rows.start, hunk.rows.end);
let end = (self.scroll + self.height).min(hunk.rows.end);
let visible = (self.scroll..end)
.map(|i| self.highlighted(i))
.collect::<Vec<_>>();
frame.render_widget(Paragraph::new(visible).scroll((0, self.pan)), inner);
}
pub fn render_divided(
&mut self,
frame: &mut Frame<'_>,
area: Rect,
block: Block<'static>,
at: usize,
rows: &[(usize, Mark)],
) {
let inner = block.inner(area);
frame.render_widget(block, area);
self.height = usize::from(inner.height);
let Some(hunk) = self.hunks.get(at) else {
return;
};
let Some(parsed) = self
.patch
.files()
.get(hunk.id.file)
.and_then(|f| f.hunks.get(hunk.id.hunk))
else {
return;
};
let row_of = |l: usize| hunk.rows.start + 1 + l.saturating_sub(parsed.lines.start);
let height = self.height.max(1);
let cursor = rows.iter().position(|(_, m)| m.is_cursor()).unwrap_or(0);
let top = cursor
.saturating_sub(height / 2)
.min(rows.len().saturating_sub(height));
let lines: Vec<Line<'static>> = rows
.iter()
.skip(top)
.take(height)
.map(|&(l, mark)| mark.apply(self.rows.get(row_of(l)).cloned().unwrap_or_default()))
.collect();
frame.render_widget(Paragraph::new(lines).scroll((0, self.pan)), inner);
}
pub fn show_hunk(&mut self, at: usize) {
if let Some(hunk) = self.hunks.get(at) {
self.scroll = hunk.rows.start;
}
}
const fn jump(&mut self, row: Option<usize>) {
if let Some(row) = row {
self.scroll = row;
}
}
pub fn search(&mut self, query: &str) -> usize {
if query.is_empty() {
self.search = None;
return 0;
}
let ignore_case = !query.chars().any(char::is_uppercase);
let needle = if ignore_case {
query.to_lowercase()
} else {
query.to_owned()
};
let rows: Vec<usize> = (0..self.rows.len())
.filter(|&i| {
let text = line_text(&self.rows[i]);
if ignore_case {
text.to_lowercase()
} else {
text
}
.contains(&needle)
})
.collect();
let count = rows.len();
let current = rows.iter().position(|&row| row >= self.scroll).unwrap_or(0);
self.search = Some(Search {
query: query.to_owned(),
rows,
current,
});
self.show_match();
count
}
pub fn next_match(&mut self) {
if let Some(search) = &mut self.search
&& !search.rows.is_empty()
{
search.current = (search.current + 1) % search.rows.len();
}
self.show_match();
}
pub fn prev_match(&mut self) {
if let Some(search) = &mut self.search
&& !search.rows.is_empty()
{
search.current = search
.current
.checked_sub(1)
.unwrap_or(search.rows.len() - 1);
}
self.show_match();
}
#[must_use]
pub fn search_status(&self) -> Option<(&str, usize, usize)> {
let search = self.search.as_ref()?;
let current = if search.rows.is_empty() {
0
} else {
search.current + 1
};
Some((&search.query, current, search.rows.len()))
}
fn show_match(&mut self) {
if let Some(&row) = self.search.as_ref().and_then(|s| s.rows.get(s.current)) {
self.scroll = row.saturating_sub(self.height / 3);
}
}
fn highlighted(&self, i: usize) -> Line<'static> {
let mut line = self.rows[i].clone();
let Some(search) = &self.search else {
return line;
};
let style = match search.rows.binary_search(&i) {
Ok(n) if n == search.current => Style::new().add_modifier(Modifier::REVERSED),
Ok(_) => Style::new().bg(Color::DarkGray),
Err(_) => return line,
};
for span in &mut line.spans {
span.style = span.style.patch(style);
}
line
}
}
fn file_title(file: &FileDiff) -> Line<'static> {
let bold = Style::new().add_modifier(Modifier::BOLD);
let mut spans = vec![Span::styled(file.path.clone(), bold.fg(Color::Yellow))];
if file.binary {
spans.push(Span::styled(" binary", Style::new().fg(Color::DarkGray)));
} else {
spans.push(Span::styled(
format!(" +{}", file.added),
bold.fg(Color::Green),
));
spans.push(Span::styled(
format!(" -{}", file.removed),
bold.fg(Color::Red),
));
}
Line::from(spans)
}
fn first_after(mut rows: impl Iterator<Item = usize>, top: usize) -> Option<usize> {
rows.find(|&row| row > top)
}
fn last_before(rows: impl Iterator<Item = usize>, top: usize) -> Option<usize> {
rows.take_while(|&row| row < top).last()
}
fn list_entry(file: &FileEntry) -> Line<'static> {
Line::from(vec![
Span::raw(file.path.clone()),
Span::styled(format!(" +{}", file.added), Color::Green),
Span::styled(format!(" -{}", file.removed), Color::Red),
])
}
fn line_text(line: &Line<'_>) -> String {
line.spans
.iter()
.map(|span| span.content.as_ref())
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
const OUTPUT: &[u8] = b"\
\x1b[1mdiff --git a/a.rs b/a.rs\x1b[0m
\x1b[1mindex 1111..2222 100644\x1b[0m
\x1b[1m--- a/a.rs\x1b[0m
\x1b[1m+++ b/a.rs\x1b[0m
\x1b[38;5;6m@@ -1,2 +1,2 @@\x1b[39m
keep
\x1b[38;5;1m-\told\x1b[39m
\x1b[38;5;2m+\tnew\x1b[39m
\x1b[1mdiff --git a/b.txt b/b.txt\x1b[0m
\x1b[1mnew file mode 100644\x1b[0m
\x1b[38;5;6m@@ -0,0 +1,1 @@\x1b[39m
\x1b[38;5;2m+hi\x1b[39m
";
fn text(line: &Line<'_>) -> String {
line.spans.iter().map(|s| s.content.as_ref()).collect()
}
#[test]
fn expands_tabs_to_tab_stops() {
assert_eq!(expand_tabs(b"\tx"), b" x");
assert_eq!(expand_tabs(b"ab\tx\n\ty"), b"ab x\n y");
}
#[test]
fn escapes_and_multibyte_chars_take_no_extra_columns() {
assert_eq!(expand_tabs(b"\x1b[32m+\x1b[0m\tx"), b"\x1b[32m+\x1b[0m x");
assert_eq!(expand_tabs("é\tx".as_bytes()), "é x".as_bytes());
}
#[test]
fn rows_have_titles_hunks_and_no_header_noise() {
let view = DiffView::from_output(OUTPUT, "").unwrap();
let rows: Vec<String> = view.rows.iter().map(text).collect();
assert_eq!(
rows,
[
"a.rs +1 -1",
"@@ -1,2 +1,2 @@",
" keep",
"- old",
"+ new",
"",
"b.txt +1 -0",
"new file mode 100644",
"@@ -0,0 +1,1 @@",
"+hi",
]
);
assert_eq!(view.files.iter().map(|f| f.row).collect::<Vec<_>>(), [0, 6]);
let starts: Vec<usize> = view.hunks.iter().map(|h| h.rows.start).collect();
assert_eq!(starts, [1, 8]);
}
#[test]
fn current_file_follows_the_scroll() {
let mut view = DiffView::from_output(OUTPUT, "").unwrap();
view.height = 2;
assert_eq!(view.current_file().unwrap().0, 1);
view.scroll_down(5);
assert_eq!(view.current_file().unwrap().0, 1);
view.scroll_down(1);
let (n, file) = view.current_file().unwrap();
assert_eq!((n, file.path.as_str(), file.added), (2, "b.txt", 1));
}
#[test]
fn empty_diff_says_so() {
let view = DiffView::from_output(b"", "(no changes)").unwrap();
assert_eq!(text(&view.rows[0]), "(no changes)");
assert!(view.files.is_empty());
}
#[test]
fn scrolling_is_clamped() {
let mut view = DiffView::from_output(OUTPUT, "").unwrap();
view.height = 4;
view.scroll_down(100);
assert_eq!(view.scroll, 6);
view.scroll_up(100);
assert_eq!(view.scroll, 0);
}
#[test]
fn jumps_between_files_and_hunks() {
let mut view = DiffView::from_output(OUTPUT, "").unwrap();
view.height = 2;
view.next_hunk();
assert_eq!(view.scroll, 1);
view.next_file();
assert_eq!(view.scroll, 6);
view.next_hunk();
assert_eq!(view.scroll, 8);
view.next_hunk(); assert_eq!(view.scroll, 8);
view.prev_file();
assert_eq!(view.scroll, 6);
view.prev_hunk();
assert_eq!(view.scroll, 1);
view.prev_file();
assert_eq!(view.scroll, 0);
}
#[test]
fn jumping_to_the_last_file_puts_it_on_top() {
let mut view = DiffView::from_output(OUTPUT, "").unwrap();
view.height = 8; view.next_file();
assert_eq!(view.current_file().unwrap().0, 2);
view.scroll_down(1); assert_eq!(view.scroll, 6);
}
#[test]
fn search_finds_rows_and_wraps() {
let mut view = DiffView::from_output(OUTPUT, "").unwrap();
view.height = 3;
assert_eq!(view.search("B.txt"), 0); assert_eq!(view.search("b.txt"), 1); view.scroll_to_top();
assert_eq!(view.search("new"), 2); assert_eq!(view.search_status(), Some(("new", 1, 2)));
assert_eq!(view.scroll, 4 - 1);
view.next_match();
assert_eq!(view.search_status(), Some(("new", 2, 2)));
view.next_match();
assert_eq!(view.search_status(), Some(("new", 1, 2)));
view.prev_match();
assert_eq!(view.search_status(), Some(("new", 2, 2)));
assert_eq!(view.search(""), 0);
assert_eq!(view.search_status(), None);
}
}