use std::collections::{BTreeSet, HashMap, HashSet};
use diffler_core::feedback::{self, FeedbackOptions};
use diffler_core::highlight::{Highlighter, StyledRange};
use diffler_core::model::{DiffModel, FileDiff, LineKind};
use diffler_core::review::Review;
use diffler_core::session::{Anchor, Comment, CommentStatus, Session};
use diffler_core::source::ReviewSource;
use diffler_core::syntax::ScopeIndex;
use unicode_width::UnicodeWidthStr;
use super::markdown::{self, MdSpan};
use super::{App, InputOp, Modal, Screen};
use crate::config::FileLayout;
use crate::keymap::Action;
use crate::tree::{self, Bucket, TreeNode, TreeRow};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pane {
List,
Diff,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollAlign {
Center,
Top,
Bottom,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct BucketFolds {
to_review: bool,
viewed: bool,
}
impl Default for BucketFolds {
fn default() -> Self {
Self {
to_review: false,
viewed: true,
}
}
}
impl BucketFolds {
fn is_folded(self, bucket: Bucket) -> bool {
match bucket {
Bucket::ToReview => self.to_review,
Bucket::Viewed => self.viewed,
}
}
fn toggle_fold(&mut self, bucket: Bucket) {
match bucket {
Bucket::ToReview => self.to_review = !self.to_review,
Bucket::Viewed => self.viewed = !self.viewed,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffRow {
Hunk {
file: usize,
hunk: usize,
},
Line {
file: usize,
hunk: usize,
line: usize,
},
Comment {
comment: usize,
line: usize,
outdated: bool,
},
}
#[derive(Debug, Clone)]
pub struct FileHighlights {
pub hash: String,
pub old: Vec<Vec<StyledRange>>,
pub new: Vec<Vec<StyledRange>>,
}
#[derive(Debug)]
pub struct FileScope {
pub hash: String,
pub index: ScopeIndex,
}
pub struct DiffView {
pub source: ReviewSource,
pub(crate) commit_model: Option<DiffModel>,
pub focus: Pane,
layout: FileLayout,
pub selected: usize,
pub(crate) folded_dirs: BTreeSet<String>,
pub(crate) bucket_folds: BucketFolds,
pub(crate) tree_cursor: usize,
pub cursor: usize,
pub scroll: usize,
pub(crate) scroll_align: Option<ScrollAlign>,
pub side_by_side: bool,
pub(crate) split_scroll: usize,
pub(crate) sidebar: ratatui::layout::Rect,
pub(crate) sidebar_scroll: usize,
pub(crate) pane: ratatui::layout::Rect,
pub visual_anchor: Option<usize>,
pub(crate) viewport: u16,
pub(crate) rows: Vec<DiffRow>,
pub(crate) line_rows: Vec<Option<usize>>,
rows_dirty: bool,
wrap_width: u16,
wrap_dirty: bool,
pub(crate) split_rows: Vec<SplitRow>,
pub(crate) highlights: HashMap<String, FileHighlights>,
pub(crate) scopes: HashMap<String, FileScope>,
enriched: HashSet<String>,
pub(crate) context: HashMap<String, u32>,
}
impl DiffView {
fn new(
source: ReviewSource,
commit_model: Option<DiffModel>,
review: &Review,
layout: FileLayout,
side_by_side: bool,
) -> Self {
let mut view = Self {
source,
commit_model,
focus: Pane::List,
layout,
selected: 0,
folded_dirs: BTreeSet::new(),
bucket_folds: BucketFolds::default(),
tree_cursor: 0,
cursor: 0,
scroll: 0,
scroll_align: None,
side_by_side,
split_scroll: 0,
sidebar: ratatui::layout::Rect::default(),
sidebar_scroll: 0,
pane: ratatui::layout::Rect::default(),
visual_anchor: None,
viewport: 0,
rows: Vec::new(),
line_rows: Vec::new(),
rows_dirty: true,
wrap_width: u16::MAX,
wrap_dirty: false,
split_rows: Vec::new(),
highlights: HashMap::new(),
scopes: HashMap::new(),
enriched: HashSet::new(),
context: HashMap::new(),
};
view.ensure_rows(review);
view
}
pub fn model<'a>(&'a self, review: &'a Review) -> &'a DiffModel {
self.commit_model.as_ref().unwrap_or_else(|| review.model())
}
pub(crate) fn is_enriched(&self, path: &str) -> bool {
self.enriched.contains(path)
}
pub(crate) fn mark_enriched(&mut self, path: &str) {
self.enriched.insert(path.to_owned());
}
pub(crate) fn clear_enriched(&mut self) {
self.enriched.clear();
}
pub fn rows(&self) -> &[DiffRow] {
&self.rows
}
pub(crate) fn split_cursor(&self, split: &[SplitRow]) -> (usize, Option<SplitSide>) {
let Some(row) = self.rows.get(self.cursor) else {
return (0, None);
};
match *row {
DiffRow::Hunk { hunk, .. } => (
split
.iter()
.position(|r| matches!(r, SplitRow::Hunk { hunk: h } if *h == hunk))
.unwrap_or(0),
None,
),
DiffRow::Line { hunk, line, .. } => {
for (i, r) in split.iter().enumerate() {
if let SplitRow::Pair {
hunk: h,
left,
right,
} = r
&& *h == hunk
{
if *left == Some(line) && *right == Some(line) {
return (i, None);
}
if *left == Some(line) {
return (i, Some(SplitSide::Left));
}
if *right == Some(line) {
return (i, Some(SplitSide::Right));
}
}
}
(0, None)
}
DiffRow::Comment { comment, line, .. } => (
split
.iter()
.position(|r| {
matches!(r, SplitRow::Comment { comment: c, line: l, .. } if *c == comment && *l == line)
})
.unwrap_or(0),
None,
),
}
}
pub fn selected_path(&self, review: &Review) -> Option<String> {
self.model(review)
.files
.get(self.selected)
.map(|f| f.path.clone())
}
pub(crate) fn mark_rows_dirty(&mut self) {
self.rows_dirty = true;
self.visual_anchor = None;
}
pub(crate) fn invalidate(&mut self) {
self.mark_rows_dirty();
self.enriched.clear();
}
pub(crate) fn set_wrap_width(&mut self, width: u16) {
if width > 0 && self.wrap_width != width {
self.wrap_width = width;
self.wrap_dirty = true;
}
}
pub(crate) fn ensure_rows(&mut self, review: &Review) {
if !self.rows_dirty && !self.wrap_dirty {
return;
}
let model = self.commit_model.as_ref().unwrap_or_else(|| review.model());
self.selected = self.selected.min(model.files.len().saturating_sub(1));
let session = review.session_for(&self.source);
self.rows = build_rows(model, session, self.selected, self.wrap_width);
self.split_rows = build_split_rows(model, session, self.selected, self.wrap_width);
self.cursor = self.cursor.min(self.rows.len().saturating_sub(1));
self.scroll = self.scroll.min(self.rows.len().saturating_sub(1));
if self.rows_dirty {
let tree_rows = self.tree_rows(model, session);
self.reseat_tree_cursor(&tree_rows);
}
self.rows_dirty = false;
self.wrap_dirty = false;
}
pub(crate) fn reseat_tree_cursor(&mut self, rows: &[TreeRow]) {
self.tree_cursor = tree_position_of_file(rows, self.selected)
.unwrap_or_else(|| self.tree_cursor.min(rows.len().saturating_sub(1)));
}
pub fn selection(&self) -> Option<(usize, usize)> {
let anchor = self.visual_anchor?;
Some((anchor.min(self.cursor), anchor.max(self.cursor)))
}
fn select(&mut self, selected: usize, review: &Review) {
if self.selected == selected {
return;
}
self.selected = selected;
self.cursor = 0;
self.scroll = 0;
self.visual_anchor = None;
self.rows_dirty = true;
self.ensure_rows(review);
}
pub(crate) fn tree_rows(&self, model: &DiffModel, session: &Session) -> Vec<TreeRow> {
match self.layout {
FileLayout::Review => self.review_rows(model, session),
FileLayout::Tree | FileLayout::List => {
let paths: Vec<&str> = model.files.iter().map(|f| f.path.as_str()).collect();
tree::visible_rows(&paths, &self.folded_dirs)
}
}
}
fn review_rows(&self, model: &DiffModel, session: &Session) -> Vec<TreeRow> {
let (mut fresh, mut viewed) = (Vec::new(), Vec::new());
for (index, file) in model.files.iter().enumerate() {
if session.is_viewed(&file.path, &file.content_hash()) {
viewed.push(index);
} else {
fresh.push(index);
}
}
let mut rows = Vec::new();
for (bucket, indices) in [(Bucket::ToReview, fresh), (Bucket::Viewed, viewed)] {
let folded = self.bucket_folds.is_folded(bucket);
rows.push(TreeRow {
depth: 0,
node: TreeNode::Section {
bucket,
count: indices.len(),
folded,
},
});
if folded {
continue;
}
rows.extend(indices.into_iter().filter_map(|index| {
let file = model.files.get(index)?;
Some(TreeRow {
depth: 1,
node: TreeNode::File {
index,
name: file.path.clone(),
},
})
}));
}
rows
}
pub(crate) fn cycle_layout(&mut self) -> FileLayout {
self.layout = match self.layout {
FileLayout::Review => FileLayout::Tree,
_ => FileLayout::Review,
};
self.layout
}
}
fn sidebar_rows(diff: &DiffView, review: &Review) -> Vec<TreeRow> {
diff.tree_rows(diff.model(review), review.session_for(&diff.source))
}
fn next_unviewed_index(diff: &DiffView, review: &Review, wrap: bool) -> Option<usize> {
let model = diff.model(review);
let session = review.session_for(&diff.source);
let count = model.files.len();
(1..=count)
.map(|step| diff.selected + step)
.take_while(|&index| wrap || index < count)
.map(|index| index % count)
.find(|&index| {
model
.files
.get(index)
.is_some_and(|file| !session.is_viewed(&file.path, &file.content_hash()))
})
}
fn tree_position_of_file(rows: &[TreeRow], file_index: usize) -> Option<usize> {
rows.iter()
.position(|row| matches!(&row.node, TreeNode::File { index, .. } if *index == file_index))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CommentLine {
Header,
Body(Vec<MdSpan>),
Reply {
author: String,
spans: Vec<MdSpan>,
first: bool,
},
Footer,
}
pub fn comment_display(
comment: &Comment,
row_width: u16,
highlighter: Option<&Highlighter>,
) -> Vec<CommentLine> {
let budget = (row_width.saturating_sub(4) as usize).max(8);
let mut lines = vec![CommentLine::Header];
for logical in markdown::parse(&comment.body, highlighter) {
lines.extend(
markdown::wrap(&logical, budget, budget)
.into_iter()
.map(CommentLine::Body),
);
}
for reply in &comment.replies {
let label = format!("↳ {}: ", reply.author).width();
let mut first = true;
for logical in markdown::parse(&reply.body, highlighter) {
let head = budget.saturating_sub(if first { label } else { 2 }).max(8);
for spans in markdown::wrap(&logical, head, budget.saturating_sub(2).max(8)) {
lines.push(CommentLine::Reply {
author: reply.author.clone(),
spans,
first,
});
first = false;
}
}
}
lines.push(CommentLine::Footer);
lines
}
fn anchor_target(file: &FileDiff, anchor: &Anchor) -> Option<(usize, usize)> {
let target = anchor.line_end.or(anchor.line)?;
for (hunk_idx, hunk) in file.hunks.iter().enumerate() {
let found = hunk.lines.iter().position(|l| {
let no = if anchor.on_old_side {
l.old_no
} else {
l.new_no
};
no == Some(target)
});
if let Some(line_idx) = found {
return Some((hunk_idx, line_idx));
}
}
None
}
fn push_comment_rows(
rows: &mut Vec<DiffRow>,
session: &Session,
comments: &[(usize, bool)],
wrap_width: u16,
) {
for &(comment, outdated) in comments {
let Some(c) = session.comments.get(comment) else {
continue;
};
let count = comment_display(c, wrap_width, None).len();
rows.extend((0..count).map(|line| DiffRow::Comment {
comment,
line,
outdated,
}));
}
}
type CommentBuckets = (
HashMap<(usize, usize), Vec<(usize, bool)>>,
Vec<(usize, bool)>,
);
fn collect_comments(file: &FileDiff, session: &Session, model: &DiffModel) -> CommentBuckets {
let mut by_line: HashMap<(usize, usize), Vec<(usize, bool)>> = HashMap::new();
let mut unanchored: Vec<(usize, bool)> = Vec::new();
for (comment_idx, comment) in session.comments.iter().enumerate() {
if comment.anchor.file != file.path {
continue;
}
let outdated = comment.anchor.is_outdated(model);
match anchor_target(file, &comment.anchor) {
Some((hunk, line)) => by_line
.entry((hunk, line))
.or_default()
.push((comment_idx, outdated)),
None => unanchored.push((comment_idx, outdated)),
}
}
(by_line, unanchored)
}
fn build_rows(
model: &DiffModel,
session: &Session,
selected: usize,
wrap_width: u16,
) -> Vec<DiffRow> {
let mut rows = Vec::new();
let Some(file) = model.files.get(selected) else {
return rows;
};
let (by_line, unanchored) = collect_comments(file, session, model);
push_comment_rows(&mut rows, session, &unanchored, wrap_width);
for (hunk_idx, hunk) in file.hunks.iter().enumerate() {
rows.push(DiffRow::Hunk {
file: selected,
hunk: hunk_idx,
});
for line_idx in 0..hunk.lines.len() {
rows.push(DiffRow::Line {
file: selected,
hunk: hunk_idx,
line: line_idx,
});
if let Some(list) = by_line.get(&(hunk_idx, line_idx)) {
push_comment_rows(&mut rows, session, list, wrap_width);
}
}
}
rows
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SplitSide {
Left,
Right,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SplitRow {
Hunk {
hunk: usize,
},
Pair {
hunk: usize,
left: Option<usize>,
right: Option<usize>,
},
Comment {
comment: usize,
line: usize,
outdated: bool,
},
}
fn push_split_comments(
rows: &mut Vec<SplitRow>,
session: &Session,
comments: &[(usize, bool)],
wrap_width: u16,
) {
for &(comment, outdated) in comments {
let Some(c) = session.comments.get(comment) else {
continue;
};
let count = comment_display(c, wrap_width, None).len();
rows.extend((0..count).map(|line| SplitRow::Comment {
comment,
line,
outdated,
}));
}
}
fn flush_change_block(
rows: &mut Vec<SplitRow>,
session: &Session,
by_line: &HashMap<(usize, usize), Vec<(usize, bool)>>,
hunk: usize,
dels: &[usize],
adds: &[usize],
wrap_width: u16,
) {
for k in 0..dels.len().max(adds.len()) {
let left = dels.get(k).copied();
let right = adds.get(k).copied();
rows.push(SplitRow::Pair { hunk, left, right });
for line in [left, right].into_iter().flatten() {
if let Some(list) = by_line.get(&(hunk, line)) {
push_split_comments(rows, session, list, wrap_width);
}
}
}
}
pub(crate) fn build_split_rows(
model: &DiffModel,
session: &Session,
selected: usize,
wrap_width: u16,
) -> Vec<SplitRow> {
let mut rows = Vec::new();
let Some(file) = model.files.get(selected) else {
return rows;
};
let (by_line, unanchored) = collect_comments(file, session, model);
push_split_comments(&mut rows, session, &unanchored, wrap_width);
for (hunk_idx, hunk) in file.hunks.iter().enumerate() {
rows.push(SplitRow::Hunk { hunk: hunk_idx });
let mut dels: Vec<usize> = Vec::new();
let mut adds: Vec<usize> = Vec::new();
for (line_idx, line) in hunk.lines.iter().enumerate() {
match line.kind {
LineKind::Context => {
flush_change_block(
&mut rows, session, &by_line, hunk_idx, &dels, &adds, wrap_width,
);
dels.clear();
adds.clear();
rows.push(SplitRow::Pair {
hunk: hunk_idx,
left: Some(line_idx),
right: Some(line_idx),
});
if let Some(list) = by_line.get(&(hunk_idx, line_idx)) {
push_split_comments(&mut rows, session, list, wrap_width);
}
}
LineKind::Deleted => dels.push(line_idx),
LineKind::Added => adds.push(line_idx),
}
}
flush_change_block(
&mut rows, session, &by_line, hunk_idx, &dels, &adds, wrap_width,
);
}
rows
}
impl App {
pub(crate) fn open_working_tree_diff(&mut self, scope: Option<&str>) {
self.open_working_tree_diff_focused(scope, Pane::List);
}
pub(crate) fn open_working_tree_file(&mut self, path: &str) {
self.open_working_tree_diff_focused(Some(path), Pane::Diff);
}
fn open_working_tree_diff_focused(&mut self, scope: Option<&str>, focus: Pane) {
self.install_diff_view(ReviewSource::WorkingTree, None);
let Some(view) = self.diff.as_mut() else {
return;
};
if let Some(path) = scope
&& let Some(index) = self
.review
.model()
.files
.iter()
.position(|f| f.path == path)
{
view.selected = index;
view.invalidate();
view.ensure_rows(&self.review);
}
view.focus = focus;
}
fn install_diff_view(&mut self, source: ReviewSource, model: Option<DiffModel>) {
if let Err(err) = self.review.ensure_source(&source) {
self.error(err.to_string());
return;
}
let view = DiffView::new(
source,
model,
&self.review,
self.config.ui.diff_file_layout,
self.config.ui.side_by_side,
);
self.diff = Some(view);
self.push_screen(Screen::Diff);
}
pub(crate) fn open_commit_diff(&mut self, oid: &str) {
match self.review.vcs.commit_diff(oid) {
Ok(model) => self.install_diff_view(ReviewSource::commit(oid), Some(model)),
Err(err) => self.error(err.to_string()),
}
}
pub(crate) fn open_against_diff(&mut self, rev: &str) {
match diffler_core::vcs::against_diff(self.review.vcs.as_ref(), rev) {
Ok(model) => {
let source = ReviewSource::against(rev);
if let Some(diff) = self.diff.as_mut().filter(|d| d.source == source) {
diff.commit_model = Some(model);
diff.invalidate();
diff.ensure_rows(&self.review);
} else {
self.install_diff_view(source, Some(model));
}
}
Err(err) => self.error(err.to_string()),
}
}
pub(crate) fn against_model_for(&self, rev: &str) -> DiffModel {
self.diff
.as_ref()
.filter(|d| d.source == ReviewSource::against(rev))
.and_then(|d| d.commit_model.clone())
.unwrap_or_else(|| {
diffler_core::vcs::against_diff(self.review.vcs.as_ref(), rev).unwrap_or_default()
})
}
pub fn against_rev(&self) -> Option<&str> {
match self.diff.as_ref().map(|d| &d.source) {
Some(ReviewSource::Against { rev }) => Some(rev),
_ => None,
}
}
pub(crate) fn open_range_diff(&mut self, oldest: &str, newest: &str) {
match self.review.vcs.range_diff(oldest, newest) {
Ok(model) => self.install_diff_view(ReviewSource::range(oldest, newest), Some(model)),
Err(err) => self.error(err.to_string()),
}
}
pub(crate) fn open_pr_review(&mut self) {
let Some(pr) = self.pr.clone() else {
self.info("no open PR detected for this branch");
return;
};
self.open_pr_review_for(pr);
}
pub(crate) fn open_pr_review_for(&mut self, pr: crate::ci::PullRequest) {
if let Some((base, head)) = self.resolve_pr_range(&pr) {
self.open_pr_diff(pr.number, &base, &head);
} else {
let remote = self
.ci_remotes
.first()
.map_or_else(|| "origin".to_owned(), |r| r.name.clone());
let refspec = format!("refs/pull/{}/head", pr.number);
let base_ref = pr.base_ref.clone();
let label = Self::pr_fetch_label(pr.number);
self.pending_pr_open = Some(pr);
self.pending_git = Some(super::GitOp {
label,
argv: vec![
"git".to_owned(),
"fetch".to_owned(),
remote,
refspec,
base_ref,
],
});
}
}
pub(super) fn resolve_pr_range(&self, pr: &crate::ci::PullRequest) -> Option<(String, String)> {
let head = self.review.vcs.resolve(&pr.head_oid).ok()?;
let base_tip = self
.ci_remotes
.first()
.and_then(|r| {
self.review
.vcs
.resolve(&format!("refs/remotes/{}/{}", r.name, pr.base_ref))
.ok()
})
.or_else(|| self.review.vcs.resolve(&pr.base_ref).ok())?;
let base = self.review.vcs.merge_base(&base_tip, &head).ok()?;
Some((base, head))
}
pub(crate) fn open_pr_diff(&mut self, number: u64, base: &str, head: &str) {
match self.review.vcs.tree_diff(base, head) {
Ok(model) => {
self.pr_ranges
.insert(number, (base.to_owned(), head.to_owned()));
let source = ReviewSource::pr(number);
if let Err(err) = self.review.ensure_source(&source) {
self.error(err.to_string());
return;
}
if let Some(diff) = self.diff.as_mut().filter(|d| d.source == source) {
diff.commit_model = Some(model);
diff.invalidate();
diff.ensure_rows(&self.review);
} else {
self.install_diff_view(source, Some(model));
}
self.pending_ci = Some(super::CiRequest::PrComments(number));
}
Err(err) => self.error(err.to_string()),
}
}
pub(super) fn dispatch_diff(&mut self, action: Action) {
let scope = self.diff.as_ref().map(|d| (d.selected, d.focus));
self.dispatch_diff_inner(action);
if self.search.is_some() && self.diff.as_ref().map(|d| (d.selected, d.focus)) != scope {
self.search = None;
}
}
fn dispatch_diff_inner(&mut self, action: Action) {
if let Some(diff) = self.diff.as_mut() {
diff.ensure_rows(&self.review);
} else {
return;
}
match action {
Action::NextFile => return self.diff_step_file(true),
Action::PrevFile => return self.diff_step_file(false),
Action::NextUnviewed => return self.diff_jump_unviewed(),
Action::CycleSidebarMode => return self.diff_cycle_sidebar_mode(),
Action::MoveLeft => return self.diff_focus(Pane::List),
Action::MoveRight => return self.diff_focus(Pane::Diff),
Action::ToggleSideBySide => return self.toggle_side_by_side(),
Action::SubmitReview => return self.submit_pr_review(),
Action::NextComment => {
self.diff_focus(Pane::Diff);
return self.diff_jump_comment(true);
}
Action::PrevComment => {
self.diff_focus(Pane::Diff);
return self.diff_jump_comment(false);
}
_ => {}
}
match self.diff.as_ref().map(|d| d.focus) {
Some(Pane::List) => self.dispatch_diff_list(action),
Some(Pane::Diff) => self.dispatch_diff_pane(action),
None => {}
}
}
fn dispatch_diff_list(&mut self, action: Action) {
match action {
Action::MoveDown => self.diff_tree_step(1),
Action::MoveUp => self.diff_tree_step(-1),
Action::GoTop => self.diff_tree_to(0),
Action::GoBottom => self.diff_tree_to(usize::MAX),
Action::HalfPageDown => self.diff_move(self.diff_page(false)),
Action::HalfPageUp => self.diff_move(-self.diff_page(false)),
Action::FullPageDown => self.diff_move(self.diff_page(true)),
Action::FullPageUp => self.diff_move(-self.diff_page(true)),
Action::Open => self.diff_tree_activate(),
Action::ToggleFold => self.diff_toggle_dir_fold(),
Action::MarkViewed => self.diff_toggle_viewed(),
Action::UnviewAll => self.diff_unview_all(),
Action::OpenEditor => self.editor_at_diff_cursor(),
Action::CopyFileFeedback => self.copy_file_or_selection(),
Action::Impact => self.open_impact(),
Action::CopyAllFeedback => self.copy_feedback(false),
Action::Comment => self.comment_on_selected_file(),
Action::VisualSelect | Action::Reply | Action::Resolve | Action::DeleteComment => {
self.info("move into the diff to comment");
}
_ => {}
}
}
fn dispatch_diff_pane(&mut self, action: Action) {
match action {
Action::Impact => self.open_impact(),
Action::MoveDown => self.diff_move(1),
Action::MoveUp => self.diff_move(-1),
Action::GoTop => self.diff_move(isize::MIN),
Action::GoBottom => self.diff_move(isize::MAX),
Action::HalfPageDown => self.diff_move(self.diff_page(false)),
Action::HalfPageUp => self.diff_move(-self.diff_page(false)),
Action::FullPageDown => self.diff_move(self.diff_page(true)),
Action::FullPageUp => self.diff_move(-self.diff_page(true)),
Action::NextHunk => self.diff_jump(true, |row| matches!(row, DiffRow::Hunk { .. })),
Action::PrevHunk => self.diff_jump(false, |row| matches!(row, DiffRow::Hunk { .. })),
Action::NextFunction => self.diff_jump_function(true),
Action::PrevFunction => self.diff_jump_function(false),
Action::CenterCursor => self.diff_align(ScrollAlign::Center),
Action::CursorTop => self.diff_align(ScrollAlign::Top),
Action::CursorBottom => self.diff_align(ScrollAlign::Bottom),
Action::ExpandContext => self.expand_context(),
Action::CollapseContext => self.collapse_context(),
Action::ExpandWholeFile => self.expand_whole_file(),
Action::Open => self.diff_focus(Pane::List),
Action::Comment | Action::VisualSelect | Action::Reply | Action::Resolve
if self.diff.as_ref().is_some_and(|d| d.side_by_side) =>
{
self.info("switch to the unified view (|) to comment");
}
Action::Comment => self.comment_at_cursor(),
Action::VisualSelect => self.toggle_visual(),
Action::Reply => self.reply_at_cursor(),
Action::Resolve => self.resolve_at_cursor(),
Action::DeleteComment => self.delete_comment_at_cursor(),
Action::MarkViewed => self.diff_toggle_viewed(),
Action::UnviewAll => self.diff_unview_all(),
Action::CopyFileFeedback => self.copy_file_or_selection(),
Action::CopyAllFeedback => self.copy_feedback(false),
Action::OpenEditor => self.editor_at_diff_cursor(),
Action::ToggleFold => {}
other => {
self.info(format!("{} is not implemented yet", other.name()));
}
}
}
fn toggle_side_by_side(&mut self) {
let Some(diff) = self.diff.as_mut() else {
return;
};
diff.side_by_side = !diff.side_by_side;
diff.split_scroll = 0;
self.info(if self.diff.as_ref().is_some_and(|d| d.side_by_side) {
"side-by-side"
} else {
"unified"
});
}
fn diff_focus(&mut self, pane: Pane) {
if let Some(diff) = self.diff.as_mut() {
diff.focus = pane;
}
}
fn diff_align(&mut self, align: ScrollAlign) {
if let Some(diff) = self.diff.as_mut() {
diff.scroll_align = Some(align);
}
}
pub(super) fn diff_mouse(&mut self, gesture: super::MouseGesture) {
use super::MouseGesture;
match gesture {
MouseGesture::Scroll { col, down, .. } => {
let delta = if down { 3 } else { -3 };
let in_sidebar = self.diff.as_ref().is_some_and(|d| col < d.pane.x);
if in_sidebar {
self.diff_tree_step(delta);
} else {
self.diff_move(delta);
}
}
MouseGesture::Press { col, row } => self.diff_press_at(col, row),
MouseGesture::DoublePress { col, row } => self.diff_activate_at(col, row),
MouseGesture::Drag { col, row } => self.diff_drag_to(col, row),
MouseGesture::Cancel => {
if let Some(diff) = self.diff.as_mut() {
diff.visual_anchor = None;
}
}
}
}
fn diff_press_at(&mut self, col: u16, row: u16) {
if let Some(index) = self.diff_sidebar_row_at(col, row) {
self.diff_tree_to(index);
return;
}
if let Some(index) = self.diff_pane_row_at(col, row)
&& let Some(diff) = self.diff.as_mut()
{
diff.cursor = index;
diff.visual_anchor = None;
}
}
fn diff_activate_at(&mut self, col: u16, row: u16) {
if let Some(index) = self.diff_sidebar_row_at(col, row) {
self.diff_tree_to(index);
self.diff_tree_activate();
return;
}
if let Some(index) = self.diff_pane_row_at(col, row) {
if let Some(diff) = self.diff.as_mut() {
diff.cursor = index;
diff.visual_anchor = None;
}
self.diff_focus(Pane::Diff);
self.comment_at_cursor();
}
}
fn diff_drag_to(&mut self, col: u16, row: u16) {
if let Some(index) = self.diff_pane_row_at(col, row)
&& let Some(diff) = self.diff.as_mut()
{
if diff.visual_anchor.is_none() {
diff.visual_anchor = Some(diff.cursor);
}
diff.cursor = index;
}
}
fn diff_sidebar_row_at(&self, col: u16, row: u16) -> Option<usize> {
let diff = self.diff.as_ref()?;
let index = super::hit_index(diff.sidebar, diff.sidebar_scroll, col, row)?;
(index < sidebar_rows(diff, &self.review).len()).then_some(index)
}
fn diff_pane_row_at(&self, col: u16, row: u16) -> Option<usize> {
let diff = self.diff.as_ref()?;
if diff.side_by_side {
return None;
}
let pane = diff.pane;
let inside = col >= pane.x
&& col < pane.x + pane.width
&& row >= pane.y
&& row < pane.y + pane.height;
if !inside {
return None;
}
diff.line_rows
.get((row - pane.y) as usize)
.copied()
.flatten()
}
fn diff_tree_step(&mut self, delta: isize) {
let Some(diff) = self.diff.as_ref() else {
return;
};
let rows = sidebar_rows(diff, &self.review);
if rows.is_empty() {
return;
}
let target = diff
.tree_cursor
.saturating_add_signed(delta)
.min(rows.len() - 1);
self.diff_tree_to(target);
}
fn diff_tree_to(&mut self, target: usize) {
let review = &self.review;
let Some(diff) = self.diff.as_mut() else {
return;
};
let rows = sidebar_rows(diff, review);
if rows.is_empty() {
return;
}
let target = target.min(rows.len() - 1);
diff.tree_cursor = target;
if let Some(TreeRow {
node: TreeNode::File { index, .. },
..
}) = rows.get(target)
{
let index = *index;
diff.select(index, review);
diff.tree_cursor = target;
}
}
fn diff_tree_activate(&mut self) {
let review = &self.review;
let Some(diff) = self.diff.as_mut() else {
return;
};
let rows = sidebar_rows(diff, review);
match rows.get(diff.tree_cursor).map(|r| &r.node) {
Some(TreeNode::File { .. }) => self.diff_focus(Pane::Diff),
Some(TreeNode::Dir { .. } | TreeNode::Section { .. }) => self.diff_toggle_dir_fold(),
None => {}
}
}
fn diff_toggle_dir_fold(&mut self) {
let review = &self.review;
let Some(diff) = self.diff.as_mut() else {
return;
};
let rows = sidebar_rows(diff, review);
match rows.get(diff.tree_cursor).map(|r| &r.node) {
Some(TreeNode::Dir { path, .. }) => {
let path = path.clone();
if !diff.folded_dirs.remove(&path) {
diff.folded_dirs.insert(path);
}
}
Some(TreeNode::Section { bucket, .. }) => diff.bucket_folds.toggle_fold(*bucket),
_ => return,
}
let rows = sidebar_rows(diff, review);
diff.tree_cursor = diff.tree_cursor.min(rows.len().saturating_sub(1));
}
fn diff_step_file(&mut self, forward: bool) {
let Some(diff) = self.diff.as_ref() else {
return;
};
let rows = sidebar_rows(diff, &self.review);
let is_file = |row: &TreeRow| matches!(row.node, TreeNode::File { .. });
let target = if forward {
rows.iter()
.enumerate()
.skip(diff.tree_cursor + 1)
.find(|(_, row)| is_file(row))
.map(|(index, _)| index)
} else {
rows.iter()
.enumerate()
.take(diff.tree_cursor)
.rfind(|(_, row)| is_file(row))
.map(|(index, _)| index)
};
if let Some(target) = target {
self.diff_tree_to(target);
}
}
fn diff_jump_unviewed(&mut self) {
let Some(diff) = self.diff.as_ref() else {
return;
};
if diff.model(&self.review).files.is_empty() {
self.info("nothing to review");
return;
}
match next_unviewed_index(diff, &self.review, true) {
Some(index) => self.diff_select_file_index(index),
None => self.info("every file is viewed"),
}
}
fn diff_cycle_sidebar_mode(&mut self) {
let review = &self.review;
let Some(diff) = self.diff.as_mut() else {
return;
};
let layout = diff.cycle_layout();
let rows = sidebar_rows(diff, review);
diff.reseat_tree_cursor(&rows);
self.search = None;
self.info(format!("sidebar: {layout}"));
}
fn editor_at_diff_cursor(&mut self) {
let target = self.diff.as_ref().and_then(|diff| {
let model = diff.model(&self.review);
let file = model.files.get(diff.selected)?;
if diff.focus == Pane::List {
return Some((file.path.clone(), None));
}
match diff.rows.get(diff.cursor) {
Some(DiffRow::Hunk { .. }) | None => Some((file.path.clone(), None)),
Some(DiffRow::Line { hunk, line, .. }) => {
let line = file.hunks.get(*hunk)?.lines.get(*line)?;
Some((file.path.clone(), line.new_no.or(line.old_no)))
}
Some(DiffRow::Comment { comment, .. }) => self
.review
.session_for(&diff.source)
.comments
.get(*comment)
.map(|c| (c.anchor.file.clone(), c.anchor.line_end.or(c.anchor.line))),
}
});
match target {
Some((path, line)) => self.request_editor(&path, line),
None => self.info("no file under the cursor"),
}
}
fn diff_move(&mut self, delta: isize) {
let Some(diff) = self.diff.as_mut() else {
return;
};
let last = diff.rows.len().saturating_sub(1);
diff.cursor = diff.cursor.saturating_add_signed(delta).min(last);
}
fn diff_page(&self, full: bool) -> isize {
let step = super::page_step(self.diff.as_ref().map_or(0, |d| d.viewport), full);
isize::try_from(step).unwrap_or(20)
}
fn diff_jump_comment(&mut self, forward: bool) {
self.diff_jump(forward, |row| {
matches!(row, DiffRow::Comment { line: 0, .. })
});
}
fn diff_jump_function(&mut self, forward: bool) {
let Some(diff) = self.diff.as_ref() else {
return;
};
let Some(path) = diff.selected_path(&self.review) else {
return;
};
let Some(scope) = diff.scopes.get(&path) else {
self.info("no definition index for this file (yet)");
return;
};
let starts: std::collections::HashSet<u32> = scope
.index
.def_starts()
.into_iter()
.filter_map(|row| u32::try_from(row + 1).ok())
.collect();
if starts.is_empty() {
self.info("no definitions in this file");
return;
}
let model = diff
.commit_model
.clone()
.unwrap_or_else(|| self.review.model().clone());
let file = model.files.iter().position(|f| f.path == path);
self.diff_jump(forward, |row| {
let DiffRow::Line {
file: f,
hunk,
line,
} = row
else {
return false;
};
Some(*f) == file
&& model
.files
.get(*f)
.and_then(|fd| fd.hunks.get(*hunk))
.and_then(|h| h.lines.get(*line))
.and_then(|l| l.new_no)
.is_some_and(|no| starts.contains(&no))
});
}
fn diff_jump(&mut self, forward: bool, target: impl Fn(&DiffRow) -> bool) {
let Some(diff) = self.diff.as_mut() else {
return;
};
let position = if forward {
diff.rows
.iter()
.enumerate()
.skip(diff.cursor + 1)
.find(|(_, row)| target(row))
.map(|(index, _)| index)
} else {
diff.rows
.iter()
.enumerate()
.take(diff.cursor)
.rfind(|(_, row)| target(row))
.map(|(index, _)| index)
};
if let Some(position) = position {
diff.cursor = position;
}
}
pub(crate) fn diff_cursor_path(&self) -> Option<String> {
let diff = self.diff.as_ref()?;
diff.selected_path(&self.review)
}
pub(super) fn restore_diff_cursor(&mut self, path: Option<String>) {
let Some(path) = path else {
return;
};
let review = &self.review;
let Some(diff) = self.diff.as_mut() else {
return;
};
let model = diff.commit_model.as_ref().unwrap_or_else(|| review.model());
match model.files.iter().position(|f| f.path == path) {
Some(index) if index != diff.selected => diff.selected = index,
Some(_) => return,
None => {}
}
diff.invalidate();
diff.ensure_rows(review);
}
fn toggle_visual(&mut self) {
let Some(diff) = self.diff.as_mut() else {
return;
};
if diff.visual_anchor.take().is_some() {
return;
}
if matches!(diff.rows.get(diff.cursor), Some(DiffRow::Line { .. })) {
diff.visual_anchor = Some(diff.cursor);
} else {
self.info("move to a diff line to start a selection");
}
}
fn comment_anchor(&self) -> Option<Anchor> {
let diff = self.diff.as_ref()?;
let model = diff.model(&self.review);
let line_at = |row: &DiffRow| -> Option<(
usize,
&diffler_core::model::Hunk,
&diffler_core::model::DiffLine,
)> {
let DiffRow::Line { file, hunk, line } = row else {
return None;
};
let hunk_data = model.files.get(*file)?.hunks.get(*hunk)?;
Some((*file, hunk_data, hunk_data.lines.get(*line)?))
};
let anchor_row = diff.visual_anchor.unwrap_or(diff.cursor);
let (file_idx, _, line) = line_at(diff.rows.get(anchor_row)?)?;
let file = model.files.get(file_idx)?;
let on_old_side = line.new_no.is_none();
let number = |l: &diffler_core::model::DiffLine| {
if on_old_side { l.old_no } else { l.new_no }
};
let Some((start, end)) = diff.selection() else {
return Some(Anchor {
file: file.path.clone(),
line: Some(number(line)?),
line_end: None,
on_old_side,
line_text: Some(line.text.clone()),
});
};
let mut numbered: Vec<(u32, String)> = Vec::new();
for index in start..=end {
let Some(row) = diff.rows.get(index) else {
continue;
};
if !matches!(row, DiffRow::Line { file, .. } if *file == file_idx) {
continue;
}
let Some((_, _, l)) = line_at(row) else {
continue;
};
if let Some(no) = number(l) {
numbered.push((no, l.text.clone()));
}
}
let (first, _) = numbered.iter().min_by_key(|(no, _)| *no)?.clone();
let (last, last_text) = numbered.iter().max_by_key(|(no, _)| *no)?.clone();
Some(Anchor {
file: file.path.clone(),
line: Some(first),
line_end: (last > first).then_some(last),
on_old_side,
line_text: Some(last_text),
})
}
fn comment_at_cursor(&mut self) {
if let Some(comment) = self.comment_at_cursor_row() {
let comment_id = comment.id.clone();
let body = comment.body.clone();
self.open_input(
"Edit comment".to_owned(),
body,
InputOp::EditComment { comment_id },
);
return;
}
let Some(anchor) = self.comment_anchor() else {
self.info("move to a diff line to comment");
return;
};
let title = match (anchor.line, anchor.line_end) {
(Some(line), Some(end)) => format!("Comment {}:{line}-{end}", anchor.file),
(Some(line), None) => format!("Comment {}:{line}", anchor.file),
_ => format!("Comment {}", anchor.file),
};
self.open_input(title, String::new(), InputOp::Comment { anchor });
}
fn comment_on_selected_file(&mut self) {
let Some(path) = self
.diff
.as_ref()
.and_then(|d| d.selected_path(&self.review))
else {
self.info("select a file to comment on");
return;
};
let anchor = Anchor {
file: path.clone(),
line: None,
line_end: None,
on_old_side: false,
line_text: None,
};
self.open_input(
format!("Comment {path}"),
String::new(),
InputOp::Comment { anchor },
);
}
fn comment_at_cursor_row(&self) -> Option<&Comment> {
let diff = self.diff.as_ref()?;
let DiffRow::Comment { comment, .. } = diff.rows.get(diff.cursor)? else {
return None;
};
self.review.session_for(&diff.source).comments.get(*comment)
}
fn delete_comment_at_cursor(&mut self) {
let Some(comment) = self.comment_at_cursor_row() else {
self.info("move onto a comment to delete it");
return;
};
let (id, author) = (comment.id.clone(), comment.author.clone());
self.modal = Some(Modal::Confirm {
message: format!("Delete {author}'s comment?"),
on_confirm: super::PendingOp::DeleteComment(id),
});
}
fn reply_at_cursor(&mut self) {
let Some(comment) = self.comment_at_cursor_row() else {
self.info("move onto a comment to reply");
return;
};
let comment_id = comment.id.clone();
let author = comment.author.clone();
self.open_input(
format!("Reply to {author}"),
String::new(),
InputOp::Reply { comment_id },
);
}
fn resolve_at_cursor(&mut self) {
let Some(comment) = self.comment_at_cursor_row() else {
self.info("move onto a comment to resolve");
return;
};
let id = comment.id.clone();
let resolving = comment.status != CommentStatus::Resolved;
let forge = comment.remote_id.is_some();
let source = self.active_review_source();
if forge
&& let ReviewSource::Pr { number } = source
&& !self.queue_pr_resolve(number, &id, resolving)
{
return;
}
let session = self.review.session_for_mut(&source);
if resolving {
session.resolve(&id);
} else if let Some(comment) = session.comments.iter_mut().find(|c| c.id == id) {
comment.status = CommentStatus::Open;
}
self.after_session_change();
self.info(if resolving {
"comment resolved"
} else {
"comment reopened"
});
}
fn diff_toggle_viewed(&mut self) {
let Some(path) = self.diff_cursor_path() else {
return;
};
let source = self.active_review_source();
let hash = self.diff.as_ref().and_then(|diff| {
diff.model(&self.review)
.files
.iter()
.find(|f| f.path == path)
.map(FileDiff::content_hash)
});
let Some(hash) = hash else {
self.info(format!("{path} is not part of the review diff"));
return;
};
let session = self.review.session_for_mut(&source);
let viewed = session.is_viewed(&path, &hash);
if viewed {
session.unmark_viewed(&path);
} else {
session.mark_viewed(&path, &hash);
}
if let Err(err) = self.review.save_for(&source) {
self.error(err.to_string());
}
if !viewed {
self.diff_advance_to_unviewed();
}
let review = &self.review;
if let Some(diff) = self.diff.as_mut() {
let rows = sidebar_rows(diff, review);
diff.reseat_tree_cursor(&rows);
}
}
fn diff_unview_all(&mut self) {
let source = self.active_review_source();
let session = self.review.session_for_mut(&source);
if session.viewed.is_empty() {
self.info("no files marked viewed");
return;
}
session.clear_viewed();
if let Err(err) = self.review.save_for(&source) {
self.error(err.to_string());
return;
}
let review = &self.review;
if let Some(diff) = self.diff.as_mut() {
let rows = sidebar_rows(diff, review);
diff.reseat_tree_cursor(&rows);
}
self.info("cleared all viewed marks");
}
fn diff_advance_to_unviewed(&mut self) {
let next = self
.diff
.as_ref()
.and_then(|diff| next_unviewed_index(diff, &self.review, false));
if let Some(index) = next {
self.diff_select_file_index(index);
}
}
fn diff_select_file_index(&mut self, index: usize) {
let review = &self.review;
if let Some(diff) = self.diff.as_mut() {
let count = diff.model(review).files.len();
if count == 0 {
return;
}
diff.select(index.min(count - 1), review);
}
}
fn copy_feedback(&mut self, file_only: bool) {
let filter = if file_only {
let Some(path) = self.diff_cursor_path() else {
self.info("no file under the cursor");
return;
};
Some(path)
} else {
None
};
let source = self.active_review_source();
let session = self.review.session_for(&source);
let count = session
.comments
.iter()
.filter(|c| c.status != CommentStatus::Resolved)
.filter(|c| filter.as_deref().is_none_or(|f| c.anchor.file == f))
.count();
let noun = if count == 1 { "comment" } else { "comments" };
if count == 0 {
self.info("no comments to copy");
return;
}
let repo = self
.review
.repo_root
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
let branch = self.head.branch.clone().unwrap_or_else(|| "?".to_owned());
let title = format!("Review feedback — {repo} @ {branch} ({count} {noun})");
let model = self
.diff
.as_ref()
.and_then(|diff| diff.commit_model.as_ref())
.unwrap_or_else(|| self.review.model());
let markdown = feedback::to_markdown(
session,
model,
&FeedbackOptions {
title: &title,
file_filter: filter.as_deref(),
include_resolved: false,
},
);
self.pending_clipboard = Some(markdown);
let scope = if file_only { "file" } else { "all" };
self.info(format!("copied {count} {noun} ({scope})"));
}
fn copy_selection(&mut self) -> bool {
let (text, count) = {
let Some(diff) = self.diff.as_ref() else {
return false;
};
let Some((start, end)) = diff.selection() else {
return false;
};
let model = diff.model(&self.review);
let mut text = String::new();
let mut count = 0;
for row in diff.rows().get(start..=end).into_iter().flatten() {
let DiffRow::Line { file, hunk, line } = row else {
continue;
};
let Some(diff_line) = model
.files
.get(*file)
.and_then(|f| f.hunks.get(*hunk))
.and_then(|h| h.lines.get(*line))
else {
continue;
};
let marker = match diff_line.kind {
LineKind::Added => '+',
LineKind::Deleted => '-',
LineKind::Context => ' ',
};
text.push(marker);
text.push_str(&diff_line.text);
text.push('\n');
count += 1;
}
(text, count)
};
if count == 0 {
return false;
}
self.pending_clipboard = Some(text);
if let Some(diff) = self.diff.as_mut() {
diff.visual_anchor = None;
}
self.info(format!(
"copied {count} line{}",
if count == 1 { "" } else { "s" }
));
true
}
fn copy_file_or_selection(&mut self) {
if !self.copy_selection() {
self.copy_feedback(true);
}
}
}
#[cfg(test)]
mod tests {
use diffler_core::session::CommentStatus;
use super::*;
use crate::app::Screen;
use crate::config::LoadedConfig;
use crate::event::AppEvent;
use crate::test_support::{
Fixture, code_key, ctrl_key, key, standard_fixture, two_hunk_fixture,
};
fn diff_app(fixture: &Fixture) -> App {
let mut app = App::new(fixture.review(), LoadedConfig::default());
app.author = "reviewer".to_owned();
app.open_working_tree_diff(None);
app
}
fn diff_app_with_layout(fixture: &Fixture, layout: crate::config::FileLayout) -> App {
let mut loaded = LoadedConfig::default();
loaded.config.ui.diff_file_layout = layout;
let mut app = App::new(fixture.review(), loaded);
app.author = "reviewer".to_owned();
app.open_working_tree_diff(None);
app
}
fn rows(app: &App) -> Vec<DiffRow> {
app.diff.as_ref().expect("diff view").rows().to_vec()
}
fn focus(app: &App) -> Pane {
app.diff.as_ref().expect("diff view").focus
}
fn selected_path(app: &App) -> String {
app.diff
.as_ref()
.expect("diff view")
.selected_path(&app.review)
.expect("selected file")
}
fn tree_cursor(app: &App) -> usize {
app.diff.as_ref().expect("diff view").tree_cursor
}
fn tree_row_count(app: &App) -> usize {
let diff = app.diff.as_ref().expect("diff view");
sidebar_rows(diff, &app.review).len()
}
fn tree_kinds(app: &App) -> Vec<String> {
let diff = app.diff.as_ref().expect("diff view");
sidebar_rows(diff, &app.review)
.iter()
.map(|row| match &row.node {
crate::tree::TreeNode::Dir { .. } => "dir".to_owned(),
crate::tree::TreeNode::File { name, .. } => format!("file:{name}"),
crate::tree::TreeNode::Section { bucket, count, .. } => {
format!("section:{}:{count}", bucket.label())
}
})
.collect()
}
fn enter_diff_pane(app: &mut App) {
app.diff.as_mut().expect("diff view").focus = Pane::Diff;
}
fn cursor_to_line(app: &mut App, pred: impl Fn(&DiffRow) -> bool) {
let position = rows(app).iter().position(pred).expect("row present");
app.diff.as_mut().unwrap().cursor = position;
}
fn select_file(app: &mut App, path: &str) {
let index = app
.diff
.as_ref()
.unwrap()
.model(&app.review)
.files
.iter()
.position(|f| f.path == path)
.expect("file present");
app.diff_select_file_index(index);
enter_diff_pane(app);
}
fn added_line_position(app: &App) -> usize {
let diff = app.diff.as_ref().unwrap();
let model = diff.model(&app.review);
rows(app)
.iter()
.position(|row| {
let DiffRow::Line { file, hunk, line } = row else {
return false;
};
model.files.get(*file).is_some_and(|f| {
f.path == "src/lib.rs"
&& f.hunks.get(*hunk).is_some_and(|h| {
h.lines
.get(*line)
.is_some_and(|l| l.new_no.is_some() && l.text.contains("42"))
})
})
})
.expect("added line present")
}
fn type_text(app: &mut App, text: &str) {
for c in text.chars() {
app.handle(key(c));
}
}
#[test]
fn rows_flatten_the_selected_files_hunks_and_lines_in_order() {
let fixture = two_hunk_fixture();
let app = diff_app(&fixture);
let rows = rows(&app);
assert!(matches!(rows.first(), Some(DiffRow::Hunk { hunk: 0, .. })));
let hunks: Vec<usize> = rows
.iter()
.filter_map(|r| match r {
DiffRow::Hunk { hunk, .. } => Some(*hunk),
_ => None,
})
.collect();
assert_eq!(hunks, vec![0, 1], "both hunks flattened in order");
assert!(
rows.iter()
.any(|r| matches!(r, DiffRow::Line { hunk: 1, .. })),
"second hunk has line rows"
);
}
#[test]
fn open_starts_on_the_sidebar_at_the_first_file() {
let fixture = standard_fixture();
let app = diff_app(&fixture);
assert_eq!(focus(&app), Pane::List);
assert_eq!(app.diff.as_ref().unwrap().selected, 0);
}
#[test]
fn list_jk_moves_over_tree_rows_and_files_under_the_cursor_become_selected() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
assert_eq!(
tree_kinds(&app),
vec![
"dir".to_owned(),
"file:lib.rs".to_owned(),
"file:ci.yml".to_owned(),
"file:todo.md".to_owned(),
]
);
assert_eq!(tree_cursor(&app), 2);
assert_eq!(selected_path(&app), "ci.yml");
app.handle(key('g'));
app.handle(key('g'));
assert_eq!(tree_cursor(&app), 0);
assert_eq!(selected_path(&app), "ci.yml", "a dir row keeps the pane");
enter_diff_pane(&mut app);
app.handle(key('j'));
assert!(app.diff.as_ref().unwrap().cursor > 0);
app.diff.as_mut().unwrap().focus = Pane::List;
app.handle(key('j'));
assert_eq!(tree_cursor(&app), 1);
assert_eq!(selected_path(&app), "src/lib.rs");
assert_eq!(app.diff.as_ref().unwrap().cursor, 0, "diff cursor reset");
assert_eq!(app.diff.as_ref().unwrap().scroll, 0);
app.handle(key('j'));
assert_eq!(selected_path(&app), "ci.yml");
app.handle(key('k'));
assert_eq!(selected_path(&app), "src/lib.rs");
}
#[test]
fn the_default_sidebar_layout_is_a_tree_with_dir_rows() {
let fixture = standard_fixture();
let app = diff_app(&fixture);
assert_eq!(
tree_kinds(&app),
vec![
"dir".to_owned(),
"file:lib.rs".to_owned(),
"file:ci.yml".to_owned(),
"file:todo.md".to_owned(),
]
);
}
#[test]
fn gg_and_g_jump_to_the_first_and_last_visible_row() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
let last = tree_row_count(&app) - 1;
app.handle(key('G'));
assert_eq!(tree_cursor(&app), last);
assert_eq!(selected_path(&app), "todo.md");
app.handle(key('g'));
app.handle(key('g'));
assert_eq!(tree_cursor(&app), 0, "back to the first visible row");
}
#[test]
fn folding_a_dir_hides_its_subtree_and_unfolding_restores_it() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
app.handle(key('g'));
app.handle(key('g'));
assert_eq!(tree_kinds(&app).len(), 4);
app.handle(key('z'));
app.handle(key('a'));
assert_eq!(
tree_kinds(&app),
vec![
"dir".to_owned(),
"file:ci.yml".to_owned(),
"file:todo.md".to_owned(),
],
"folded src/ hides lib.rs"
);
app.handle(key('\n'));
assert_eq!(
tree_kinds(&app).len(),
4,
"unfolded src/ shows lib.rs again"
);
}
#[test]
fn cr_on_a_file_row_focuses_the_diff_pane() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
assert!(matches!(
tree_kinds(&app).get(tree_cursor(&app)).map(String::as_str),
Some("file:ci.yml")
));
app.handle(key('\n'));
assert_eq!(focus(&app), Pane::Diff);
}
#[test]
fn h_and_l_focus_the_panes_and_clamp() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
assert_eq!(focus(&app), Pane::List);
app.handle(key('l'));
assert_eq!(focus(&app), Pane::Diff);
app.handle(key('l'));
assert_eq!(
focus(&app),
Pane::Diff,
"repeats stay on the diff, no cycle"
);
app.handle(key('h'));
assert_eq!(focus(&app), Pane::List);
app.handle(key('h'));
assert_eq!(
focus(&app),
Pane::List,
"repeats stay on the sidebar, no cycle"
);
}
#[test]
fn arrow_keys_focus_the_panes_like_h_and_l() {
use crossterm::event::KeyCode;
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
app.handle(code_key(KeyCode::Right));
assert_eq!(focus(&app), Pane::Diff);
app.handle(code_key(KeyCode::Left));
assert_eq!(focus(&app), Pane::List);
}
#[test]
fn tab_and_backtab_step_through_files_keeping_focus() {
use crossterm::event::KeyCode;
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
let first = selected_path(&app);
app.handle(key('\t'));
let second = selected_path(&app);
assert_ne!(first, second, "tab advances to the next file");
assert_eq!(focus(&app), Pane::List, "stepping files keeps focus");
app.handle(code_key(KeyCode::BackTab));
assert_eq!(selected_path(&app), first, "shift-tab steps back");
}
#[test]
fn cr_from_the_list_focuses_the_diff_and_cr_back_returns() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
app.handle(key('\n'));
assert_eq!(focus(&app), Pane::Diff);
app.handle(key('\n'));
assert_eq!(focus(&app), Pane::List);
}
#[test]
fn ctrl_n_switches_the_selected_file_from_the_diff_pane_keeping_focus() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
enter_diff_pane(&mut app);
let first = selected_path(&app);
app.handle(ctrl_key('n'));
assert_eq!(focus(&app), Pane::Diff, "focus stays on the diff");
assert_ne!(selected_path(&app), first, "selection advanced");
app.handle(ctrl_key('p'));
assert_eq!(selected_path(&app), first);
}
#[test]
fn ctrl_n_and_ctrl_p_walk_only_file_rows_skipping_directories() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
app.handle(key('g'));
app.handle(key('g'));
assert!(matches!(
tree_kinds(&app).get(tree_cursor(&app)).map(String::as_str),
Some("dir")
));
app.handle(ctrl_key('n'));
assert_eq!(selected_path(&app), "src/lib.rs");
let mut visited = vec![selected_path(&app)];
for _ in 0..2 {
app.handle(ctrl_key('n'));
assert!(matches!(
tree_kinds(&app).get(tree_cursor(&app)).map(String::as_str),
Some(kind) if kind.starts_with("file:")
));
visited.push(selected_path(&app));
}
assert_eq!(visited, vec!["src/lib.rs", "ci.yml", "todo.md"]);
app.handle(ctrl_key('p'));
assert_eq!(selected_path(&app), "ci.yml");
}
#[test]
fn bracket_keys_walk_between_comments() {
let fixture = two_hunk_fixture();
let mut app = App::new(fixture.review(), LoadedConfig::default());
let anchor = |line: u32| Anchor {
file: "data.txt".to_owned(),
line: Some(line),
line_end: None,
on_old_side: false,
line_text: None,
};
app.review.session.add_comment(anchor(1), "r", "first");
app.review.session.add_comment(anchor(20), "r", "second");
app.open_working_tree_diff(None);
{
let diff = app.diff.as_mut().unwrap();
diff.focus = Pane::Diff;
diff.cursor = 0;
diff.invalidate();
}
app.diff.as_mut().unwrap().ensure_rows(&app.review);
let on_header = |app: &App| {
let diff = app.diff.as_ref().unwrap();
matches!(
diff.rows().get(diff.cursor),
Some(DiffRow::Comment { line: 0, .. })
)
};
app.handle(key(']'));
assert!(on_header(&app), "] lands on a comment header");
let first = app.diff.as_ref().unwrap().cursor;
app.handle(key(']'));
assert!(on_header(&app));
let second = app.diff.as_ref().unwrap().cursor;
assert!(second > first, "] advances to the next comment");
app.handle(key('['));
assert_eq!(
app.diff.as_ref().unwrap().cursor,
first,
"[ returns to the previous comment"
);
}
#[test]
fn comment_rows_appear_under_their_anchored_line() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
select_file(&mut app, "src/lib.rs");
let position = added_line_position(&app);
app.diff.as_mut().unwrap().cursor = position;
app.handle(key('c'));
assert!(matches!(app.modal, Some(Modal::Input { .. })));
type_text(&mut app, "why 42?");
app.handle(key('\n'));
assert_eq!(app.modal, None);
let comment = &app.review.session.comments[0];
assert_eq!(comment.author, "reviewer");
assert_eq!(comment.body, "why 42?");
assert_eq!(comment.anchor.file, "src/lib.rs");
assert_eq!(comment.anchor.line, Some(2));
assert!(!comment.anchor.on_old_side);
assert_eq!(comment.anchor.line_text.as_deref(), Some(" 42"));
let diff = app.diff.as_mut().unwrap();
diff.ensure_rows(&app.review);
let rows = rows(&app);
let line_position = added_line_position(&app);
let block: Vec<_> = rows
.iter()
.skip(line_position + 1)
.take_while(|r| matches!(r, DiffRow::Comment { .. }))
.collect();
assert_eq!(
block.len(),
3,
"comment block right under the line: {rows:?}"
);
assert!(block.iter().all(|r| matches!(
r,
DiffRow::Comment {
outdated: false,
..
}
)));
}
#[test]
fn outdated_comment_is_flagged_when_the_line_text_drifts() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
select_file(&mut app, "src/lib.rs");
app.review.session.add_comment(
Anchor {
file: "src/lib.rs".to_owned(),
line: Some(2),
line_end: None,
on_old_side: false,
line_text: Some(" 43".to_owned()),
},
"reviewer",
"stale snapshot",
);
let diff = app.diff.as_mut().unwrap();
diff.invalidate();
diff.ensure_rows(&app.review);
assert!(
rows(&app)
.iter()
.any(|r| matches!(r, DiffRow::Comment { outdated: true, .. })),
"drifted line_text flags the comment outdated"
);
}
#[test]
fn comment_for_a_departed_line_attaches_at_the_top() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
select_file(&mut app, "src/lib.rs");
app.review.session.add_comment(
Anchor {
file: "src/lib.rs".to_owned(),
line: Some(99),
line_end: None,
on_old_side: false,
line_text: None,
},
"reviewer",
"moved on",
);
let diff = app.diff.as_mut().unwrap();
diff.invalidate();
diff.ensure_rows(&app.review);
let rows = rows(&app);
assert!(
matches!(rows.first(), Some(DiffRow::Comment { outdated: true, .. })),
"orphaned comment sits at the top, flagged outdated: {rows:?}"
);
}
#[test]
fn scoped_open_selects_the_file_and_focuses_the_diff() {
let fixture = standard_fixture();
let mut app = App::new(fixture.review(), LoadedConfig::default());
app.open_working_tree_file("src/lib.rs");
assert_eq!(focus(&app), Pane::Diff);
assert_eq!(selected_path(&app), "src/lib.rs");
assert_eq!(app.diff.as_ref().unwrap().cursor, 0, "starts at the top");
}
#[test]
fn visual_selection_comments_a_new_side_range() {
let fixture = two_hunk_fixture();
let mut app = diff_app(&fixture);
enter_diff_pane(&mut app);
cursor_to_line(&mut app, |r| {
matches!(
r,
DiffRow::Line {
hunk: 0,
line: 1,
..
}
)
});
app.handle(key('V'));
assert!(app.diff.as_ref().unwrap().visual_anchor.is_some());
app.handle(key('j'));
app.handle(key('j'));
app.handle(key('c'));
type_text(&mut app, "this block");
app.handle(key('\n'));
let comment = &app.review.session.comments[0];
assert_eq!(comment.anchor.line, Some(1));
assert_eq!(comment.anchor.line_end, Some(3));
assert!(!comment.anchor.on_old_side);
assert_eq!(comment.anchor.line_text.as_deref(), Some("line 3"));
assert!(
app.diff.as_ref().unwrap().visual_anchor.is_none(),
"selection ends once the comment lands"
);
}
#[test]
fn visual_selection_anchored_on_a_deleted_line_uses_the_old_side() {
let fixture = two_hunk_fixture();
let mut app = diff_app(&fixture);
enter_diff_pane(&mut app);
cursor_to_line(&mut app, |r| {
matches!(
r,
DiffRow::Line {
hunk: 0,
line: 0,
..
}
)
});
app.handle(key('V'));
app.handle(key('j'));
app.handle(key('j'));
app.handle(key('c'));
type_text(&mut app, "old side");
app.handle(key('\n'));
let comment = &app.review.session.comments[0];
assert!(comment.anchor.on_old_side);
assert_eq!(comment.anchor.line, Some(1));
assert_eq!(comment.anchor.line_end, Some(2));
}
#[test]
fn escape_cancels_visual_selection() {
let fixture = two_hunk_fixture();
let mut app = diff_app(&fixture);
enter_diff_pane(&mut app);
cursor_to_line(&mut app, |r| matches!(r, DiffRow::Line { .. }));
app.handle(key('V'));
assert!(app.diff.as_ref().unwrap().visual_anchor.is_some());
app.handle(AppEvent::Key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Esc,
crossterm::event::KeyModifiers::NONE,
)));
assert!(app.diff.as_ref().unwrap().visual_anchor.is_none());
app.handle(key('V'));
app.handle(key('V'));
assert!(app.diff.as_ref().unwrap().visual_anchor.is_none());
}
#[test]
fn reply_and_resolve_walk_the_comment_lifecycle() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
select_file(&mut app, "src/lib.rs");
let position = added_line_position(&app);
app.diff.as_mut().unwrap().cursor = position;
app.handle(key('c'));
type_text(&mut app, "question");
app.handle(key('\n'));
let position = added_line_position(&app);
app.diff.as_mut().unwrap().cursor = position + 1;
app.handle(key('r'));
assert!(matches!(app.modal, Some(Modal::Input { .. })));
type_text(&mut app, "answer");
app.handle(key('\n'));
let comment = &app.review.session.comments[0];
assert_eq!(comment.status, CommentStatus::Replied);
assert_eq!(comment.replies.len(), 1);
assert_eq!(comment.replies[0].body, "answer");
let position = added_line_position(&app);
app.diff.as_mut().unwrap().cursor = position + 1;
app.handle(key('R'));
assert_eq!(
app.review.session.comments[0].status,
CommentStatus::Resolved
);
let reloaded = diffler_core::store::load(&fixture.root).unwrap();
assert_eq!(reloaded.comments[0].status, CommentStatus::Resolved);
}
#[test]
fn c_over_a_comment_edits_it() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
select_file(&mut app, "src/lib.rs");
let position = added_line_position(&app);
app.diff.as_mut().unwrap().cursor = position;
app.handle(key('c'));
type_text(&mut app, "old note");
app.handle(key('\n'));
app.diff.as_mut().unwrap().cursor = added_line_position(&app) + 1;
app.handle(key('c'));
let Some(Modal::Input { buffer, .. }) = &app.modal else {
panic!("edit modal with the current body");
};
assert_eq!(buffer, "old note", "prefilled with the existing body");
for _ in 0.."old note".len() {
app.handle(crate::test_support::key_backspace());
}
type_text(&mut app, "new note");
app.handle(key('\n'));
assert_eq!(app.review.session.comments.len(), 1, "edited, not added");
assert_eq!(app.review.session.comments[0].body, "new note");
}
#[test]
fn reply_off_a_comment_row_hints() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
enter_diff_pane(&mut app);
app.handle(key('r'));
let message = app.message.expect("message");
assert!(message.text.contains("comment"));
}
#[test]
fn c_in_the_file_list_comments_on_the_whole_file() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
assert_eq!(focus(&app), Pane::List);
app.handle(key('c'));
assert!(
matches!(app.modal, Some(Modal::Input { .. })),
"c on a file opens a comment, not a hint"
);
type_text(&mut app, "whole-file note");
app.handle(key('\n'));
let comment = app.review.session.comments.first().expect("a file comment");
assert_eq!(comment.anchor.line, None, "file-level anchor (no line)");
assert!(comment.body.contains("whole-file note"));
}
#[test]
fn line_scoped_keys_in_the_list_hint_to_move_into_the_diff() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
assert_eq!(focus(&app), Pane::List);
app.handle(key('r')); let message = app.message.expect("message");
assert!(message.text.contains("move into the diff"));
}
#[test]
fn marking_viewed_advances_selection_to_the_next_unviewed_file() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
let paths: Vec<String> = app
.review
.model()
.files
.iter()
.map(|f| f.path.clone())
.collect();
assert_eq!(paths.len(), 3, "walk needs several files: {paths:?}");
app.handle(key('v'));
assert!(app.is_path_viewed(&paths[0]));
assert_eq!(selected_path(&app), paths[1]);
app.handle(key('v'));
assert_eq!(selected_path(&app), paths[2]);
app.handle(key('v'));
assert!(paths.iter().all(|p| app.is_path_viewed(p)));
assert_eq!(
selected_path(&app),
paths[2],
"no unviewed file below: selection stays"
);
}
#[test]
fn capital_u_clears_all_viewed_marks() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
let paths: Vec<String> = app
.review
.model()
.files
.iter()
.map(|f| f.path.clone())
.collect();
for _ in &paths {
app.handle(key('v'));
}
assert!(
paths.iter().all(|p| app.is_path_viewed(p)),
"all marked first"
);
app.handle(key('U'));
assert!(
paths.iter().all(|p| !app.is_path_viewed(p)),
"U cleared every viewed mark"
);
}
#[test]
fn unmarking_viewed_does_not_move_the_selection() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
let first = selected_path(&app);
assert_eq!(first, "ci.yml");
app.handle(key('v'));
assert_eq!(selected_path(&app), "src/lib.rs");
app.handle(key('j'));
assert_eq!(selected_path(&app), first);
app.handle(key('v'));
assert!(!app.is_path_viewed(&first));
assert_eq!(
selected_path(&app),
first,
"unmarking keeps the selection in place"
);
}
#[test]
fn viewed_can_be_marked_from_the_diff_pane() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
let first = selected_path(&app);
enter_diff_pane(&mut app);
app.handle(key('v'));
assert!(app.is_path_viewed(&first));
assert_ne!(selected_path(&app), first);
}
#[test]
fn review_layout_buckets_files_with_the_viewed_pile_folded() {
let fixture = standard_fixture();
let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Review);
assert_eq!(
tree_kinds(&app),
[
"section:To review:3",
"file:ci.yml",
"file:src/lib.rs",
"file:todo.md",
"section:Viewed:0",
]
);
app.handle(key('v'));
assert_eq!(
tree_kinds(&app),
[
"section:To review:2",
"file:src/lib.rs",
"file:todo.md",
"section:Viewed:1",
]
);
assert_eq!(selected_path(&app), "src/lib.rs");
}
#[test]
fn toggling_the_viewed_bucket_reveals_and_hides_its_files() {
let fixture = standard_fixture();
let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Review);
app.handle(key('v'));
app.handle(key('G'));
app.handle(key('z'));
app.handle(key('a'));
assert_eq!(
tree_kinds(&app),
[
"section:To review:2",
"file:src/lib.rs",
"file:todo.md",
"section:Viewed:1",
"file:ci.yml",
]
);
app.handle(key('\n'));
assert_eq!(
tree_kinds(&app).last().map(String::as_str),
Some("section:Viewed:1")
);
}
#[test]
fn editing_a_viewed_file_returns_it_to_the_to_review_bucket() {
let fixture = standard_fixture();
let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Review);
app.handle(key('v'));
assert_eq!(tree_kinds(&app)[0], "section:To review:2");
fixture.write("ci.yml", "on: push\njobs: {}\n");
app.handle(AppEvent::RepoChanged);
app.settle_refresh();
assert_eq!(
tree_kinds(&app)[0],
"section:To review:3",
"stale viewed mark drops the file back into to-review"
);
}
#[test]
fn t_cycles_the_sidebar_between_the_tree_and_the_review_buckets() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
assert!(tree_kinds(&app).contains(&"dir".to_owned()));
app.handle(key('t'));
assert_eq!(tree_kinds(&app)[0], "section:To review:3");
app.handle(key('t'));
assert!(
tree_kinds(&app).contains(&"dir".to_owned()),
"wraps back to the tree"
);
}
#[test]
fn unmarking_in_the_review_layout_reseats_the_cursor_on_the_moved_row() {
let fixture = standard_fixture();
let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Review);
app.handle(key('v'));
app.handle(key('v'));
app.handle(key('v'));
app.handle(key('G'));
app.handle(key('z'));
app.handle(key('a'));
app.handle(key('j'));
assert_eq!(selected_path(&app), "ci.yml");
app.handle(key('v'));
assert_eq!(
tree_kinds(&app),
[
"section:To review:1",
"file:ci.yml",
"section:Viewed:2",
"file:src/lib.rs",
"file:todo.md",
]
);
assert_eq!(tree_cursor(&app), 1, "cursor sits on the moved file row");
}
#[test]
fn marking_the_last_unviewed_file_keeps_the_cursor_in_range() {
let fixture = standard_fixture();
let mut app = diff_app_with_layout(&fixture, crate::config::FileLayout::Review);
app.handle(key('v'));
app.handle(key('v'));
app.handle(key('G'));
app.handle(key('v'));
let rows = tree_row_count(&app);
assert_eq!(rows, 2, "both buckets, all files folded away");
assert!(
tree_cursor(&app) < rows,
"cursor clamps into the shrunken row list"
);
}
#[test]
fn cycling_the_sidebar_layout_drops_a_committed_search() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
app.handle(key('/'));
app.handle(key('l'));
app.handle(key('\n'));
assert!(app.search.is_some(), "search committed on the tree rows");
app.handle(key('t'));
assert!(
app.search.is_none(),
"layout swap invalidates the search row indices"
);
}
#[test]
fn u_jumps_to_the_next_unviewed_file_wrapping_past_viewed_ones() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
app.handle(key('v')); select_file(&mut app, "todo.md");
app.handle(key('u'));
assert_eq!(
selected_path(&app),
"src/lib.rs",
"wraps past the viewed ci.yml"
);
}
#[test]
fn u_with_everything_viewed_says_so() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
app.handle(key('v'));
app.handle(key('v'));
app.handle(key('v'));
let before = selected_path(&app);
app.handle(key('u'));
assert_eq!(selected_path(&app), before);
let message = app.message.expect("message");
assert!(message.text.contains("every file is viewed"));
}
#[test]
fn y_copies_the_selected_files_feedback_as_markdown() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
select_file(&mut app, "src/lib.rs");
let position = added_line_position(&app);
app.diff.as_mut().unwrap().cursor = position;
app.handle(key('c'));
type_text(&mut app, "why 42?");
app.handle(key('\n'));
app.review.session.add_comment(
Anchor {
file: "todo.md".to_owned(),
line: None,
line_end: None,
on_old_side: false,
line_text: None,
},
"reviewer",
"other file",
);
select_file(&mut app, "src/lib.rs");
app.diff.as_mut().unwrap().cursor = added_line_position(&app);
app.handle(key('y'));
let payload = app
.pending_clipboard
.clone()
.expect("clipboard text queued");
let toast = app.message.clone().expect("toast");
assert_eq!(toast.text, "copied 1 comment (file)");
let repo = fixture.root.file_name().unwrap().to_string_lossy();
let expected = feedback::to_markdown(
&app.review.session,
app.review.model(),
&FeedbackOptions {
title: &format!("Review feedback — {repo} @ main (1 comment)"),
file_filter: Some("src/lib.rs"),
include_resolved: false,
},
);
assert!(expected.contains("why 42?"));
assert!(!expected.contains("other file"), "file filter applies");
assert_eq!(payload, expected);
app.handle(key('Y'));
let message = app.message.clone().expect("toast");
assert_eq!(message.text, "copied 2 comments (all)");
}
#[test]
fn y_with_a_visual_selection_copies_the_diff_lines() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
select_file(&mut app, "src/lib.rs");
app.diff.as_mut().unwrap().cursor = added_line_position(&app);
app.handle(key('V'));
app.handle(key('y'));
let text = app
.pending_clipboard
.clone()
.expect("selection copied to the clipboard");
assert!(
text.starts_with('+'),
"added line keeps its marker: {text:?}"
);
assert!(text.contains("42"), "the line text is copied: {text:?}");
assert!(
!text.contains(" 1 "),
"gutter line numbers are stripped: {text:?}"
);
assert_eq!(
app.diff.as_ref().unwrap().visual_anchor,
None,
"the selection clears after copying"
);
}
#[test]
fn y_with_no_comments_hints_instead_of_copying() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
app.handle(key('y'));
assert_eq!(app.pending_clipboard, None);
let message = app.message.expect("message");
assert!(message.text.contains("no comments"));
}
#[test]
fn e_on_a_diff_line_opens_the_editor_at_that_line() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
app.config.editor.command = Some("vim".to_owned());
select_file(&mut app, "src/lib.rs");
let position = added_line_position(&app);
app.diff.as_mut().unwrap().cursor = position;
app.handle(key('e'));
let request = app.pending_editor.clone().expect("editor request");
assert_eq!(
request.purpose,
crate::editor::EditorPurpose::OpenFile {
path: "src/lib.rs".to_owned(),
}
);
let absolute = fixture.root.join("src/lib.rs");
assert_eq!(
request.cmd,
vec![
"vim".to_owned(),
"+2".to_owned(),
absolute.to_string_lossy().into_owned(),
]
);
}
#[test]
fn e_from_the_list_opens_the_selected_file_without_a_line() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
app.config.editor.command = Some("vim".to_owned());
assert_eq!(focus(&app), Pane::List);
app.handle(key('e'));
let request = app.pending_editor.clone().expect("editor request");
assert!(
request.cmd.iter().all(|arg| !arg.starts_with('+')),
"no line jump from the list: {:?}",
request.cmd
);
}
#[test]
fn half_page_motions_move_by_the_viewport() {
let fixture = two_hunk_fixture();
let mut app = diff_app(&fixture);
enter_diff_pane(&mut app);
app.diff.as_mut().unwrap().viewport = 10;
app.handle(ctrl_key('d'));
assert_eq!(app.diff.as_ref().unwrap().cursor, 5);
app.handle(ctrl_key('u'));
assert_eq!(app.diff.as_ref().unwrap().cursor, 0);
}
#[test]
fn list_focus_half_page_scrolls_the_diff_pane_keeping_the_selection() {
let fixture = two_hunk_fixture();
let mut app = diff_app(&fixture);
assert_eq!(focus(&app), Pane::List);
let selected_before = selected_path(&app);
let tree_before = tree_cursor(&app);
app.diff.as_mut().unwrap().viewport = 10;
assert_eq!(app.diff.as_ref().unwrap().cursor, 0);
app.handle(ctrl_key('d'));
assert_eq!(app.diff.as_ref().unwrap().cursor, 5);
assert_eq!(selected_path(&app), selected_before);
assert_eq!(tree_cursor(&app), tree_before);
assert_eq!(focus(&app), Pane::List, "focus stays on the sidebar");
app.handle(ctrl_key('u'));
assert_eq!(app.diff.as_ref().unwrap().cursor, 0);
assert_eq!(selected_path(&app), selected_before);
}
#[test]
fn hunk_jumps_move_between_headers() {
let fixture = two_hunk_fixture();
let mut app = diff_app(&fixture);
enter_diff_pane(&mut app);
let first = app.diff.as_ref().unwrap().cursor;
assert!(matches!(rows(&app)[first], DiffRow::Hunk { hunk: 0, .. }));
app.handle(key('}'));
assert!(matches!(
rows(&app)[app.diff.as_ref().unwrap().cursor],
DiffRow::Hunk { hunk: 1, .. }
));
app.handle(key('{'));
assert_eq!(app.diff.as_ref().unwrap().cursor, first);
}
#[test]
fn noop_refresh_preserves_the_visual_selection() {
let fixture = two_hunk_fixture();
let mut app = diff_app(&fixture);
enter_diff_pane(&mut app);
cursor_to_line(&mut app, |r| matches!(r, DiffRow::Line { .. }));
app.handle(key('V'));
assert!(app.diff.as_ref().unwrap().visual_anchor.is_some());
app.handle(AppEvent::RepoChanged);
app.settle_refresh();
assert!(
app.diff.as_ref().unwrap().visual_anchor.is_some(),
"no-op refresh keeps the selection"
);
}
#[test]
fn real_change_refresh_clears_the_visual_selection() {
let fixture = two_hunk_fixture();
let mut app = diff_app(&fixture);
enter_diff_pane(&mut app);
cursor_to_line(&mut app, |r| matches!(r, DiffRow::Line { .. }));
app.handle(key('V'));
fixture.write("zzz.md", "new\n");
app.handle(AppEvent::RepoChanged);
app.settle_refresh();
assert!(
app.diff.as_ref().unwrap().visual_anchor.is_none(),
"rows shifted: a stale anchor would dangle"
);
}
#[test]
fn refresh_keeps_the_selected_file_by_path_when_files_shift() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
select_file(&mut app, "src/lib.rs");
let path = selected_path(&app);
fixture.write("aaa.rs", "fn nope() {}\n");
app.handle(ctrl_key('r'));
assert_eq!(
selected_path(&app),
path,
"selection follows its file across the refresh"
);
}
#[test]
fn commit_diff_survives_refresh_untouched() {
let fixture = standard_fixture();
let mut app = App::new(fixture.review(), LoadedConfig::default());
let oid = app.status.recent[0].oid.clone();
app.open_commit_diff(&oid);
assert_eq!(app.screen(), Screen::Diff);
let before = rows(&app).len();
fixture.write("zzz.md", "new\n");
app.handle(ctrl_key('r'));
assert_eq!(rows(&app).len(), before, "commit model is immutable");
}
#[test]
fn viewed_on_a_commit_diff_persists_to_that_source_not_the_working_tree() {
let fixture = standard_fixture();
let mut app = App::new(fixture.review(), LoadedConfig::default());
let oid = app.status.recent[0].oid.clone();
app.open_commit_diff(&oid);
let path = selected_path(&app);
app.handle(key('v'));
let source = ReviewSource::commit(&oid);
assert!(
app.review.session_for(&source).viewed.contains_key(&path),
"viewed mark lands on the commit source"
);
assert!(
app.review.session.viewed.is_empty(),
"the working-tree session is untouched"
);
let mut reopened = App::new(fixture.review(), LoadedConfig::default());
reopened.open_commit_diff(&oid);
assert!(
reopened
.review
.session_for(&source)
.viewed
.contains_key(&path)
);
}
#[test]
fn yank_and_editor_on_a_commit_diff_use_that_sources_comments() {
let fixture = standard_fixture();
let mut app = App::new(fixture.review(), LoadedConfig::default());
app.review.session.add_comment(
diffler_core::session::Anchor {
file: "todo.md".into(),
line: Some(1),
line_end: None,
on_old_side: false,
line_text: None,
},
"reviewer",
"working-tree decoy",
);
let oid = app.status.recent[0].oid.clone();
app.open_commit_diff(&oid);
select_file(&mut app, "src/lib.rs");
let line_row = rows(&app)
.iter()
.position(|row| matches!(row, DiffRow::Line { .. }))
.expect("a diff line in the commit");
app.diff.as_mut().unwrap().focus = Pane::Diff;
app.diff.as_mut().unwrap().cursor = line_row;
app.handle(key('c'));
type_text(&mut app, "commit note");
app.handle(key('\n'));
app.handle(key('Y'));
let markdown = app.pending_clipboard.take().expect("yanked feedback");
assert!(markdown.contains("commit note"), "commit comment exported");
assert!(
!markdown.contains("working-tree decoy"),
"working-tree comments stay out of a commit yank"
);
let comment_row = rows(&app)
.iter()
.position(|row| matches!(row, DiffRow::Comment { .. }))
.expect("comment row present");
app.diff.as_mut().unwrap().cursor = comment_row;
app.handle(key('e'));
let request = app.pending_editor.take().expect("editor request");
let argv = request.cmd.join(" ");
assert!(
argv.contains("src/lib.rs") && !argv.contains("todo.md"),
"editor resolves the commit comment, not the working-tree one: {argv}"
);
}
#[test]
fn comment_display_lines_cover_body_and_replies() {
let mut session = Session::default();
let id = session
.add_comment(
Anchor {
file: "a.rs".to_owned(),
line: Some(1),
line_end: None,
on_old_side: false,
line_text: None,
},
"reviewer",
"first\nsecond",
)
.id
.clone();
session.reply(&id, "agent", "done\nand verified");
let lines = comment_display(&session.comments[0], u16::MAX, None);
let plain = |s: &str| MdSpan {
text: s.to_owned(),
..MdSpan::default()
};
assert_eq!(
lines,
vec![
CommentLine::Header,
CommentLine::Body(vec![plain("first")]),
CommentLine::Body(vec![plain("second")]),
CommentLine::Reply {
author: "agent".to_owned(),
spans: vec![plain("done")],
first: true,
},
CommentLine::Reply {
author: "agent".to_owned(),
spans: vec![plain("and verified")],
first: false,
},
CommentLine::Footer,
]
);
}
#[test]
fn comment_display_wraps_long_text_to_the_pane_width() {
let mut session = Session::default();
let id = session
.add_comment(
Anchor {
file: "a.rs".to_owned(),
line: Some(1),
line_end: None,
on_old_side: false,
line_text: None,
},
"reviewer",
"a body long enough that it cannot fit on one row",
)
.id
.clone();
session.reply(&id, "agent", "a reply that also runs past the pane");
let lines = comment_display(&session.comments[0], 30, None);
let budget = 30 - 4;
let text = |runs: &[MdSpan]| runs.iter().map(|s| s.text.clone()).collect::<String>();
for line in &lines {
match line {
CommentLine::Body(runs) => assert!(text(runs).width() <= budget, "{runs:?}"),
CommentLine::Reply { spans, first, .. } => {
let head = if *first { "↳ agent: ".width() } else { 2 };
assert!(text(spans).width() + head <= budget, "{spans:?}");
}
_ => {}
}
}
let bodies = lines
.iter()
.filter(|l| matches!(l, CommentLine::Body(_)))
.count();
assert!(bodies > 1, "the long body wrapped onto several rows");
let joined: Vec<String> = lines
.iter()
.filter_map(|l| match l {
CommentLine::Body(runs) => Some(text(runs)),
_ => None,
})
.collect();
assert_eq!(
joined.join(" "),
"a body long enough that it cannot fit on one row"
);
}
#[test]
fn comment_display_hard_splits_an_unbreakable_token() {
let mut session = Session::default();
session.add_comment(
Anchor {
file: "a.rs".to_owned(),
line: Some(1),
line_end: None,
on_old_side: false,
line_text: None,
},
"reviewer",
"https://example.invalid/a/very/long/unbroken/path/segment/thing",
);
let lines = comment_display(&session.comments[0], 24, None);
for line in &lines {
if let CommentLine::Body(runs) = line {
let width: usize = runs.iter().map(|s| s.text.width()).sum();
assert!(width <= 20, "{runs:?}");
}
}
}
#[test]
fn deleting_a_comment_asks_for_confirmation_first() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
select_file(&mut app, "src/lib.rs");
app.diff.as_mut().unwrap().cursor = added_line_position(&app);
app.handle(key('c'));
type_text(&mut app, "why 42?");
app.handle(key('\n'));
let diff = app.diff.as_mut().unwrap();
diff.ensure_rows(&app.review);
let comment_row = rows(&app)
.iter()
.position(|r| matches!(r, DiffRow::Comment { .. }))
.expect("comment row present");
app.diff.as_mut().unwrap().cursor = comment_row;
app.delete_comment_at_cursor();
assert!(
matches!(app.modal, Some(Modal::Confirm { .. })),
"delete asks first"
);
assert_eq!(
app.review.session.comments.len(),
1,
"nothing deleted before confirming"
);
app.confirm_modal();
assert_eq!(
app.review.session.comments.len(),
0,
"confirm deletes the comment"
);
}
#[test]
fn build_split_rows_aligns_old_and_new_sides() {
let fixture = standard_fixture();
let app = diff_app(&fixture);
let diff = app.diff.as_ref().unwrap();
let model = diff.model(&app.review);
let session = app.review.session_for(&ReviewSource::WorkingTree);
for (index, file) in model.files.iter().enumerate() {
for row in build_split_rows(model, session, index, u16::MAX) {
let SplitRow::Pair { hunk, left, right } = row else {
continue;
};
assert!(left.is_some() || right.is_some(), "a pair fills a side");
let lines = &file.hunks[hunk].lines;
if let Some(l) = left {
assert!(matches!(
lines[l].kind,
LineKind::Deleted | LineKind::Context
));
}
if let Some(r) = right {
assert!(matches!(lines[r].kind, LineKind::Added | LineKind::Context));
}
if left == right {
assert!(matches!(lines[left.unwrap()].kind, LineKind::Context));
}
}
}
}
#[test]
fn toggle_side_by_side_flips_the_mode() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
app.diff.as_mut().unwrap().focus = Pane::Diff;
assert!(!app.diff.as_ref().unwrap().side_by_side);
app.handle(key('|'));
assert!(app.diff.as_ref().unwrap().side_by_side);
app.handle(key('|'));
assert!(!app.diff.as_ref().unwrap().side_by_side);
}
#[test]
fn commenting_in_side_by_side_is_redirected_to_unified() {
let fixture = standard_fixture();
let mut app = diff_app(&fixture);
let diff = app.diff.as_mut().unwrap();
diff.focus = Pane::Diff;
diff.side_by_side = true;
app.handle(key('c'));
assert!(app.modal.is_none(), "no comment modal opens in split mode");
assert!(
app.message
.as_ref()
.is_some_and(|m| m.text.contains("unified")),
"the message points to the unified view"
);
}
#[test]
fn paren_jumps_land_on_definition_starts() {
use crate::test_support::standard_fixture;
let fixture = standard_fixture();
fixture.write(
"src/lib.rs",
"pub fn answer() -> u32 {\n 42\n}\n\npub fn other() -> u32 {\n 7\n}\n",
);
let mut app =
crate::app::App::new(fixture.review(), crate::config::LoadedConfig::default());
app.open_working_tree_diff(Some("src/lib.rs"));
let (path, content) = ("src/lib.rs".to_owned(), fixture_content(&app));
let index = app.highlighter.scope_index(&path, &content);
assert!(!index.is_empty(), "rust definitions indexed");
let hash = current_hash(&app);
if let Some(diff) = app.diff.as_mut() {
diff.scopes
.insert(path, crate::app::diff::FileScope { hash, index });
diff.ensure_rows(&app.review);
diff.focus = Pane::Diff;
}
app.handle(crate::test_support::key(')'));
let diff = app.diff.as_ref().expect("diff");
let on_def = matches!(
diff.rows().get(diff.cursor),
Some(DiffRow::Line { file, hunk, line })
if app.review.model().files.get(*file)
.and_then(|f| f.hunks.get(*hunk))
.and_then(|h| h.lines.get(*line))
.is_some_and(|l| l.text.contains("fn "))
);
assert!(on_def, "cursor row {} is a definition line", diff.cursor);
}
fn against_paths(app: &App) -> Vec<String> {
app.diff
.as_ref()
.and_then(|diff| diff.commit_model.as_ref())
.expect("pinned model")
.files
.iter()
.map(|f| f.path.clone())
.collect()
}
fn against_main(fixture: &Fixture) -> App {
let mut app = App::new(fixture.review(), LoadedConfig::default());
app.handle(key('d'));
app.handle(key('d'));
app
}
#[test]
fn the_diff_transient_reviews_the_branch_against_its_base() {
let fixture = crate::test_support::branch_fixture();
let app = against_main(&fixture);
let diff = app.diff.as_ref().expect("diff view");
assert_eq!(diff.source, ReviewSource::against("main"));
assert_eq!(app.against_rev(), Some("main"));
assert_eq!(against_paths(&app), ["dirty.rs", "landed.rs"]);
assert_eq!(app.screen(), Screen::Diff);
}
#[test]
fn an_against_review_tracks_edits_through_the_refresh() {
let fixture = crate::test_support::branch_fixture();
let mut app = against_main(&fixture);
fixture.write("later.rs", "pub fn later() {}\n");
app.queue_refresh();
app.settle_refresh();
assert_eq!(against_paths(&app), ["dirty.rs", "landed.rs", "later.rs"]);
}
#[test]
fn a_refresh_answering_for_another_rev_leaves_the_open_review_alone() {
let fixture = crate::test_support::branch_fixture();
let mut app = against_main(&fixture);
app.apply_refresh(diffler_core::review::Refreshed {
status: diffler_core::vcs::StatusModel::default(),
model: DiffModel::default(),
against: Some(("develop".to_owned(), Ok(DiffModel::default()))),
});
assert_eq!(against_paths(&app), ["dirty.rs", "landed.rs"]);
}
#[test]
fn the_branch_picker_reviews_against_the_chosen_branch() {
let fixture = crate::test_support::branch_fixture();
let mut app = App::new(fixture.review(), LoadedConfig::default());
app.handle(key('d'));
app.handle(key('b'));
assert!(matches!(app.modal, Some(Modal::RevList { .. })));
app.handle(code_key(crossterm::event::KeyCode::Tab));
for c in "main".chars() {
app.handle(key(c));
}
app.handle(key('\n'));
assert!(app.modal.is_none());
let diff = app.diff.as_ref().expect("diff view");
assert_eq!(diff.source, ReviewSource::against("main"));
}
#[test]
fn the_commit_picker_reviews_against_the_chosen_commit() {
let fixture = crate::test_support::branch_fixture();
let mut app = App::new(fixture.review(), LoadedConfig::default());
app.handle(key('d'));
app.handle(key('s'));
let Some(Modal::RevList { entries, .. }) = &app.modal else {
panic!("rev picker open, got {:?}", app.modal);
};
assert!(entries[0].label.contains("feature work"), "{entries:?}");
app.handle(key('\n'));
assert_eq!(against_paths(&app), ["dirty.rs"]);
}
#[test]
fn a_rev_that_does_not_resolve_reports_instead_of_panicking() {
let fixture = crate::test_support::branch_fixture();
let mut app = App::new(fixture.review(), LoadedConfig::default());
app.open_against_diff("no-such-branch");
assert!(app.diff.is_none());
assert!(
matches!(&app.message, Some(m) if m.severity == crate::app::Severity::Error),
"{:?}",
app.message
);
}
#[test]
fn w_goes_back_to_the_plain_working_tree_review() {
let fixture = crate::test_support::branch_fixture();
let mut app = App::new(fixture.review(), LoadedConfig::default());
app.handle(key('d'));
app.handle(key('w'));
let diff = app.diff.as_ref().expect("diff view");
assert_eq!(diff.source, ReviewSource::WorkingTree);
assert_eq!(app.against_rev(), None);
}
fn fixture_content(app: &crate::app::App) -> String {
app.review
.model()
.files
.iter()
.find(|f| f.path == "src/lib.rs")
.and_then(|f| f.new_text.clone())
.expect("new text")
}
fn current_hash(app: &crate::app::App) -> String {
app.review
.model()
.files
.iter()
.find(|f| f.path == "src/lib.rs")
.map(diffler_core::model::FileDiff::sides_hash)
.expect("hash")
}
}