Initial public release
Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
416
crates/luxe-tui/src/guided_review/diff.rs
Normal file
416
crates/luxe-tui/src/guided_review/diff.rs
Normal file
@@ -0,0 +1,416 @@
|
||||
//! Unified diff row projection — bounded rendering data over immutable review hunks.
|
||||
//!
|
||||
//! The renderer asks for a visible row window instead of materializing every line in a large
|
||||
//! review. Source lines remain borrowed from the pinned review and retain both line anchors.
|
||||
|
||||
use super::fold::{FoldedRun, VisibleGroup};
|
||||
use luxe_core::guided_review::{HunkId, LineRange, ReviewHunk, ReviewLine, ReviewLineKind};
|
||||
use unicode_width::UnicodeWidthChar;
|
||||
|
||||
/// A visible unified-diff row borrowed from the pinned review source.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum UnifiedDiffRow<'a> {
|
||||
/// An orientation header for one source-anchored hunk.
|
||||
HunkHeader {
|
||||
/// Stable source identity used by review navigation.
|
||||
hunk_id: &'a HunkId,
|
||||
/// Old-side range shown in the canonical unified header.
|
||||
old_range: LineRange,
|
||||
/// New-side range shown in the canonical unified header.
|
||||
new_range: LineRange,
|
||||
/// Optional trailing context supplied by the diff source.
|
||||
heading: Option<&'a str>,
|
||||
},
|
||||
/// One exact source line with old/new anchors and a semantic diff role.
|
||||
Source(&'a ReviewLine),
|
||||
/// A run of collapsed mechanical hunks, standing in for itself on one row.
|
||||
Folded(FoldedRun),
|
||||
}
|
||||
|
||||
/// One side of a synchronized split-diff row.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum SplitDiffCell<'a> {
|
||||
/// An exact immutable source line for this side.
|
||||
Source(&'a ReviewLine),
|
||||
/// An intentionally empty counterpart for an asymmetric change.
|
||||
Empty,
|
||||
}
|
||||
|
||||
/// One row of the side-by-side projection.
|
||||
///
|
||||
/// Every row carries the **unified** row index it starts at, which is what makes side-by-side a
|
||||
/// *view* of the same row space rather than a second one: scroll position, hunk selection, click
|
||||
/// mapping, the scrollbar and search all keep working against `position.line_offset` unchanged. The
|
||||
/// old renderer paged a single hunk against its own private offset, which had to be kept in sync with
|
||||
/// the real one and could not show a file.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum SplitRow<'a> {
|
||||
/// A hunk header, spanning both columns.
|
||||
Header {
|
||||
/// Stable source identity used by review navigation.
|
||||
hunk_id: &'a HunkId,
|
||||
/// Old-side range shown in the canonical unified header.
|
||||
old_range: LineRange,
|
||||
/// New-side range shown in the canonical unified header.
|
||||
new_range: LineRange,
|
||||
/// Optional trailing context supplied by the diff source.
|
||||
heading: Option<&'a str>,
|
||||
/// Index of this row in the unified row space.
|
||||
unified_index: usize,
|
||||
},
|
||||
/// Old and new content side by side.
|
||||
Pair {
|
||||
/// Hunk this row belongs to.
|
||||
hunk_id: &'a HunkId,
|
||||
/// Old-side content or an explicit gap.
|
||||
old: SplitDiffCell<'a>,
|
||||
/// New-side content or an explicit gap.
|
||||
new: SplitDiffCell<'a>,
|
||||
/// Index of the first unified row this pair covers.
|
||||
unified_index: usize,
|
||||
/// Index of the last, so a window starting at the pair's other half still holds it
|
||||
last_index: usize,
|
||||
},
|
||||
/// A run of collapsed mechanical hunks, spanning both columns.
|
||||
Folded {
|
||||
/// What the run stands for.
|
||||
run: FoldedRun,
|
||||
/// Index of this row in the unified row space.
|
||||
unified_index: usize,
|
||||
},
|
||||
}
|
||||
|
||||
impl SplitRow<'_> {
|
||||
/// The unified row index this row starts at.
|
||||
pub(crate) fn unified_index(&self) -> usize {
|
||||
match self {
|
||||
Self::Header { unified_index, .. }
|
||||
| Self::Pair { unified_index, .. }
|
||||
| Self::Folded { unified_index, .. } => *unified_index,
|
||||
}
|
||||
}
|
||||
|
||||
/// The last unified row this row covers: its own index, or a pair's later half.
|
||||
fn last_index(&self) -> usize {
|
||||
match self {
|
||||
Self::Pair { last_index, .. } => *last_index,
|
||||
other => other.unified_index(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The hunk this row belongs to, when it belongs to one.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn hunk_id(&self) -> Option<&HunkId> {
|
||||
match self {
|
||||
Self::Header { hunk_id, .. } | Self::Pair { hunk_id, .. } => Some(hunk_id),
|
||||
Self::Folded { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Projects a window of side-by-side rows for one file, in the unified row space.
|
||||
///
|
||||
/// `offset`/`height` mean exactly what they mean for [`visible_rows`]: the first unified row to
|
||||
/// show and how many *rendered* rows fit. Pairing collapses a deletion and its replacement onto one
|
||||
/// row, so a window of `height` rows can cover more than `height` unified rows — which is the point
|
||||
/// of the layout.
|
||||
pub(crate) fn visible_split_rows<'a>(
|
||||
groups: &[VisibleGroup<'a>],
|
||||
offset: usize,
|
||||
height: usize,
|
||||
) -> Vec<SplitRow<'a>> {
|
||||
if height == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut rows: Vec<SplitRow<'a>> = Vec::with_capacity(height);
|
||||
let mut unified = 0usize;
|
||||
for group in groups {
|
||||
let hunk = match group {
|
||||
VisibleGroup::Folded(run) => {
|
||||
if unified >= offset && rows.len() < height {
|
||||
rows.push(SplitRow::Folded { run: *run, unified_index: unified });
|
||||
}
|
||||
unified += 1;
|
||||
if rows.len() == height && unified > offset {
|
||||
return rows;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
VisibleGroup::Hunk(hunk) => hunk,
|
||||
};
|
||||
if unified >= offset && rows.len() < height {
|
||||
rows.push(SplitRow::Header {
|
||||
hunk_id: &hunk.id,
|
||||
old_range: hunk.old_range,
|
||||
new_range: hunk.new_range,
|
||||
heading: hunk.heading.as_deref(),
|
||||
unified_index: unified,
|
||||
});
|
||||
}
|
||||
unified += 1;
|
||||
if rows.len() == height && unified > offset {
|
||||
return rows;
|
||||
}
|
||||
|
||||
let mut deletions: Vec<(usize, &ReviewLine)> = Vec::new();
|
||||
let mut additions: Vec<(usize, &ReviewLine)> = Vec::new();
|
||||
|
||||
for line in &hunk.lines {
|
||||
let index = unified;
|
||||
unified += 1;
|
||||
match line.kind {
|
||||
ReviewLineKind::Deletion => deletions.push((index, line)),
|
||||
ReviewLineKind::Addition => additions.push((index, line)),
|
||||
ReviewLineKind::Context | ReviewLineKind::NoNewlineMarker => {
|
||||
project_change_run(
|
||||
&mut rows,
|
||||
&hunk.id,
|
||||
(&mut deletions, &mut additions),
|
||||
(offset, height),
|
||||
);
|
||||
push_split_row(
|
||||
&mut rows,
|
||||
SplitRow::Pair {
|
||||
hunk_id: &hunk.id,
|
||||
old: SplitDiffCell::Source(line),
|
||||
new: SplitDiffCell::Source(line),
|
||||
unified_index: index,
|
||||
last_index: index,
|
||||
},
|
||||
offset,
|
||||
height,
|
||||
);
|
||||
}
|
||||
}
|
||||
if rows.len() == height {
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
project_change_run(&mut rows, &hunk.id, (&mut deletions, &mut additions), (offset, height));
|
||||
if rows.len() == height {
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// Changed lines of one kind in a run, each with its unified index.
|
||||
type ChangeRun<'a> = Vec<(usize, &'a ReviewLine)>;
|
||||
|
||||
/// One run of changes as split rows: deletions paired positionally with the additions after
|
||||
/// them, which is also what makes the intra-line marks exact here, then whatever is unpaired.
|
||||
fn project_change_run<'a>(
|
||||
rows: &mut Vec<SplitRow<'a>>,
|
||||
hunk_id: &'a HunkId,
|
||||
(deletions, additions): (&mut ChangeRun<'a>, &mut ChangeRun<'a>),
|
||||
(offset, height): (usize, usize),
|
||||
) {
|
||||
let paired = deletions.len().min(additions.len());
|
||||
for index in 0..paired {
|
||||
let (old_index, old) = deletions[index];
|
||||
let (new_index, new) = additions[index];
|
||||
push_split_row(
|
||||
rows,
|
||||
SplitRow::Pair {
|
||||
hunk_id,
|
||||
old: SplitDiffCell::Source(old),
|
||||
new: SplitDiffCell::Source(new),
|
||||
unified_index: old_index.min(new_index),
|
||||
last_index: old_index.max(new_index),
|
||||
},
|
||||
offset,
|
||||
height,
|
||||
);
|
||||
}
|
||||
for (index, line) in deletions.drain(..).skip(paired) {
|
||||
push_split_row(
|
||||
rows,
|
||||
SplitRow::Pair {
|
||||
hunk_id,
|
||||
old: SplitDiffCell::Source(line),
|
||||
new: SplitDiffCell::Empty,
|
||||
unified_index: index,
|
||||
last_index: index,
|
||||
},
|
||||
offset,
|
||||
height,
|
||||
);
|
||||
}
|
||||
for (index, line) in additions.drain(..).skip(paired) {
|
||||
push_split_row(
|
||||
rows,
|
||||
SplitRow::Pair {
|
||||
hunk_id,
|
||||
old: SplitDiffCell::Empty,
|
||||
new: SplitDiffCell::Source(line),
|
||||
unified_index: index,
|
||||
last_index: index,
|
||||
},
|
||||
offset,
|
||||
height,
|
||||
);
|
||||
}
|
||||
deletions.clear();
|
||||
additions.clear();
|
||||
}
|
||||
|
||||
fn push_split_row<'a>(
|
||||
rows: &mut Vec<SplitRow<'a>>,
|
||||
row: SplitRow<'a>,
|
||||
offset: usize,
|
||||
height: usize,
|
||||
) {
|
||||
// Once the window has started, every row after it belongs. It starts at the row holding the
|
||||
// offset, which for a pair may be its later half, or else the first row past it.
|
||||
let starts = row.unified_index() >= offset || row.last_index() == offset;
|
||||
if (!rows.is_empty() || starts) && rows.len() < height {
|
||||
rows.push(row);
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the minimum fixed gutter width that can display every visible source line number.
|
||||
pub(crate) fn gutter_width(hunks: &[ReviewHunk]) -> usize {
|
||||
hunks
|
||||
.iter()
|
||||
.flat_map(|hunk| hunk.lines.iter())
|
||||
.flat_map(|line| [line.old_line, line.new_line])
|
||||
.flatten()
|
||||
.map(u32::ilog10)
|
||||
.map(|digits| digits as usize + 1)
|
||||
.max()
|
||||
.unwrap_or(1)
|
||||
}
|
||||
|
||||
/// Projects a window of a file's visible row space, retaining bounded allocation and source
|
||||
/// identity.
|
||||
///
|
||||
/// `offset` counts rows in that space — a hunk header plus its source lines, or one row per
|
||||
/// collapsed run — which is the same space navigation and the scrollbar count in. A zero-sized
|
||||
/// window returns no rows, so a collapsed terminal body never forces source traversal allocation.
|
||||
pub(crate) fn visible_rows<'a>(
|
||||
groups: &[VisibleGroup<'a>],
|
||||
offset: usize,
|
||||
height: usize,
|
||||
) -> Vec<UnifiedDiffRow<'a>> {
|
||||
if height == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut skipped = 0usize;
|
||||
let mut visible = Vec::with_capacity(height);
|
||||
for group in groups {
|
||||
let hunk = match group {
|
||||
VisibleGroup::Folded(run) => {
|
||||
append_visible_row(
|
||||
&mut visible,
|
||||
UnifiedDiffRow::Folded(*run),
|
||||
offset,
|
||||
height,
|
||||
&mut skipped,
|
||||
);
|
||||
if visible.len() == height {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
VisibleGroup::Hunk(hunk) => hunk,
|
||||
};
|
||||
let header = UnifiedDiffRow::HunkHeader {
|
||||
hunk_id: &hunk.id,
|
||||
old_range: hunk.old_range,
|
||||
new_range: hunk.new_range,
|
||||
heading: hunk.heading.as_deref(),
|
||||
};
|
||||
append_visible_row(&mut visible, header, offset, height, &mut skipped);
|
||||
if visible.len() == height {
|
||||
break;
|
||||
}
|
||||
|
||||
for line in &hunk.lines {
|
||||
append_visible_row(
|
||||
&mut visible,
|
||||
UnifiedDiffRow::Source(line),
|
||||
offset,
|
||||
height,
|
||||
&mut skipped,
|
||||
);
|
||||
if visible.len() == height {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if visible.len() == height {
|
||||
break;
|
||||
}
|
||||
}
|
||||
visible
|
||||
}
|
||||
|
||||
fn append_visible_row<'a>(
|
||||
visible: &mut Vec<UnifiedDiffRow<'a>>,
|
||||
row: UnifiedDiffRow<'a>,
|
||||
offset: usize,
|
||||
height: usize,
|
||||
skipped: &mut usize,
|
||||
) {
|
||||
if *skipped >= offset {
|
||||
visible.push(row);
|
||||
}
|
||||
*skipped += 1;
|
||||
debug_assert!(visible.len() <= height);
|
||||
}
|
||||
|
||||
/// Clips a source line by terminal cells without splitting a wide glyph.
|
||||
pub(crate) fn clip_terminal_cells(text: &str, offset: usize, width: usize) -> String {
|
||||
let mut skipped = 0usize;
|
||||
let mut visible_width = 0usize;
|
||||
let mut clipped = String::new();
|
||||
|
||||
for character in text.chars() {
|
||||
let character_width = UnicodeWidthChar::width(character).unwrap_or(0);
|
||||
if skipped < offset {
|
||||
skipped = skipped.saturating_add(character_width);
|
||||
continue;
|
||||
}
|
||||
if character_width == 0 && clipped.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if visible_width.saturating_add(character_width) > width {
|
||||
break;
|
||||
}
|
||||
clipped.push(character);
|
||||
visible_width = visible_width.saturating_add(character_width);
|
||||
}
|
||||
clipped
|
||||
}
|
||||
|
||||
/// Clips `text` to `width` terminal cells, appending an ellipsis (`…`) when it truncates.
|
||||
///
|
||||
/// Unlike [`clip_terminal_cells`] (offset-based horizontal scrolling for diff source), this is
|
||||
/// for fixed-width labels/titles: it never scrolls and signals truncation with a trailing `…`
|
||||
/// rather than silently cutting mid-word. Returns the text unchanged when it already fits.
|
||||
pub(crate) fn clip_terminal_cells_ellipsis(text: &str, width: usize) -> String {
|
||||
if width == 0 {
|
||||
return String::new();
|
||||
}
|
||||
let full_width: usize =
|
||||
text.chars().map(|character| UnicodeWidthChar::width(character).unwrap_or(0)).sum();
|
||||
if full_width <= width {
|
||||
return text.to_string();
|
||||
}
|
||||
let mut clipped = clip_terminal_cells(text, 0, width.saturating_sub(1));
|
||||
clipped.push('…');
|
||||
clipped
|
||||
}
|
||||
|
||||
/// Returns the readable, color-independent marker for one source line.
|
||||
pub(crate) const fn marker(kind: ReviewLineKind) -> char {
|
||||
match kind {
|
||||
ReviewLineKind::Context => ' ',
|
||||
ReviewLineKind::Deletion => '-',
|
||||
ReviewLineKind::Addition => '+',
|
||||
ReviewLineKind::NoNewlineMarker => '\\',
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
308
crates/luxe-tui/src/guided_review/diff/tests.rs
Normal file
308
crates/luxe-tui/src/guided_review/diff/tests.rs
Normal file
@@ -0,0 +1,308 @@
|
||||
use super::*;
|
||||
use luxe_core::guided_review::{FileId, HunkId, NoiseKind};
|
||||
use std::path::Path;
|
||||
|
||||
fn hunk(start: u32, lines: Vec<ReviewLine>) -> ReviewHunk {
|
||||
ReviewHunk {
|
||||
id: HunkId::from_content(
|
||||
&FileId::from_path_lineage(None, Some(Path::new("fixture.rs"))),
|
||||
&format!("context-{start}"),
|
||||
"let value = 1;",
|
||||
),
|
||||
old_range: LineRange::new(start, lines.len() as u32),
|
||||
new_range: LineRange::new(start, lines.len() as u32),
|
||||
heading: Some("fn example".into()),
|
||||
symbol: None,
|
||||
lines,
|
||||
noise: NoiseKind::Semantic,
|
||||
}
|
||||
}
|
||||
|
||||
fn line(old_line: Option<u32>, new_line: Option<u32>, kind: ReviewLineKind) -> ReviewLine {
|
||||
ReviewLine { old_line, new_line, kind, text: "let value = 1;".into() }
|
||||
}
|
||||
|
||||
/// Every hunk open — the row space when nothing is collapsed.
|
||||
fn open(hunks: &[ReviewHunk]) -> Vec<VisibleGroup<'_>> {
|
||||
hunks.iter().map(VisibleGroup::Hunk).collect()
|
||||
}
|
||||
|
||||
/// Mechanical hunks collapsed into runs, the way `visible_groups` builds them.
|
||||
fn collapsing_mechanical(hunks: &[ReviewHunk]) -> Vec<VisibleGroup<'_>> {
|
||||
let mut groups: Vec<VisibleGroup<'_>> = Vec::new();
|
||||
for hunk in hunks {
|
||||
if !super::super::fold::is_mechanical(hunk.noise) {
|
||||
groups.push(VisibleGroup::Hunk(hunk));
|
||||
continue;
|
||||
}
|
||||
match groups.last_mut() {
|
||||
Some(VisibleGroup::Folded(run)) => {
|
||||
run.hunks += 1;
|
||||
run.lines += hunk.lines.len();
|
||||
}
|
||||
_ => groups.push(VisibleGroup::Folded(FoldedRun {
|
||||
hunks: 1,
|
||||
lines: hunk.lines.len(),
|
||||
noise: hunk.noise,
|
||||
})),
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// Side-by-side is a *view* of the unified row space: every row says which unified row it
|
||||
/// starts at, so scroll position, selection and click mapping need no second model.
|
||||
#[test]
|
||||
fn split_rows_pair_changes_and_carry_their_unified_index() {
|
||||
let hunks = vec![hunk(
|
||||
1,
|
||||
vec![
|
||||
line(Some(1), Some(1), ReviewLineKind::Context),
|
||||
line(Some(2), None, ReviewLineKind::Deletion),
|
||||
line(Some(3), None, ReviewLineKind::Deletion),
|
||||
line(None, Some(2), ReviewLineKind::Addition),
|
||||
],
|
||||
)];
|
||||
|
||||
let rows = visible_split_rows(&open(&hunks), 0, 8);
|
||||
|
||||
// Header, the context row, the paired replacement, then the unpaired deletion.
|
||||
assert!(matches!(rows[0], SplitRow::Header { unified_index: 0, .. }));
|
||||
assert!(matches!(
|
||||
rows[1],
|
||||
SplitRow::Pair { old: SplitDiffCell::Source(old), unified_index: 1, .. }
|
||||
if old.old_line == Some(1)
|
||||
));
|
||||
assert!(matches!(
|
||||
rows[2],
|
||||
SplitRow::Pair {
|
||||
old: SplitDiffCell::Source(old),
|
||||
new: SplitDiffCell::Source(new),
|
||||
unified_index: 2,
|
||||
..
|
||||
} if old.old_line == Some(2) && new.new_line == Some(2)
|
||||
));
|
||||
assert!(matches!(
|
||||
rows[3],
|
||||
SplitRow::Pair { old: SplitDiffCell::Source(old), new: SplitDiffCell::Empty, .. }
|
||||
if old.old_line == Some(3)
|
||||
));
|
||||
assert_eq!(rows.len(), 4, "one hunk, four rendered rows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_rows_preserve_an_unanchored_no_newline_marker() {
|
||||
let hunks = vec![hunk(1, vec![line(None, None, ReviewLineKind::NoNewlineMarker)])];
|
||||
|
||||
let rows = visible_split_rows(&open(&hunks), 1, 4);
|
||||
|
||||
assert!(matches!(
|
||||
rows.as_slice(),
|
||||
[SplitRow::Pair { old: SplitDiffCell::Source(line), .. }]
|
||||
if line.kind == ReviewLineKind::NoNewlineMarker
|
||||
));
|
||||
}
|
||||
|
||||
/// The window is bounded by rendered rows and positioned by the unified offset, exactly like the
|
||||
/// unified projection — so a huge file never materializes.
|
||||
#[test]
|
||||
fn split_rows_return_only_the_requested_window() {
|
||||
let hunks = vec![hunk(
|
||||
1,
|
||||
(1..=10_000)
|
||||
.map(|number| line(Some(number), Some(number), ReviewLineKind::Context))
|
||||
.collect(),
|
||||
)];
|
||||
|
||||
let rows = visible_split_rows(&open(&hunks), 9_998, 3);
|
||||
|
||||
// Row 0 is the hunk header, so unified row 9_998 is source line 9_998.
|
||||
assert_eq!(rows.len(), 3);
|
||||
assert!(matches!(
|
||||
rows[0],
|
||||
SplitRow::Pair { old: SplitDiffCell::Source(line), unified_index: 9_998, .. }
|
||||
if line.old_line == Some(9_998)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_rows_collapse_mechanical_hunks_like_the_unified_projection() {
|
||||
let semantic = hunk(1, vec![line(Some(1), Some(1), ReviewLineKind::Context)]);
|
||||
let mut folded = hunk(10, vec![line(Some(10), Some(10), ReviewLineKind::Context)]);
|
||||
folded.noise = NoiseKind::FormattingOnly;
|
||||
let hunks = [semantic.clone(), folded];
|
||||
|
||||
let rows = visible_split_rows(&collapsing_mechanical(&hunks), 0, 8);
|
||||
|
||||
assert_eq!(rows.len(), 3, "the semantic hunk's header and line, then a collapsed run");
|
||||
assert!(rows[..2].iter().all(|row| row.hunk_id() == Some(&semantic.id)));
|
||||
assert!(
|
||||
matches!(rows[2], SplitRow::Folded { run, .. } if run.hunks == 1),
|
||||
"the collapsed hunk stands as one row rather than vanishing: {rows:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visible_rows_include_hunk_headers_and_preserve_both_gutters() {
|
||||
let hunks = vec![hunk(
|
||||
9,
|
||||
vec![
|
||||
line(Some(9), Some(9), ReviewLineKind::Context),
|
||||
line(Some(10), None, ReviewLineKind::Deletion),
|
||||
line(None, Some(10), ReviewLineKind::Addition),
|
||||
],
|
||||
)];
|
||||
|
||||
let rows = visible_rows(&open(&hunks), 1, 2);
|
||||
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert!(
|
||||
matches!(rows[0], UnifiedDiffRow::Source(line) if line.old_line == Some(9) && line.new_line == Some(9))
|
||||
);
|
||||
assert!(
|
||||
matches!(rows[1], UnifiedDiffRow::Source(line) if line.old_line == Some(10) && line.new_line.is_none())
|
||||
);
|
||||
assert_eq!(gutter_width(&hunks), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hunk_headers_keep_stable_selection_identity() {
|
||||
let hunks = vec![hunk(1, vec![line(Some(1), Some(1), ReviewLineKind::Context)])];
|
||||
|
||||
let rows = visible_rows(&open(&hunks), 0, 1);
|
||||
|
||||
assert!(
|
||||
matches!(rows[0], UnifiedDiffRow::HunkHeader { hunk_id, .. } if hunk_id == &hunks[0].id)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_collapsed_run_stands_in_for_its_hunks_without_materializing_them() {
|
||||
let semantic = hunk(1, vec![line(Some(1), Some(1), ReviewLineKind::Context)]);
|
||||
let mut folded = hunk(10, vec![line(Some(10), Some(10), ReviewLineKind::Context)]);
|
||||
folded.noise = NoiseKind::FormattingOnly;
|
||||
|
||||
let hunks = [semantic.clone(), folded];
|
||||
let rows = visible_rows(&collapsing_mechanical(&hunks), 0, 3);
|
||||
|
||||
assert_eq!(rows.len(), 3);
|
||||
assert!(
|
||||
matches!(rows[0], UnifiedDiffRow::HunkHeader { hunk_id, .. } if hunk_id == &semantic.id)
|
||||
);
|
||||
assert!(
|
||||
matches!(rows[2], UnifiedDiffRow::Folded(run) if run.hunks == 1 && run.lines == 1),
|
||||
"a collapsed hunk is a row that says what it stands for: {rows:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn huge_diff_projects_only_the_requested_window() {
|
||||
let lines = (1..=10_000)
|
||||
.map(|number| line(Some(number), Some(number), ReviewLineKind::Context))
|
||||
.collect();
|
||||
let hunks = vec![hunk(1, lines)];
|
||||
|
||||
let rows = visible_rows(&open(&hunks), 9_998, 3);
|
||||
|
||||
assert_eq!(rows.len(), 3);
|
||||
assert!(matches!(rows[0], UnifiedDiffRow::Source(line) if line.old_line == Some(9_998)));
|
||||
assert!(matches!(rows[2], UnifiedDiffRow::Source(line) if line.old_line == Some(10_000)));
|
||||
assert_eq!(gutter_width(&hunks), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_cell_clipping_keeps_wide_glyphs_intact() {
|
||||
assert_eq!(clip_terminal_cells("ab界cd", 2, 3), "界c");
|
||||
assert_eq!(clip_terminal_cells("ab界cd", 3, 2), "cd");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ellipsis_clip_marks_truncation_but_leaves_fitting_text_alone() {
|
||||
// Fits: returned unchanged, no ellipsis.
|
||||
assert_eq!(clip_terminal_cells_ellipsis("short", 10), "short");
|
||||
assert_eq!(clip_terminal_cells_ellipsis("exactfit", 8), "exactfit");
|
||||
// Truncates: one cell reserved for the ellipsis (no silent mid-word cut).
|
||||
assert_eq!(clip_terminal_cells_ellipsis("handles output", 10), "handles o…");
|
||||
// Wide glyphs are never split by the reserved-cell math.
|
||||
assert_eq!(clip_terminal_cells_ellipsis("ab界cd", 4), "ab…");
|
||||
assert_eq!(clip_terminal_cells_ellipsis("anything", 0), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markers_remain_distinguishable_without_theme_color() {
|
||||
assert_eq!(marker(ReviewLineKind::Context), ' ');
|
||||
assert_eq!(marker(ReviewLineKind::Deletion), '-');
|
||||
assert_eq!(marker(ReviewLineKind::Addition), '+');
|
||||
assert_eq!(marker(ReviewLineKind::NoNewlineMarker), '\\');
|
||||
}
|
||||
|
||||
/// A window starting at the added half of a pair starts with that pair, whatever follows it.
|
||||
///
|
||||
/// The break this catches: a pair carried only its earlier index, so a window starting at the
|
||||
/// addition dropped the pair and began at the next context line, or held nothing at all.
|
||||
#[test]
|
||||
fn split_window_keeps_the_pair_containing_the_selected_addition() {
|
||||
use ReviewLineKind::{Addition, Context, Deletion};
|
||||
let starts_with_addition = |rows: &[SplitRow<'_>], new_line: u32| {
|
||||
matches!(rows.first(), Some(SplitRow::Pair { new: SplitDiffCell::Source(line), .. })
|
||||
if line.new_line == Some(new_line))
|
||||
};
|
||||
// header 0, deletion 1, addition 2, context 3
|
||||
let replaced = [hunk(
|
||||
1,
|
||||
vec![
|
||||
line(Some(1), None, Deletion),
|
||||
line(None, Some(1), Addition),
|
||||
line(Some(2), Some(2), Context),
|
||||
],
|
||||
)];
|
||||
let rows = visible_split_rows(&open(&replaced), 2, 3);
|
||||
assert!(starts_with_addition(&rows, 1), "one replaced line");
|
||||
assert_eq!(rows.len(), 2, "the pair, then the context after it");
|
||||
|
||||
// header 0, deletions 1 and 2, addition 3: the pair, then the unpaired deletion
|
||||
let longer = [hunk(
|
||||
1,
|
||||
vec![
|
||||
line(Some(1), None, Deletion),
|
||||
line(Some(2), None, Deletion),
|
||||
line(None, Some(1), Addition),
|
||||
],
|
||||
)];
|
||||
let rows = visible_split_rows(&open(&longer), 3, 4);
|
||||
assert!(starts_with_addition(&rows, 1), "a longer run, no trailing context");
|
||||
assert!(matches!(rows.get(1), Some(SplitRow::Pair { new: SplitDiffCell::Empty, .. })));
|
||||
|
||||
assert!(visible_split_rows(&open(&replaced), 2, 0).is_empty(), "zero height is nothing");
|
||||
}
|
||||
|
||||
/// In a run of three replaced lines, a cursor on any deletion starts the window at that deletion's
|
||||
/// own pair, not the first pair of the run.
|
||||
///
|
||||
/// The break this catches: the window started at the first pair whose later half reached the
|
||||
/// offset, which for a deletion deep in a run is the run's first pair, so the cursor row drew
|
||||
/// lower and lower until it left the pane.
|
||||
#[test]
|
||||
fn split_window_starts_at_the_pair_holding_a_selected_deletion() {
|
||||
use ReviewLineKind::{Addition, Deletion};
|
||||
// header 0, deletions 1..=3, additions 4..=6
|
||||
let run = [hunk(
|
||||
1,
|
||||
vec![
|
||||
line(Some(1), None, Deletion),
|
||||
line(Some(2), None, Deletion),
|
||||
line(Some(3), None, Deletion),
|
||||
line(None, Some(1), Addition),
|
||||
line(None, Some(2), Addition),
|
||||
line(None, Some(3), Addition),
|
||||
],
|
||||
)];
|
||||
for (offset, old_line) in [(1, 1), (2, 2), (3, 3), (4, 1), (5, 2), (6, 3)] {
|
||||
let rows = visible_split_rows(&open(&run), offset, 1);
|
||||
assert!(
|
||||
matches!(rows.first(), Some(SplitRow::Pair { old: SplitDiffCell::Source(line), .. })
|
||||
if line.old_line == Some(old_line)),
|
||||
"offset {offset} should start on the pair of old line {old_line}"
|
||||
);
|
||||
}
|
||||
}
|
||||
279
crates/luxe-tui/src/guided_review/findings.rs
Normal file
279
crates/luxe-tui/src/guided_review/findings.rs
Normal file
@@ -0,0 +1,279 @@
|
||||
//! Review findings — the feedback window and a finding's details, drafts and their anchors.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl GuidedReviewWorkspace {
|
||||
/// Toggles the local inspector for persisted review findings.
|
||||
pub(crate) fn toggle_findings(&mut self) {
|
||||
self.findings_visible = !self.findings_visible;
|
||||
if self.findings_visible {
|
||||
self.help_visible = false;
|
||||
} else {
|
||||
self.finding_details_visible = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes the feedback window and the details and fix views drawn over it, which answer to its
|
||||
/// keys and would be left with none.
|
||||
pub(crate) fn close_feedback_window(&mut self) {
|
||||
self.findings_visible = false;
|
||||
self.finding_details_visible = false;
|
||||
self.finding_fix_visible = false;
|
||||
}
|
||||
|
||||
/// Toggles the selected finding's immutable evidence summary.
|
||||
pub(crate) fn toggle_finding_details(&mut self) {
|
||||
self.finding_details_visible = !self.finding_details_visible;
|
||||
}
|
||||
|
||||
/// Toggles the before/after view of what changed at the selected comment's anchor.
|
||||
pub(crate) fn toggle_finding_fix(&mut self) {
|
||||
self.finding_fix_visible = !self.finding_fix_visible;
|
||||
if self.finding_fix_visible {
|
||||
self.finding_details_visible = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the persisted-finding selection through its stable triage order.
|
||||
pub(crate) fn move_finding_selection(
|
||||
&mut self,
|
||||
findings: &[ReviewFinding],
|
||||
forward: bool,
|
||||
) -> bool {
|
||||
self.feedback_scroll = 0;
|
||||
let findings = ordered_findings(findings);
|
||||
let Some(_first) = findings.first() else {
|
||||
return false;
|
||||
};
|
||||
let next = self
|
||||
.selected_finding_id
|
||||
.as_ref()
|
||||
.and_then(|selected| findings.iter().position(|finding| &finding.id == selected))
|
||||
.map_or_else(
|
||||
|| if forward { 0 } else { findings.len().saturating_sub(1) },
|
||||
|index| {
|
||||
if forward {
|
||||
(index + 1) % findings.len()
|
||||
} else {
|
||||
index.checked_sub(1).unwrap_or(findings.len().saturating_sub(1))
|
||||
}
|
||||
},
|
||||
);
|
||||
self.selected_finding_id = Some(findings[next].id.clone());
|
||||
true
|
||||
}
|
||||
|
||||
/// Selects a persisted finding's immutable anchor when it remains in the pinned review.
|
||||
pub(crate) fn jump_to_finding(
|
||||
&mut self,
|
||||
finding: &ReviewFinding,
|
||||
review: &GuidedReview,
|
||||
) -> bool {
|
||||
match &finding.anchor {
|
||||
FindingAnchor::Line { file_id, hunk_id, side, line, .. } => {
|
||||
let Some(file) = review.files.iter().find(|file| &file.id == file_id) else {
|
||||
return false;
|
||||
};
|
||||
let Some((hunk_index, hunk)) =
|
||||
file.hunks.iter().enumerate().find(|(_, hunk)| &hunk.id == hunk_id)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Some(line_index) = hunk.lines.iter().position(|source| match side {
|
||||
DiffSide::Old => source.old_line == Some(*line),
|
||||
DiffSide::New => source.new_line == Some(*line),
|
||||
}) else {
|
||||
return false;
|
||||
};
|
||||
self.select_finding_hunk(file, hunk_index, Some(line_index));
|
||||
true
|
||||
}
|
||||
FindingAnchor::Hunk { file_id, hunk_id } => {
|
||||
let Some(file) = review.files.iter().find(|file| &file.id == file_id) else {
|
||||
return false;
|
||||
};
|
||||
let Some(hunk_index) = file.hunks.iter().position(|hunk| &hunk.id == hunk_id)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
self.select_finding_hunk(file, hunk_index, None);
|
||||
true
|
||||
}
|
||||
FindingAnchor::Chapter { chapter_id } => {
|
||||
let known = review.chapters.iter().any(|chapter| &chapter.id == chapter_id);
|
||||
if known {
|
||||
self.position.chapter_id = Some(chapter_id.clone());
|
||||
}
|
||||
known
|
||||
}
|
||||
// Anchored to the review rather than to any line in it, so there is nowhere to go.
|
||||
FindingAnchor::Review => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens one unsaved finding draft at the current review selection.
|
||||
pub(crate) fn begin_finding_draft(&mut self, files: &[ReviewFile]) -> bool {
|
||||
if self.finding_draft.is_some() {
|
||||
return false;
|
||||
}
|
||||
self.finding_draft = Some(FindingDraft::new(
|
||||
self.selected_finding_anchor(files),
|
||||
FindingSeverity::Issue,
|
||||
false,
|
||||
None,
|
||||
));
|
||||
true
|
||||
}
|
||||
|
||||
/// Opens a comment on the review as a whole, which posts as its summary.
|
||||
///
|
||||
/// The cursor always sits somewhere in the diff, so `c` never reaches the review itself; the
|
||||
/// post preview is where a summary is wanted, and where Request changes needs one.
|
||||
pub(crate) fn begin_review_summary(&mut self) -> bool {
|
||||
if self.finding_draft.is_some() {
|
||||
return false;
|
||||
}
|
||||
self.finding_draft =
|
||||
Some(FindingDraft::new(FindingAnchor::Review, FindingSeverity::Issue, false, None));
|
||||
true
|
||||
}
|
||||
|
||||
/// Opens a question at the current selection, dispatched the moment it is saved.
|
||||
///
|
||||
/// Asking is how a reviewer builds a theory of code they did not write, so it is a verb of its
|
||||
/// own rather than a comment severity buried in a form.
|
||||
pub(crate) fn begin_question(&mut self, files: &[ReviewFile]) -> bool {
|
||||
if self.finding_draft.is_some() {
|
||||
return false;
|
||||
}
|
||||
self.finding_draft = Some(FindingDraft::new(
|
||||
self.selected_finding_anchor(files),
|
||||
FindingSeverity::Question,
|
||||
true,
|
||||
None,
|
||||
));
|
||||
true
|
||||
}
|
||||
|
||||
/// Opens a reply to an existing comment, continuing its thread.
|
||||
///
|
||||
/// The reply's `severity` is what it asks of the agent: the finding's own to continue it, or an
|
||||
/// issue to turn a question into a fix request.
|
||||
pub(crate) fn begin_reply(
|
||||
&mut self,
|
||||
finding: &ReviewFinding,
|
||||
severity: FindingSeverity,
|
||||
) -> bool {
|
||||
if self.finding_draft.is_some() {
|
||||
return false;
|
||||
}
|
||||
let draft =
|
||||
FindingDraft::new(finding.anchor.clone(), severity, true, Some(finding.id.clone()));
|
||||
self.finding_draft = Some(draft);
|
||||
self.close_feedback_window();
|
||||
true
|
||||
}
|
||||
|
||||
/// Opens a local editor prefilled from an unsubmitted persisted finding draft.
|
||||
pub(crate) fn begin_edit_finding_draft(&mut self, finding: &ReviewFinding) -> bool {
|
||||
if self.finding_draft.is_some() || finding.state != FindingState::Draft {
|
||||
return false;
|
||||
}
|
||||
let mut draft = FindingDraft::new(finding.anchor.clone(), finding.severity, false, None);
|
||||
draft.carry_fix(finding.proposed_fix.clone());
|
||||
draft.set_body(finding.body.clone());
|
||||
self.finding_draft = Some(draft);
|
||||
self.editing_finding_id = Some(finding.id.clone());
|
||||
self.close_feedback_window();
|
||||
true
|
||||
}
|
||||
|
||||
/// Discards the unsaved finding draft without changing the underlying review session.
|
||||
pub(crate) fn discard_finding_draft(&mut self) {
|
||||
self.finding_draft = None;
|
||||
self.editing_finding_id = None;
|
||||
}
|
||||
|
||||
/// Scrolls the feedback window's reading pane by `rows`, down when positive, within what it
|
||||
/// was last drawn with.
|
||||
pub(crate) fn scroll_feedback(&mut self, rows: i32) {
|
||||
let room = i32::from(self.feedback_room.get());
|
||||
let at = i32::from(self.feedback_scroll).saturating_add(rows).clamp(0, room);
|
||||
self.feedback_scroll = u16::try_from(at).unwrap_or(0);
|
||||
}
|
||||
|
||||
/// Maps the focused unified-diff row to the narrowest honest finding anchor.
|
||||
pub(crate) fn selected_finding_anchor(&self, files: &[ReviewFile]) -> FindingAnchor {
|
||||
let Some(file_id) = self.position.file_id.as_ref() else {
|
||||
return self.chapter_or_review_anchor();
|
||||
};
|
||||
let Some(file) = files.iter().find(|file| &file.id == file_id) else {
|
||||
return self.chapter_or_review_anchor();
|
||||
};
|
||||
|
||||
let mut row = 0usize;
|
||||
for group in visible_groups(file, &self.fold) {
|
||||
let VisibleGroup::Hunk(hunk) = group else {
|
||||
// A collapsed run is one row, and comments do not anchor to it.
|
||||
row = row.saturating_add(1);
|
||||
continue;
|
||||
};
|
||||
if row == self.position.line_offset {
|
||||
return FindingAnchor::Hunk { file_id: file.id.clone(), hunk_id: hunk.id.clone() };
|
||||
}
|
||||
row = row.saturating_add(1);
|
||||
|
||||
for line in &hunk.lines {
|
||||
if row == self.position.line_offset {
|
||||
return finding_anchor_for_line(file, hunk, line).unwrap_or_else(|| {
|
||||
FindingAnchor::Hunk { file_id: file.id.clone(), hunk_id: hunk.id.clone() }
|
||||
});
|
||||
}
|
||||
row = row.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
self.position.hunk_id.clone().map_or_else(
|
||||
|| self.chapter_or_review_anchor(),
|
||||
|hunk_id| FindingAnchor::Hunk { file_id: file.id.clone(), hunk_id },
|
||||
)
|
||||
}
|
||||
|
||||
/// The file the cursor is in and the line of the *new* file it is on, for opening it in an
|
||||
/// editor: a hunk's header is its first line, a removed line is the line it was removed
|
||||
/// before, and a folded run of churn names no line at all.
|
||||
pub(crate) fn selected_new_line<'a>(
|
||||
&self,
|
||||
files: &'a [ReviewFile],
|
||||
) -> Option<(&'a ReviewFile, Option<u32>)> {
|
||||
let file = self.selected_file(files)?;
|
||||
let mut row = 0usize;
|
||||
for group in visible_groups(file, &self.fold) {
|
||||
let VisibleGroup::Hunk(hunk) = group else {
|
||||
if row == self.position.line_offset {
|
||||
return Some((file, None));
|
||||
}
|
||||
row = row.saturating_add(1);
|
||||
continue;
|
||||
};
|
||||
if row == self.position.line_offset {
|
||||
return Some((file, (hunk.new_range.start > 0).then_some(hunk.new_range.start)));
|
||||
}
|
||||
row = row.saturating_add(1);
|
||||
for index in 0..hunk.lines.len() {
|
||||
if row == self.position.line_offset {
|
||||
return Some((file, new_side_line(hunk, index)));
|
||||
}
|
||||
row = row.saturating_add(1);
|
||||
}
|
||||
}
|
||||
Some((file, None))
|
||||
}
|
||||
|
||||
fn chapter_or_review_anchor(&self) -> FindingAnchor {
|
||||
self.position
|
||||
.chapter_id
|
||||
.clone()
|
||||
.map_or(FindingAnchor::Review, |chapter_id| FindingAnchor::Chapter { chapter_id })
|
||||
}
|
||||
}
|
||||
284
crates/luxe-tui/src/guided_review/fold.rs
Normal file
284
crates/luxe-tui/src/guided_review/fold.rs
Normal file
@@ -0,0 +1,284 @@
|
||||
//! Fold — the one answer to "is this hunk on screen right now".
|
||||
//!
|
||||
//! Folding exists for mechanical churn: a reformatted import block, a regenerated file, a lockfile,
|
||||
//! a rename. Nothing else. A hunk is never hidden because a test covers it or because someone other
|
||||
//! than the agent wrote it — that is a *claim*, and a claim belongs on the hunk, not in place of it.
|
||||
//!
|
||||
//! There is exactly one predicate because two would disagree: if the renderer folded everything the
|
||||
//! review budget accounted for while navigation folded only mechanical noise, the cursor could
|
||||
//! settle on a hunk the renderer refused to draw and the pane would go blank under a breadcrumb.
|
||||
|
||||
use luxe_core::guided_review::{FileId, NoiseKind, ReviewFile, ReviewHunk};
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// Which mechanical changes the reviewer currently has open.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Fold {
|
||||
/// Every mechanical hunk in the review is open.
|
||||
all: bool,
|
||||
/// Files opened one at a time, from their collapsed row.
|
||||
files: HashSet<FileId>,
|
||||
}
|
||||
|
||||
impl Fold {
|
||||
/// Whether this hunk is collapsed into its file's placeholder row.
|
||||
pub fn hides(&self, file: &ReviewFile, hunk: &ReviewHunk) -> bool {
|
||||
!self.all && !self.files.contains(&file.id) && is_mechanical(hunk.noise)
|
||||
}
|
||||
|
||||
/// Whether every mechanical hunk is open.
|
||||
pub const fn is_open(&self) -> bool {
|
||||
self.all
|
||||
}
|
||||
|
||||
/// Whether this file's mechanical hunks are open.
|
||||
pub fn file_is_open(&self, file: &FileId) -> bool {
|
||||
self.all || self.files.contains(file)
|
||||
}
|
||||
|
||||
/// Opens or re-collapses every mechanical hunk in the review.
|
||||
pub fn toggle_all(&mut self) {
|
||||
self.all = !self.all;
|
||||
if !self.all {
|
||||
self.files.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens or re-collapses one file's mechanical hunks.
|
||||
///
|
||||
/// A file opened while everything is open collapses just that file, which is what the row the
|
||||
/// reviewer clicked implies.
|
||||
pub fn toggle_file(&mut self, file: &FileId) {
|
||||
if self.files.contains(file) {
|
||||
self.files.remove(file);
|
||||
} else {
|
||||
self.files.insert(file.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens whatever is needed for this hunk to be on screen.
|
||||
pub fn reveal(&mut self, file: &ReviewFile, hunk: &ReviewHunk) {
|
||||
if self.hides(file, hunk) {
|
||||
self.files.insert(file.id.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops per-file state for files a refreshed review no longer carries.
|
||||
pub fn reconcile(&mut self, files: &[ReviewFile]) {
|
||||
self.files.retain(|id| files.iter().any(|file| &file.id == id));
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a classification describes mechanical churn rather than a decision.
|
||||
pub const fn is_mechanical(noise: NoiseKind) -> bool {
|
||||
matches!(
|
||||
noise,
|
||||
NoiseKind::FormattingOnly
|
||||
| NoiseKind::Generated
|
||||
| NoiseKind::Lockfile
|
||||
| NoiseKind::Mechanical
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether this review contains any mechanical churn at all, open or collapsed.
|
||||
///
|
||||
/// With none, the fold controls are dead keys — nothing to collapse, and nothing for `d` to
|
||||
/// explain. A control that cannot do anything is worse than an absent one: the reviewer presses
|
||||
/// it, watches nothing happen, and learns that the footer is not to be trusted.
|
||||
pub fn has_mechanical_churn(files: &[ReviewFile]) -> bool {
|
||||
files.iter().flat_map(|file| file.hunks.iter()).any(|hunk| is_mechanical(hunk.noise))
|
||||
}
|
||||
|
||||
/// The reviewer-facing reason a class of change collapses.
|
||||
pub const fn mechanical_label(noise: NoiseKind) -> &'static str {
|
||||
match noise {
|
||||
NoiseKind::FormattingOnly => "formatting only",
|
||||
NoiseKind::Generated => "generated",
|
||||
NoiseKind::Lockfile => "lockfile",
|
||||
NoiseKind::Mechanical => "moved or renamed",
|
||||
NoiseKind::CommentOnly => "comments only",
|
||||
NoiseKind::Semantic | NoiseKind::Unknown => "low signal",
|
||||
}
|
||||
}
|
||||
|
||||
/// One collapsed run of consecutive mechanical hunks in a file.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct FoldedRun {
|
||||
/// Hunks the run stands for.
|
||||
pub hunks: usize,
|
||||
/// Source lines the run stands for.
|
||||
pub lines: usize,
|
||||
/// Classification of the first hunk in the run, which names the collapse.
|
||||
pub noise: NoiseKind,
|
||||
}
|
||||
|
||||
impl FoldedRun {
|
||||
/// `3 hunks · 148 lines · lockfile`.
|
||||
pub fn summary(&self) -> String {
|
||||
let hunks =
|
||||
format!("{} {}", self.hunks, if self.hunks == 1 { "change" } else { "changes" });
|
||||
let lines = format!("{} {}", self.lines, if self.lines == 1 { "line" } else { "lines" });
|
||||
format!("{hunks} · {lines} · {}", mechanical_label(self.noise))
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry of a file's visible row space: a hunk, or a collapsed run standing in for several.
|
||||
///
|
||||
/// Everything that counts rows — the renderer, the scrollbar, cursor offsets, scroll bounds, click
|
||||
/// mapping — walks this, so they cannot disagree about what is on screen.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum VisibleGroup<'a> {
|
||||
/// An open hunk, occupying its header plus one row per source line.
|
||||
Hunk(&'a ReviewHunk),
|
||||
/// A collapsed run of consecutive mechanical hunks, occupying exactly one row.
|
||||
Folded(FoldedRun),
|
||||
}
|
||||
|
||||
impl VisibleGroup<'_> {
|
||||
/// Rows this group occupies.
|
||||
pub fn rows(&self) -> usize {
|
||||
match self {
|
||||
Self::Hunk(hunk) => hunk.lines.len() + 1,
|
||||
Self::Folded(_) => 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The unified rows one hunk owns — its header and every line under it — or `None` when the fold
|
||||
/// has it collapsed.
|
||||
///
|
||||
/// The renderer needs this to mark the hunk being read down its whole height, and cannot get it
|
||||
/// from the rows alone: a window that starts mid-hunk has no header in it to attribute the lines to.
|
||||
pub fn hunk_row_span(
|
||||
groups: &[VisibleGroup<'_>],
|
||||
hunk_id: &luxe_core::guided_review::HunkId,
|
||||
) -> Option<std::ops::Range<usize>> {
|
||||
let mut row = 0usize;
|
||||
for group in groups {
|
||||
let rows = group.rows();
|
||||
if matches!(group, VisibleGroup::Hunk(hunk) if &hunk.id == hunk_id) {
|
||||
return Some(row..row + rows);
|
||||
}
|
||||
row += rows;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// A file's visible row space: open hunks in source order, with each run of collapsed mechanical
|
||||
/// hunks standing as one row where it sits.
|
||||
pub fn visible_groups<'a>(file: &'a ReviewFile, fold: &Fold) -> Vec<VisibleGroup<'a>> {
|
||||
let mut groups: Vec<VisibleGroup<'a>> = Vec::with_capacity(file.hunks.len());
|
||||
for hunk in &file.hunks {
|
||||
if !fold.hides(file, hunk) {
|
||||
groups.push(VisibleGroup::Hunk(hunk));
|
||||
continue;
|
||||
}
|
||||
match groups.last_mut() {
|
||||
Some(VisibleGroup::Folded(run)) => {
|
||||
run.hunks += 1;
|
||||
run.lines += hunk.lines.len();
|
||||
}
|
||||
_ => groups.push(VisibleGroup::Folded(FoldedRun {
|
||||
hunks: 1,
|
||||
lines: hunk.lines.len(),
|
||||
noise: hunk.noise,
|
||||
})),
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use luxe_core::guided_review::{HunkId, LineRange, ReviewFileStatus};
|
||||
use std::path::Path;
|
||||
|
||||
fn file(path: &str, noise: NoiseKind) -> ReviewFile {
|
||||
let id = FileId::from_path_lineage(None, Some(Path::new(path)));
|
||||
let hunk = ReviewHunk {
|
||||
id: HunkId::from_content(&id, "h", "h"),
|
||||
old_range: LineRange::new(1, 1),
|
||||
new_range: LineRange::new(1, 1),
|
||||
heading: None,
|
||||
symbol: None,
|
||||
lines: Vec::new(),
|
||||
noise,
|
||||
};
|
||||
ReviewFile {
|
||||
id,
|
||||
old_path: None,
|
||||
new_path: Some(path.into()),
|
||||
status: ReviewFileStatus::Modified,
|
||||
language: None,
|
||||
additions: Some(1),
|
||||
deletions: Some(0),
|
||||
hunks: vec![hunk],
|
||||
binary: false,
|
||||
generated: false,
|
||||
non_text: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_mechanical_change_folds() {
|
||||
let fold = Fold::default();
|
||||
let lockfile = file("Cargo.lock", NoiseKind::Lockfile);
|
||||
let source = file("src/lib.rs", NoiseKind::Semantic);
|
||||
assert!(fold.hides(&lockfile, &lockfile.hunks[0]));
|
||||
assert!(!fold.hides(&source, &source.hunks[0]), "a decision is never hidden");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_opens_on_its_own_and_closes_again() {
|
||||
let mut fold = Fold::default();
|
||||
let lockfile = file("Cargo.lock", NoiseKind::Lockfile);
|
||||
let other = file("pnpm-lock.yaml", NoiseKind::Lockfile);
|
||||
|
||||
fold.toggle_file(&lockfile.id);
|
||||
assert!(!fold.hides(&lockfile, &lockfile.hunks[0]));
|
||||
assert!(fold.hides(&other, &other.hunks[0]), "opening one file opens only that file");
|
||||
|
||||
fold.toggle_file(&lockfile.id);
|
||||
assert!(fold.hides(&lockfile, &lockfile.hunks[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revealing_a_hidden_hunk_opens_its_file_and_nothing_else() {
|
||||
let mut fold = Fold::default();
|
||||
let lockfile = file("Cargo.lock", NoiseKind::Lockfile);
|
||||
let other = file("pnpm-lock.yaml", NoiseKind::Lockfile);
|
||||
|
||||
fold.reveal(&lockfile, &lockfile.hunks[0]);
|
||||
|
||||
assert!(!fold.hides(&lockfile, &lockfile.hunks[0]));
|
||||
assert!(fold.hides(&other, &other.hunks[0]));
|
||||
assert!(!fold.is_open(), "one file is not the whole review");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refreshed_review_drops_state_for_files_it_no_longer_carries() {
|
||||
let mut fold = Fold::default();
|
||||
let gone = file("Cargo.lock", NoiseKind::Lockfile);
|
||||
let kept = file("pnpm-lock.yaml", NoiseKind::Lockfile);
|
||||
fold.toggle_file(&gone.id);
|
||||
fold.toggle_file(&kept.id);
|
||||
|
||||
fold.reconcile(std::slice::from_ref(&kept));
|
||||
|
||||
assert!(fold.file_is_open(&kept.id));
|
||||
assert!(!fold.file_is_open(&gone.id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_says_how_much_it_stands_for() {
|
||||
assert_eq!(
|
||||
FoldedRun { hunks: 3, lines: 148, noise: NoiseKind::Lockfile }.summary(),
|
||||
"3 changes · 148 lines · lockfile"
|
||||
);
|
||||
assert_eq!(
|
||||
FoldedRun { hunks: 1, lines: 1, noise: NoiseKind::FormattingOnly }.summary(),
|
||||
"1 change · 1 line · formatting only"
|
||||
);
|
||||
}
|
||||
}
|
||||
228
crates/luxe-tui/src/guided_review/geometry.rs
Normal file
228
crates/luxe-tui/src/guided_review/geometry.rs
Normal file
@@ -0,0 +1,228 @@
|
||||
//! Guided Review layout math — viewport widths, gutters, split columns, and item lookups.
|
||||
//!
|
||||
//! Pure geometry over the pinned review data. Kept apart from the workspace state machine so
|
||||
//! the sizing rules read as one place.
|
||||
|
||||
use super::fold::{visible_groups, Fold, VisibleGroup};
|
||||
use super::ReviewPosition;
|
||||
use luxe_core::guided_review::{
|
||||
DiffSide, FileId, FindingAnchor, GuidedReview, HunkId, ReviewChapter, ReviewFile, ReviewHunk,
|
||||
ReviewItemRef, ReviewLine, ReviewLineKind,
|
||||
};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// One cursor stop in the diff pane: a file, plus its hunk when the file carries text.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub(super) struct NavStop {
|
||||
/// Index into the review's canonical file order.
|
||||
pub(crate) file: usize,
|
||||
/// Index into that file's hunks, or `None` for a non-text item.
|
||||
pub(crate) hunk: Option<usize>,
|
||||
}
|
||||
|
||||
/// Row offset of a hunk's header inside the file's *visible* row space — the space the renderer
|
||||
/// actually lays out. Counting collapsed hunks at full height drops the cursor rows past its target.
|
||||
pub(super) fn visible_row_offset(file: &ReviewFile, hunk_index: usize, fold: &Fold) -> usize {
|
||||
let target = file.hunks.get(hunk_index.min(file.hunks.len().saturating_sub(1)));
|
||||
let mut rows = 0usize;
|
||||
for group in visible_groups(file, fold) {
|
||||
if let (VisibleGroup::Hunk(hunk), Some(target)) = (group, target) {
|
||||
if hunk.id == target.id {
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
rows += group.rows();
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// Where every file and hunk id sits in the review's canonical order.
|
||||
///
|
||||
/// A chapter names its items by id while a stop is a pair of indices, so resolving one is a lookup
|
||||
/// — and doing it by scanning `review.files`, or for a hunk every file's every hunk, is quadratic
|
||||
/// in the size of the review. [`super::ReviewWorkspace::walkthrough_step`] does it once per chapter
|
||||
/// on every frame, which on a 784-file change is 23 ms a frame spent working out a breadcrumb that
|
||||
/// reads `step 7/312`. Built once and asked per item instead.
|
||||
pub(super) struct StopIndex<'a> {
|
||||
files: HashMap<&'a FileId, usize>,
|
||||
hunks: HashMap<&'a HunkId, NavStop>,
|
||||
}
|
||||
|
||||
impl<'a> StopIndex<'a> {
|
||||
/// Indexes every file and hunk in `review`.
|
||||
pub(super) fn of(review: &'a GuidedReview) -> Self {
|
||||
let mut files = HashMap::with_capacity(review.files.len());
|
||||
let mut hunks = HashMap::new();
|
||||
for (index, file) in review.files.iter().enumerate() {
|
||||
files.insert(&file.id, index);
|
||||
for (hunk, entry) in file.hunks.iter().enumerate() {
|
||||
hunks.insert(&entry.id, NavStop { file: index, hunk: Some(hunk) });
|
||||
}
|
||||
}
|
||||
Self { files, hunks }
|
||||
}
|
||||
}
|
||||
|
||||
/// Ordered cursor stops the current presentation allows.
|
||||
///
|
||||
/// Inside a section that is the order **the guide chose** for `chapter.items` — the schema before
|
||||
/// the logic that consumes it, the call sites before the tests that cover them, which is the order
|
||||
/// the work was reasoned in and the whole reason a walkthrough beats a file list. Outside one (All
|
||||
/// Files) it is canonical source order.
|
||||
///
|
||||
/// A text file whose every hunk is collapsed still earns one stop. Skipping it would let a
|
||||
/// walkthrough step through fifteen files showing nothing: the stop lands on the file's collapsed
|
||||
/// rows, which say what is there and open in place.
|
||||
pub(super) fn nav_stops(
|
||||
review: &GuidedReview,
|
||||
chapter: Option<&ReviewChapter>,
|
||||
fold: &Fold,
|
||||
index: &StopIndex<'_>,
|
||||
) -> Vec<NavStop> {
|
||||
let candidates = match chapter {
|
||||
Some(chapter) => chapter_stops(review, chapter, index),
|
||||
None => canonical_stops(review),
|
||||
};
|
||||
apply_fold(review, fold, &candidates)
|
||||
}
|
||||
|
||||
/// Every reviewable item in canonical source order, before folding.
|
||||
fn canonical_stops(review: &GuidedReview) -> Vec<NavStop> {
|
||||
let mut stops = Vec::new();
|
||||
for (index, file) in review.files.iter().enumerate() {
|
||||
if file.non_text.is_some() {
|
||||
stops.push(NavStop { file: index, hunk: None });
|
||||
continue;
|
||||
}
|
||||
stops.extend((0..file.hunks.len()).map(|hunk| NavStop { file: index, hunk: Some(hunk) }));
|
||||
}
|
||||
stops
|
||||
}
|
||||
|
||||
/// A section's items in the order the guide listed them, before folding.
|
||||
///
|
||||
/// A chapter may name a file and one of its hunks both, so repeats are dropped — through a set,
|
||||
/// because scanning what has been collected so far is quadratic in a chapter's own length.
|
||||
fn chapter_stops(
|
||||
review: &GuidedReview,
|
||||
chapter: &ReviewChapter,
|
||||
index: &StopIndex<'_>,
|
||||
) -> Vec<NavStop> {
|
||||
let mut stops: Vec<NavStop> = Vec::new();
|
||||
let mut seen: HashSet<NavStop> = HashSet::new();
|
||||
let mut push = |stops: &mut Vec<NavStop>, stop: NavStop| {
|
||||
if seen.insert(stop) {
|
||||
stops.push(stop);
|
||||
}
|
||||
};
|
||||
for item in &chapter.items {
|
||||
match item {
|
||||
ReviewItemRef::File(file_id) => {
|
||||
let Some(&file_index) = index.files.get(file_id) else {
|
||||
continue;
|
||||
};
|
||||
let file = &review.files[file_index];
|
||||
if file.non_text.is_some() {
|
||||
push(&mut stops, NavStop { file: file_index, hunk: None });
|
||||
} else {
|
||||
for hunk in 0..file.hunks.len() {
|
||||
push(&mut stops, NavStop { file: file_index, hunk: Some(hunk) });
|
||||
}
|
||||
}
|
||||
}
|
||||
ReviewItemRef::Hunk(hunk_id) => {
|
||||
if let Some(&stop) = index.hunks.get(hunk_id) {
|
||||
push(&mut stops, stop);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
stops
|
||||
}
|
||||
|
||||
/// Drops collapsed hunks, keeping one stop per run of them so a file can never vanish.
|
||||
fn apply_fold(review: &GuidedReview, fold: &Fold, candidates: &[NavStop]) -> Vec<NavStop> {
|
||||
let mut stops: Vec<NavStop> = Vec::with_capacity(candidates.len());
|
||||
let mut run = 0usize;
|
||||
while run < candidates.len() {
|
||||
let file_index = candidates[run].file;
|
||||
let end = candidates[run..]
|
||||
.iter()
|
||||
.position(|stop| stop.file != file_index)
|
||||
.map_or(candidates.len(), |offset| run + offset);
|
||||
let file = &review.files[file_index];
|
||||
let before = stops.len();
|
||||
stops.extend(
|
||||
candidates[run..end]
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|stop| stop.hunk.is_none_or(|hunk| !fold.hides(file, &file.hunks[hunk]))),
|
||||
);
|
||||
if stops.len() == before {
|
||||
stops.push(NavStop { file: file_index, hunk: None });
|
||||
}
|
||||
run = end;
|
||||
}
|
||||
stops
|
||||
}
|
||||
|
||||
/// One bounded step through `stops`. Returns `None` at either end — movement never wraps, so a
|
||||
/// chapter boundary stays a boundary the footer can explain.
|
||||
pub(super) fn step_stop(stops: &[NavStop], current: Option<usize>, forward: bool) -> Option<usize> {
|
||||
if stops.is_empty() {
|
||||
return None;
|
||||
}
|
||||
match (current, forward) {
|
||||
(Some(index), true) => (index + 1 < stops.len()).then_some(index + 1),
|
||||
(Some(index), false) => index.checked_sub(1),
|
||||
(None, true) => Some(0),
|
||||
(None, false) => Some(stops.len() - 1),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn selected_file_row_count(
|
||||
position: &ReviewPosition,
|
||||
files: &[ReviewFile],
|
||||
fold: &Fold,
|
||||
) -> usize {
|
||||
position
|
||||
.file_id
|
||||
.as_ref()
|
||||
.and_then(|file_id| files.iter().find(|file| &file.id == file_id))
|
||||
.map(|file| visible_groups(file, fold).iter().map(VisibleGroup::rows).sum())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(super) fn finding_anchor_for_line(
|
||||
file: &ReviewFile,
|
||||
hunk: &ReviewHunk,
|
||||
line: &ReviewLine,
|
||||
) -> Option<FindingAnchor> {
|
||||
let (side, line_number) = match line.kind {
|
||||
ReviewLineKind::Deletion => (DiffSide::Old, line.old_line),
|
||||
ReviewLineKind::Addition => (DiffSide::New, line.new_line),
|
||||
ReviewLineKind::Context => (DiffSide::New, line.new_line.or(line.old_line)),
|
||||
ReviewLineKind::NoNewlineMarker => return None,
|
||||
};
|
||||
|
||||
line_number.map(|line_number| FindingAnchor::Line {
|
||||
file_id: file.id.clone(),
|
||||
hunk_id: hunk.id.clone(),
|
||||
side,
|
||||
line: line_number,
|
||||
context_hash: line.context_hash(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The widest line `file` holds, in terminal cells.
|
||||
pub(super) fn file_source_width(file: &ReviewFile) -> usize {
|
||||
file.hunks
|
||||
.iter()
|
||||
.flat_map(|hunk| hunk.lines.iter())
|
||||
.map(|line| crate::tabstop::display_width(&line.text))
|
||||
.max()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
160
crates/luxe-tui/src/guided_review/geometry/tests.rs
Normal file
160
crates/luxe-tui/src/guided_review/geometry/tests.rs
Normal file
@@ -0,0 +1,160 @@
|
||||
use super::*;
|
||||
use crate::fixture::{fixture_guided_review_scaled, fixture_large_guided_review};
|
||||
|
||||
/// Every stop a chapter offers has to survive being resolved through the index rather than by
|
||||
/// scanning — the whole change is a lookup, and a lookup that misses drops a hunk out of the
|
||||
/// walkthrough silently.
|
||||
#[test]
|
||||
fn an_indexed_lookup_finds_exactly_what_a_scan_did() {
|
||||
let review = fixture_large_guided_review();
|
||||
let index = StopIndex::of(&review);
|
||||
for chapter in &review.chapters {
|
||||
let indexed = chapter_stops(&review, chapter, &index);
|
||||
let scanned = chapter_stops_by_scanning(&review, chapter);
|
||||
assert_eq!(indexed, scanned, "chapter {:?}", chapter.title);
|
||||
assert!(!indexed.is_empty(), "chapter {:?} offers nothing to step to", chapter.title);
|
||||
}
|
||||
}
|
||||
|
||||
/// A chapter that names a file *and* one of its hunks lists that hunk once.
|
||||
#[test]
|
||||
fn a_repeated_item_earns_one_stop() {
|
||||
let mut review = fixture_large_guided_review();
|
||||
let file = review.files.iter().find(|file| !file.hunks.is_empty()).expect("a text file");
|
||||
let (file_id, hunk_id) = (file.id.clone(), file.hunks[0].id.clone());
|
||||
let chapter = &mut review.chapters[0];
|
||||
chapter.items = vec![
|
||||
ReviewItemRef::File(file_id),
|
||||
ReviewItemRef::Hunk(hunk_id),
|
||||
ReviewItemRef::Hunk(review.files[0].hunks[0].id.clone()),
|
||||
];
|
||||
|
||||
let review = review.clone();
|
||||
let stops = chapter_stops(&review, &review.chapters[0], &StopIndex::of(&review));
|
||||
let mut seen = stops.clone();
|
||||
seen.sort_by_key(|stop| (stop.file, stop.hunk));
|
||||
seen.dedup();
|
||||
assert_eq!(seen.len(), stops.len(), "a stop was listed twice: {stops:?}");
|
||||
}
|
||||
|
||||
/// An id the review no longer holds is skipped, not resolved to whatever sorts nearest.
|
||||
#[test]
|
||||
fn an_unknown_id_contributes_no_stop() {
|
||||
let mut review = fixture_large_guided_review();
|
||||
let ghost = FileId::from_path_lineage(None, Some(std::path::Path::new("gone.rs")));
|
||||
review.chapters[0].items = vec![ReviewItemRef::File(ghost)];
|
||||
let review = review.clone();
|
||||
|
||||
assert!(chapter_stops(&review, &review.chapters[0], &StopIndex::of(&review)).is_empty());
|
||||
}
|
||||
|
||||
/// Copies of the fixture have to be distinct items, or a scaling measurement taken against
|
||||
/// them measures a lookup collapsing duplicates rather than a review getting bigger.
|
||||
#[test]
|
||||
fn a_scaled_review_holds_distinct_items() {
|
||||
let single = fixture_large_guided_review();
|
||||
let quadruple = fixture_guided_review_scaled(4);
|
||||
assert_eq!(quadruple.files.len(), single.files.len() * 4);
|
||||
assert_eq!(quadruple.chapters.len(), single.chapters.len() * 4);
|
||||
|
||||
let index = StopIndex::of(&quadruple);
|
||||
assert_eq!(index.files.len(), quadruple.files.len(), "file ids collided");
|
||||
let hunks: usize = quadruple.files.iter().map(|file| file.hunks.len()).sum();
|
||||
assert_eq!(index.hunks.len(), hunks, "hunk ids collided");
|
||||
for chapter in &quadruple.chapters {
|
||||
assert!(
|
||||
!chapter_stops(&quadruple, chapter, &index).is_empty(),
|
||||
"a copy's chapter resolves to nothing, so its items point at another copy"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Each copy's chapter notes name that copy's items, and none of the original's.
|
||||
///
|
||||
/// The break this catches: scaling renamed the items but not the notes keyed to them, so every
|
||||
/// copy's notes pointed at the first copy's hunks.
|
||||
#[test]
|
||||
fn scaled_chapter_notes_name_only_that_copys_items() {
|
||||
let scaled = fixture_guided_review_scaled(3);
|
||||
for chapter in &scaled.chapters {
|
||||
let items: Vec<String> = chapter
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| match item {
|
||||
ReviewItemRef::Hunk(id) => id.as_str().to_owned(),
|
||||
ReviewItemRef::File(id) => id.as_str().to_owned(),
|
||||
})
|
||||
.collect();
|
||||
for note in &chapter.notes {
|
||||
assert!(items.contains(¬e.item), "a note names another copy's item");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A scaled review's totals are its own files', not one copy's.
|
||||
#[test]
|
||||
fn scaled_stats_equal_stats_derived_from_files() {
|
||||
let scaled = fixture_guided_review_scaled(3);
|
||||
let derived = luxe_core::guided_review::ReviewStats::from_files(&scaled.files);
|
||||
|
||||
let mut excluding = fixture_large_guided_review();
|
||||
excluding.stats.excluded_files = 2;
|
||||
let scaled_excluding = crate::fixture::scaled::scale(excluding, 3);
|
||||
assert_eq!(scaled_excluding.stats.excluded_files, 6, "each copy excludes what one does");
|
||||
assert_eq!((scaled.stats.files, scaled.stats.hunks), (derived.files, derived.hunks));
|
||||
assert_eq!(
|
||||
(scaled.stats.additions, scaled.stats.deletions),
|
||||
(derived.additions, derived.deletions)
|
||||
);
|
||||
}
|
||||
|
||||
/// A demo hunk's header counts every line on its side, context included.
|
||||
#[test]
|
||||
fn demo_hunk_ranges_count_context_on_each_side() {
|
||||
let review = crate::fixture::fixture_demo_guided_review();
|
||||
for hunk in review.files.iter().flat_map(|file| &file.hunks) {
|
||||
let old = hunk.lines.iter().filter(|line| line.old_line.is_some()).count() as u32;
|
||||
let new = hunk.lines.iter().filter(|line| line.new_line.is_some()).count() as u32;
|
||||
assert_eq!((hunk.old_range.count, hunk.new_range.count), (old, new));
|
||||
}
|
||||
}
|
||||
|
||||
/// What `chapter_stops` used to do: resolve every item by scanning the review.
|
||||
///
|
||||
/// Kept as the oracle the indexed version is checked against. It is also the shape the fix
|
||||
/// removed — quadratic in the review, and run once per chapter on every frame.
|
||||
fn chapter_stops_by_scanning(review: &GuidedReview, chapter: &ReviewChapter) -> Vec<NavStop> {
|
||||
let mut stops: Vec<NavStop> = Vec::new();
|
||||
let push = |stops: &mut Vec<NavStop>, stop: NavStop| {
|
||||
if !stops.contains(&stop) {
|
||||
stops.push(stop);
|
||||
}
|
||||
};
|
||||
for item in &chapter.items {
|
||||
match item {
|
||||
ReviewItemRef::File(file_id) => {
|
||||
let Some((index, file)) =
|
||||
review.files.iter().enumerate().find(|(_, file)| &file.id == file_id)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if file.non_text.is_some() {
|
||||
push(&mut stops, NavStop { file: index, hunk: None });
|
||||
} else {
|
||||
for hunk in 0..file.hunks.len() {
|
||||
push(&mut stops, NavStop { file: index, hunk: Some(hunk) });
|
||||
}
|
||||
}
|
||||
}
|
||||
ReviewItemRef::Hunk(hunk_id) => {
|
||||
for (index, file) in review.files.iter().enumerate() {
|
||||
if let Some(hunk) = file.hunks.iter().position(|hunk| &hunk.id == hunk_id) {
|
||||
push(&mut stops, NavStop { file: index, hunk: Some(hunk) });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
stops
|
||||
}
|
||||
315
crates/luxe-tui/src/guided_review/navigation.rs
Normal file
315
crates/luxe-tui/src/guided_review/navigation.rs
Normal file
@@ -0,0 +1,315 @@
|
||||
//! Guided Review navigation — line/page/column scrolling, hunk/chapter/file movement,
|
||||
//! and position reconciliation after a refresh.
|
||||
|
||||
mod scroll;
|
||||
mod search;
|
||||
mod selection;
|
||||
|
||||
use super::*;
|
||||
|
||||
impl GuidedReviewWorkspace {
|
||||
/// Selects the following hunk in reading order and anchors the diff at its header.
|
||||
///
|
||||
/// Past the chapter's last stop it carries on into the next chapter, short of generated churn.
|
||||
pub(crate) fn next_hunk(&mut self, review: &GuidedReview) {
|
||||
self.move_hunk(review, true);
|
||||
}
|
||||
|
||||
/// Selects the preceding hunk in reading order and anchors the diff at its header.
|
||||
pub(crate) fn previous_hunk(&mut self, review: &GuidedReview) {
|
||||
self.move_hunk(review, false);
|
||||
}
|
||||
|
||||
/// Whether the cursor sits on the chapter's last stop, so the footer can offer `]` instead of
|
||||
/// a dead key.
|
||||
pub(crate) fn at_scope_end(&self, review: &GuidedReview) -> bool {
|
||||
let stops = self.stops(review);
|
||||
step_stop(&stops, self.current_stop(review, &stops), true).is_none()
|
||||
}
|
||||
|
||||
/// Whether the cursor sits on the first stop the current scope allows.
|
||||
pub(crate) fn at_scope_start(&self, review: &GuidedReview) -> bool {
|
||||
let stops = self.stops(review);
|
||||
step_stop(&stops, self.current_stop(review, &stops), false).is_none()
|
||||
}
|
||||
|
||||
/// Selects the next semantic Guide chapter and its first reachable diff item.
|
||||
pub(crate) fn next_chapter(&mut self, review: &GuidedReview) {
|
||||
self.move_chapter(review, true);
|
||||
}
|
||||
|
||||
/// Selects the previous semantic Guide chapter and its first reachable diff item.
|
||||
pub(crate) fn previous_chapter(&mut self, review: &GuidedReview) {
|
||||
self.move_chapter(review, false);
|
||||
}
|
||||
|
||||
/// Selects the next file in scope.
|
||||
pub(crate) fn next_chapter_file(&mut self, review: &GuidedReview) {
|
||||
self.move_file(review, true);
|
||||
}
|
||||
|
||||
/// Selects the previous file in scope.
|
||||
pub(crate) fn previous_chapter_file(&mut self, review: &GuidedReview) {
|
||||
self.move_file(review, false);
|
||||
}
|
||||
|
||||
/// Enters the chapter under the guide cursor: its first stop, with the diff focused.
|
||||
pub(crate) fn enter_selected_chapter(&mut self, review: &GuidedReview) {
|
||||
let stops = self.stops(review);
|
||||
if let Some(first) = step_stop(&stops, None, true) {
|
||||
self.select_stop(review, stops[first]);
|
||||
}
|
||||
}
|
||||
|
||||
/// The chapter that scopes cursor movement.
|
||||
fn nav_scope<'a>(&self, review: &'a GuidedReview) -> Option<&'a ReviewChapter> {
|
||||
self.position
|
||||
.chapter_id
|
||||
.as_ref()
|
||||
.and_then(|id| review.chapters.iter().find(|chapter| &chapter.id == id))
|
||||
}
|
||||
|
||||
fn stops(&self, review: &GuidedReview) -> Vec<NavStop> {
|
||||
nav_stops(review, self.nav_scope(review), &self.fold, &StopIndex::of(review))
|
||||
}
|
||||
|
||||
fn current_stop(&self, review: &GuidedReview, stops: &[NavStop]) -> Option<usize> {
|
||||
let file_id = self.position.file_id.as_ref()?;
|
||||
stops.iter().position(|stop| {
|
||||
let file = &review.files[stop.file];
|
||||
&file.id == file_id
|
||||
&& match stop.hunk {
|
||||
Some(index) => self.position.hunk_id.as_ref() == Some(&file.hunks[index].id),
|
||||
None => self.position.hunk_id.is_none(),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn move_hunk(&mut self, review: &GuidedReview, forward: bool) {
|
||||
let stops = self.stops(review);
|
||||
let Some(target) = step_stop(&stops, self.current_stop(review, &stops), forward) else {
|
||||
// Nothing further in this section: the reading of it is done, and stepping carries on
|
||||
// into the next one. A boundary that ate the keystroke made the reviewer discover `]`
|
||||
// to keep reading, which is not a walkthrough.
|
||||
self.note_chapter_walked(review);
|
||||
self.step_chapter_boundary(review, forward);
|
||||
return;
|
||||
};
|
||||
self.select_stop(review, stops[target]);
|
||||
self.note_chapter_walked(review);
|
||||
}
|
||||
|
||||
/// Steps across a chapter boundary, landing on the neighboring section's first (or last)
|
||||
/// stop. The narration always owns the diff, because the chapter moves with the cursor.
|
||||
fn step_chapter_boundary(&mut self, review: &GuidedReview, forward: bool) {
|
||||
let Some((current, target)) = self.adjacent_chapter(review, forward) else {
|
||||
return;
|
||||
};
|
||||
// Stepping never *falls* into generated churn. The terminal bucket a large review folds its
|
||||
// leftovers into is real content `]` opens, but walking somebody through a lockfile because
|
||||
// they held `Space` is how a walkthrough loses its meaning.
|
||||
use luxe_core::guided_review::ChapterKind;
|
||||
if forward
|
||||
&& review.chapters[target].kind == ChapterKind::Generated
|
||||
&& review.chapters[current].kind != ChapterKind::Generated
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.position.chapter_id = Some(review.chapters[target].id.clone());
|
||||
let stops = self.stops(review);
|
||||
if let Some(index) = step_stop(&stops, None, forward) {
|
||||
self.select_stop(review, stops[index]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the cursor is in the whole walkthrough: `(step, total)` over the stops every section
|
||||
/// offers, so the reader can see the end coming.
|
||||
pub(crate) fn walkthrough_step(&self, review: &GuidedReview) -> Option<(usize, usize)> {
|
||||
let mut before = 0usize;
|
||||
let mut total = 0usize;
|
||||
let mut found = None;
|
||||
// One index for every chapter, not one per chapter: this runs on every frame.
|
||||
let index = StopIndex::of(review);
|
||||
for chapter in &review.chapters {
|
||||
let stops = nav_stops(review, Some(chapter), &self.fold, &index);
|
||||
if self.position.chapter_id.as_ref() == Some(&chapter.id) {
|
||||
found = self.current_stop(review, &stops).map(|index| before + index + 1);
|
||||
}
|
||||
if found.is_none() {
|
||||
before += stops.len();
|
||||
}
|
||||
total += stops.len();
|
||||
}
|
||||
found.map(|step| (step, total.max(step)))
|
||||
}
|
||||
|
||||
/// Moves the cursor onto a neighboring file within scope: forward lands on that file's first
|
||||
/// visible item, backward on the previous file's last one (reading up through the review).
|
||||
fn move_file(&mut self, review: &GuidedReview, forward: bool) {
|
||||
let stops = self.stops(review);
|
||||
let Some(current) = self.current_stop(review, &stops) else {
|
||||
let Some(target) = step_stop(&stops, None, forward) else {
|
||||
return;
|
||||
};
|
||||
self.select_stop(review, stops[target]);
|
||||
return;
|
||||
};
|
||||
let file = stops[current].file;
|
||||
let target = if forward {
|
||||
stops.iter().position(|stop| stop.file > file)
|
||||
} else {
|
||||
stops.iter().rposition(|stop| stop.file < file)
|
||||
};
|
||||
let Some(target) = target else {
|
||||
return;
|
||||
};
|
||||
self.select_stop(review, stops[target]);
|
||||
}
|
||||
|
||||
fn select_stop(&mut self, review: &GuidedReview, stop: NavStop) {
|
||||
let file = &review.files[stop.file];
|
||||
self.position.file_id = Some(file.id.clone());
|
||||
match stop.hunk {
|
||||
Some(index) => self.select_hunk(file, index),
|
||||
None => self.clear_hunk_selection(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The current chapter's index and its neighbor's in the direction of travel, or `None` at
|
||||
/// either end. Whether the neighbor may be entered is the caller's policy, not this lookup's.
|
||||
fn adjacent_chapter(&self, review: &GuidedReview, forward: bool) -> Option<(usize, usize)> {
|
||||
let current = self
|
||||
.position
|
||||
.chapter_id
|
||||
.as_ref()
|
||||
.and_then(|id| review.chapters.iter().position(|chapter| &chapter.id == id))?;
|
||||
let target = if forward {
|
||||
current.checked_add(1).filter(|index| *index < review.chapters.len())
|
||||
} else {
|
||||
current.checked_sub(1)
|
||||
}?;
|
||||
Some((current, target))
|
||||
}
|
||||
|
||||
fn move_chapter(&mut self, review: &GuidedReview, forward: bool) {
|
||||
let Some((_, target)) = self.adjacent_chapter(review, forward) else {
|
||||
return;
|
||||
};
|
||||
let chapter = &review.chapters[target];
|
||||
self.position.chapter_id = Some(chapter.id.clone());
|
||||
// Land on the new chapter's first stop; the scope is now the new chapter, so `step_stop`
|
||||
// with no current position gives exactly that. A chapter of nothing but collapsed churn
|
||||
// still has one stop per file, so the diff always follows the rail.
|
||||
let stops = self.stops(review);
|
||||
if let Some(first) = step_stop(&stops, None, true) {
|
||||
self.select_stop(review, stops[first]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod jump_tests {
|
||||
use super::*;
|
||||
use luxe_core::guided_review::{ChapterId, ChapterKind, ReviewChapter};
|
||||
|
||||
/// Two files of two hunks each, the second hunk of each holding `dos needle`. Chapter `first`
|
||||
/// holds each file's first hunk and `second` each file's second, so landing on a file does not
|
||||
/// by itself pick the right chapter.
|
||||
fn review() -> GuidedReview {
|
||||
let diff = |path: &str| {
|
||||
format!(
|
||||
"diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n\
|
||||
@@ -1,1 +1,1 @@\n-one\n+uno\n@@ -20,1 +20,1 @@\n-two needle\n+dos needle\n"
|
||||
)
|
||||
};
|
||||
let files = luxe_core::guided_review::parse_unified_diff(&(diff("a.rs") + &diff("b.rs")))
|
||||
.expect("the fixture parses")
|
||||
.files;
|
||||
let chapter = |title: &str, hunk: usize| ReviewChapter {
|
||||
id: ChapterId::from_item_keys("test", &[title]),
|
||||
title: title.into(),
|
||||
rationale: String::new(),
|
||||
impact: None,
|
||||
kind: ChapterKind::Core,
|
||||
items: files
|
||||
.iter()
|
||||
.map(|file| ReviewItemRef::Hunk(file.hunks[hunk].id.clone()))
|
||||
.collect(),
|
||||
notes: Vec::new(),
|
||||
};
|
||||
let mut review = crate::fixture::fixture_demo_guided_review();
|
||||
review.chapters = vec![chapter("first", 0), chapter("second", 1)];
|
||||
review.files = files;
|
||||
review
|
||||
}
|
||||
|
||||
fn at_start(review: &GuidedReview) -> GuidedReviewWorkspace {
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
workspace.position.file_id = Some(review.files[0].id.clone());
|
||||
workspace.position.hunk_id = Some(review.files[0].hunks[0].id.clone());
|
||||
workspace.position.chapter_id = Some(review.chapters[0].id.clone());
|
||||
workspace
|
||||
}
|
||||
|
||||
fn searching(workspace: &mut GuidedReviewWorkspace, query: &str) {
|
||||
workspace.begin_search();
|
||||
query.chars().for_each(|character| workspace.search_input(character));
|
||||
}
|
||||
|
||||
/// Where the cursor sits: `(file, hunk, chapter, row)` as indices into the fixture.
|
||||
fn at(
|
||||
workspace: &GuidedReviewWorkspace,
|
||||
review: &GuidedReview,
|
||||
) -> (usize, usize, usize, usize) {
|
||||
let position = &workspace.position;
|
||||
let file = review.files.iter().position(|f| Some(&f.id) == position.file_id.as_ref());
|
||||
let file = file.expect("on a file");
|
||||
let hunks = &review.files[file].hunks;
|
||||
let hunk = hunks.iter().position(|h| Some(&h.id) == position.hunk_id.as_ref());
|
||||
let chapter =
|
||||
review.chapters.iter().position(|c| Some(&c.id) == position.chapter_id.as_ref());
|
||||
(file, hunk.expect("on a hunk"), chapter.expect("in a chapter"), position.line_offset)
|
||||
}
|
||||
|
||||
/// A search hit in a later hunk of the same file takes the hunk and chapter with the row, and
|
||||
/// the next hunk key steps on from there.
|
||||
///
|
||||
/// The break this catches: search moved the row alone, so the hunk and the chapter stayed on
|
||||
/// the first hunk, and the next hunk key stepped from there.
|
||||
#[test]
|
||||
fn a_hit_in_a_later_hunk_moves_the_hunk_and_chapter_with_it() {
|
||||
let review = review();
|
||||
let mut workspace = at_start(&review);
|
||||
searching(&mut workspace, "dos needle");
|
||||
assert!(workspace.jump_search(&review, true));
|
||||
// header 0, two lines, header 3, `-two needle` 4, `+dos needle` 5
|
||||
assert_eq!(at(&workspace, &review), (0, 1, 1, 5));
|
||||
workspace.next_hunk(&review);
|
||||
let (file, hunk, chapter, _) = at(&workspace, &review);
|
||||
assert_eq!((file, hunk, chapter), (1, 1, 1), "the chapter's next hunk, in the next file");
|
||||
}
|
||||
|
||||
/// A hit in another file's later hunk lands there whole: row, hunk and chapter.
|
||||
#[test]
|
||||
fn a_hit_across_files_lands_on_its_own_hunk() {
|
||||
let review = review();
|
||||
let mut workspace = at_start(&review);
|
||||
workspace.position.line_offset = 5; // past the first file's hit
|
||||
searching(&mut workspace, "dos needle");
|
||||
assert!(workspace.jump_search(&review, true));
|
||||
assert_eq!(at(&workspace, &review), (1, 1, 1, 5));
|
||||
}
|
||||
|
||||
/// A clicked row is a jump like a search hit: its hunk and chapter follow it.
|
||||
#[test]
|
||||
fn a_clicked_row_moves_the_hunk_and_chapter_with_it() {
|
||||
let review = review();
|
||||
let mut app =
|
||||
crate::fixture::seeded_app("nord", crate::fixture::FixtureScenario::GuidedReviewSplit)
|
||||
.expect("fixture");
|
||||
app.guided_review_workspace = at_start(&review);
|
||||
app.guided_review = Some(Box::new(review.clone()));
|
||||
app.update(crate::app::Msg::GuidedReviewSelectDiffRow(4));
|
||||
assert_eq!(at(&app.guided_review_workspace, &review), (0, 1, 1, 4));
|
||||
}
|
||||
}
|
||||
100
crates/luxe-tui/src/guided_review/navigation/scroll.rs
Normal file
100
crates/luxe-tui/src/guided_review/navigation/scroll.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
//! Review scrolling — the diff's rows and columns, and the hunk the cursor lands in.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl GuidedReviewWorkspace {
|
||||
/// Returns horizontally clipped diff source lines to their first terminal cell.
|
||||
pub(crate) fn reset_column_offset(&mut self) {
|
||||
self.diff_column_offset = 0;
|
||||
}
|
||||
|
||||
/// Moves the selected file's source right by one bounded terminal-cell step, in whichever
|
||||
/// layout it is drawn.
|
||||
pub(crate) fn next_column(&mut self, files: &[ReviewFile]) {
|
||||
let maximum = self.selected_file(files).map_or(0, |file| self.column_maximum(file));
|
||||
self.diff_column_offset =
|
||||
self.diff_column_offset.saturating_add(COLUMN_SCROLL_STEP).min(maximum);
|
||||
}
|
||||
|
||||
/// Clamps horizontal position after a resize or presentation change.
|
||||
pub(crate) fn clamp_column_offset(&mut self, files: &[ReviewFile]) {
|
||||
let maximum = self.selected_file(files).map_or(0, |file| self.column_maximum(file));
|
||||
self.diff_column_offset = self.diff_column_offset.min(maximum);
|
||||
}
|
||||
|
||||
/// Moves the selected diff source left by one terminal-cell step without underflow.
|
||||
pub(crate) fn previous_column(&mut self) {
|
||||
self.diff_column_offset = self.diff_column_offset.saturating_sub(COLUMN_SCROLL_STEP);
|
||||
}
|
||||
|
||||
/// Puts the cursor on the row `pick` chooses out of the furthest it can go, the way a drag on
|
||||
/// the diff's scrollbar does.
|
||||
pub(crate) fn scroll_to_row(
|
||||
&mut self,
|
||||
review: &GuidedReview,
|
||||
pick: impl FnOnce(usize) -> usize,
|
||||
) {
|
||||
let files = &review.files;
|
||||
let max_offset =
|
||||
selected_file_row_count(&self.position, files, &self.fold).saturating_sub(1);
|
||||
self.position.line_offset = pick(max_offset).min(max_offset);
|
||||
self.sync_hunk_to_offset(files);
|
||||
}
|
||||
|
||||
/// Scrolls the diff within the selected file, stopping at either end.
|
||||
///
|
||||
/// Never rolls into the neighboring file: the pane draws one file at a time, so one row too
|
||||
/// many would silently move you to a diff you did not mean to be in. Moving between files is
|
||||
/// what the explicit keys are for (`Space`/`n`, `[`/`]`, `Ctrl+↑/↓`), which keep the narration
|
||||
/// and the reviewed marks in step; scrolling is only ever a look around.
|
||||
pub(in crate::guided_review) fn scroll_lines(
|
||||
&mut self,
|
||||
review: &GuidedReview,
|
||||
amount: usize,
|
||||
forward: bool,
|
||||
) {
|
||||
let files = &review.files;
|
||||
let max_offset =
|
||||
selected_file_row_count(&self.position, files, &self.fold).saturating_sub(1);
|
||||
self.position.line_offset = if forward {
|
||||
self.position.line_offset.saturating_add(amount).min(max_offset)
|
||||
} else {
|
||||
self.position.line_offset.saturating_sub(amount)
|
||||
};
|
||||
self.sync_hunk_to_offset(files);
|
||||
}
|
||||
|
||||
/// Re-points the selection at whatever the cursor row now sits inside, after the row space
|
||||
/// changed underneath it (a fold opening or closing).
|
||||
pub(crate) fn sync_hunk_to_cursor(&mut self, files: &[ReviewFile]) {
|
||||
let rows = selected_file_row_count(&self.position, files, &self.fold);
|
||||
self.position.line_offset = self.position.line_offset.min(rows.saturating_sub(1));
|
||||
self.sync_hunk_to_offset(files);
|
||||
}
|
||||
|
||||
/// Keeps the selected hunk pointing at whatever the cursor row now sits inside, so the
|
||||
/// breadcrumb and reviewed marker follow a continuous scroll.
|
||||
pub(super) fn sync_hunk_to_offset(&mut self, files: &[ReviewFile]) {
|
||||
let Some(file) =
|
||||
self.position.file_id.as_ref().and_then(|id| files.iter().find(|file| &file.id == id))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut row = 0usize;
|
||||
for group in visible_groups(file, &self.fold) {
|
||||
let span = group.rows();
|
||||
if self.position.line_offset < row + span {
|
||||
// A collapsed run belongs to no hunk, so the breadcrumb drops to the file.
|
||||
let landed = match group {
|
||||
VisibleGroup::Hunk(hunk) => Some(hunk.id.clone()),
|
||||
VisibleGroup::Folded(_) => None,
|
||||
};
|
||||
if self.position.hunk_id != landed {
|
||||
self.position.hunk_id = landed;
|
||||
}
|
||||
return;
|
||||
}
|
||||
row += span;
|
||||
}
|
||||
}
|
||||
}
|
||||
126
crates/luxe-tui/src/guided_review/navigation/search.rs
Normal file
126
crates/luxe-tui/src/guided_review/navigation/search.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
//! Review search — the query, the rows it matches, and jumping between them.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl GuidedReviewWorkspace {
|
||||
/// Opens the in-diff search prompt with an empty query.
|
||||
pub(crate) fn begin_search(&mut self) {
|
||||
self.search = Some(String::new());
|
||||
}
|
||||
|
||||
pub(crate) fn search_input(&mut self, character: char) {
|
||||
if let Some(query) = self.search.as_mut() {
|
||||
query.push(character);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn search_backspace(&mut self) {
|
||||
if let Some(query) = self.search.as_mut() {
|
||||
query.pop();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cancel_search(&mut self) {
|
||||
self.search = None;
|
||||
}
|
||||
|
||||
/// Whether a source line matches the active (non-empty) search query, case-insensitively.
|
||||
pub(crate) fn line_matches_search(&self, text: &str) -> bool {
|
||||
self.search
|
||||
.as_ref()
|
||||
.filter(|query| !query.is_empty())
|
||||
.is_some_and(|query| text.to_lowercase().contains(&query.to_lowercase()))
|
||||
}
|
||||
|
||||
/// Visible-row indices in `file` whose source text matches `needle` (already lowercased),
|
||||
/// counted like `line_offset` (hunk header + lines, respecting noise folding) so a match row
|
||||
/// is jumpable.
|
||||
fn file_match_rows(&self, file: &ReviewFile, needle: &str) -> Vec<usize> {
|
||||
let mut rows = Vec::new();
|
||||
let mut row = 0usize;
|
||||
for group in visible_groups(file, &self.fold) {
|
||||
let VisibleGroup::Hunk(hunk) = group else {
|
||||
row += 1;
|
||||
continue;
|
||||
};
|
||||
row += 1; // hunk header
|
||||
for line in &hunk.lines {
|
||||
if crate::tabstop::display_text(&line.text).to_lowercase().contains(needle) {
|
||||
rows.push(row);
|
||||
}
|
||||
row += 1;
|
||||
}
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// Visible-row indices in the selected file whose source text matches the query.
|
||||
fn current_file_match_rows(&self, files: &[ReviewFile], query: &str) -> Vec<usize> {
|
||||
let Some(file) =
|
||||
self.position.file_id.as_ref().and_then(|id| files.iter().find(|f| &f.id == id))
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
self.file_match_rows(file, &query.to_lowercase())
|
||||
}
|
||||
|
||||
/// Jumps the diff cursor to the next/previous search match. Prefers a match past the cursor in
|
||||
/// the selected file, then walks to the next/previous file (cyclically) that has a match,
|
||||
/// landing on its first (forward) / last (backward) hit; the final step wraps within the
|
||||
/// current file. Returns whether a match was found anywhere.
|
||||
///
|
||||
/// Find-in-diff is deliberately whole-review, so a hit outside the current chapter re-points
|
||||
/// the narrative rather than showing a chapter that does not own the match.
|
||||
pub(crate) fn jump_search(&mut self, review: &GuidedReview, forward: bool) -> bool {
|
||||
let files = &review.files;
|
||||
let Some(query) = self.search.as_ref().filter(|q| !q.is_empty()).cloned() else {
|
||||
return false;
|
||||
};
|
||||
let needle = query.to_lowercase();
|
||||
|
||||
// A match strictly past the cursor in the current file wins first.
|
||||
let current_rows = self.current_file_match_rows(files, &query);
|
||||
let current = self.position.line_offset;
|
||||
let within = if forward {
|
||||
current_rows.iter().copied().find(|&row| row > current)
|
||||
} else {
|
||||
current_rows.iter().copied().rev().find(|&row| row < current)
|
||||
};
|
||||
if let Some(target) = within {
|
||||
self.select_diff_row(review, target);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Otherwise scan the other files in order (wrapping); the last step revisits the current
|
||||
// file, so a single-file query still wraps to its first/last match.
|
||||
if files.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let count = files.len();
|
||||
let current_index = self
|
||||
.position
|
||||
.file_id
|
||||
.as_ref()
|
||||
.and_then(|id| files.iter().position(|file| &file.id == id))
|
||||
.unwrap_or(0);
|
||||
for step in 1..=count {
|
||||
let index = if forward {
|
||||
(current_index + step) % count
|
||||
} else {
|
||||
(current_index + count - step) % count
|
||||
};
|
||||
let rows = self.file_match_rows(&files[index], &needle);
|
||||
let target = if forward { rows.first().copied() } else { rows.last().copied() };
|
||||
let Some(target) = target else {
|
||||
continue;
|
||||
};
|
||||
if index != current_index {
|
||||
let file_id = files[index].id.clone();
|
||||
self.select_file_by_id(review, &file_id);
|
||||
}
|
||||
self.select_diff_row(review, target);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
228
crates/luxe-tui/src/guided_review/navigation/selection.rs
Normal file
228
crates/luxe-tui/src/guided_review/navigation/selection.rs
Normal file
@@ -0,0 +1,228 @@
|
||||
//! Review selection — what a click or a jump selects, and where the position lands after a
|
||||
//! refresh.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl GuidedReviewWorkspace {
|
||||
/// Moves the cursor to `offset` as an explicit jump does (a click, a search hit): within the
|
||||
/// file's rows, the hunk following the row and the chapter following the hunk.
|
||||
pub(crate) fn select_diff_row(&mut self, review: &GuidedReview, offset: usize) {
|
||||
let rows = selected_file_row_count(&self.position, &review.files, &self.fold);
|
||||
self.position.line_offset = offset.min(rows.saturating_sub(1));
|
||||
self.sync_hunk_to_offset(&review.files);
|
||||
self.sync_chapter_to_selection(review);
|
||||
}
|
||||
|
||||
/// Points the review at one place in the guide: a chapter, or a file inside one.
|
||||
///
|
||||
/// The only way in from outside the stepping keys — a click on a guide row, a jump from a
|
||||
/// finding. There is nothing to "open" afterwards, because the detail pane already shows
|
||||
/// whatever the position lands on.
|
||||
pub(crate) fn open_guide_target(
|
||||
&mut self,
|
||||
review: &GuidedReview,
|
||||
file_id: Option<&FileId>,
|
||||
hunk_id: Option<&HunkId>,
|
||||
chapter_id: Option<&ChapterId>,
|
||||
) {
|
||||
if let Some(chapter_id) = chapter_id {
|
||||
self.position.chapter_id = Some(chapter_id.clone());
|
||||
let stops = self.stops(review);
|
||||
if let Some(first) = step_stop(&stops, None, true) {
|
||||
self.select_stop(review, stops[first]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(file_id) = file_id else {
|
||||
return;
|
||||
};
|
||||
let Some(file) = review.files.iter().find(|file| &file.id == file_id) else {
|
||||
return;
|
||||
};
|
||||
match hunk_id.and_then(|id| file.hunks.iter().position(|hunk| &hunk.id == id)) {
|
||||
Some(index) => self.select_finding_hunk(file, index, None),
|
||||
None => self.select_file_by_id(review, file_id),
|
||||
}
|
||||
self.sync_chapter_to_selection(review);
|
||||
}
|
||||
|
||||
/// Selects a file by id (a click on its rail row): makes it current, focuses
|
||||
/// its first visible hunk, and re-points the narrative at the owning chapter. Reveals folded
|
||||
/// content when that is the only way to show the file. No-op for an unknown or empty file.
|
||||
pub(crate) fn select_file_by_id(&mut self, review: &GuidedReview, file_id: &FileId) {
|
||||
let Some(file) = review.files.iter().find(|file| &file.id == file_id) else {
|
||||
return;
|
||||
};
|
||||
if file.non_text.is_none() && file.hunks.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.position.file_id = Some(file.id.clone());
|
||||
// Land on the first hunk the fold leaves open rather than opening the file's churn just
|
||||
// because it happens to sort first.
|
||||
match file.hunks.iter().position(|hunk| !self.fold.hides(file, hunk)) {
|
||||
Some(index) => self.select_hunk(file, index),
|
||||
None => self.clear_hunk_selection(),
|
||||
}
|
||||
self.sync_chapter_to_selection(review);
|
||||
}
|
||||
|
||||
pub(in crate::guided_review) fn select_finding_hunk(
|
||||
&mut self,
|
||||
file: &ReviewFile,
|
||||
index: usize,
|
||||
line_index: Option<usize>,
|
||||
) {
|
||||
self.reveal_if_folded(file, &file.hunks[index]);
|
||||
self.position.file_id = Some(file.id.clone());
|
||||
self.position.hunk_id = Some(file.hunks[index].id.clone());
|
||||
self.position.line_offset = visible_row_offset(file, index, &self.fold)
|
||||
.saturating_add(usize::from(line_index.is_some()))
|
||||
.saturating_add(line_index.unwrap_or_default());
|
||||
}
|
||||
|
||||
pub(super) fn select_hunk(&mut self, file: &ReviewFile, index: usize) {
|
||||
let hunk_id = file.hunks[index].id.clone();
|
||||
self.position.hunk_id = Some(hunk_id);
|
||||
self.position.line_offset = visible_row_offset(file, index, &self.fold);
|
||||
// A no-op within one file; arriving at a narrower one, it keeps the code on screen
|
||||
self.diff_column_offset = self.diff_column_offset.min(self.column_maximum(file));
|
||||
}
|
||||
|
||||
pub(super) fn clear_hunk_selection(&mut self) {
|
||||
self.position.hunk_id = None;
|
||||
self.position.line_offset = 0;
|
||||
}
|
||||
|
||||
/// Re-points the narrative at the chapter owning the current selection.
|
||||
///
|
||||
/// Bounded stepping is scoped and can never leave a chapter, but an explicit jump (a click,
|
||||
/// next-unreviewed, a finding anchor, a search hit) can — and a rail describing chapter 01
|
||||
/// beside chapter 03's diff is worse than no narrative at all.
|
||||
pub(in crate::guided_review) fn sync_chapter_to_selection(&mut self, review: &GuidedReview) {
|
||||
let owning = review.chapters.iter().find(|chapter| {
|
||||
chapter.items.iter().any(|item| match item {
|
||||
ReviewItemRef::Hunk(hunk_id) => self.position.hunk_id.as_ref() == Some(hunk_id),
|
||||
ReviewItemRef::File(file_id) => {
|
||||
self.position.hunk_id.is_none()
|
||||
&& self.position.file_id.as_ref() == Some(file_id)
|
||||
}
|
||||
})
|
||||
});
|
||||
if let Some(chapter) = owning {
|
||||
self.position.chapter_id = Some(chapter.id.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens collapsed content when an explicit jump targets a hunk the fold is hiding, so a
|
||||
/// selection always shows the thing it selected — and only that file, not the whole review.
|
||||
fn reveal_if_folded(&mut self, file: &ReviewFile, hunk: &ReviewHunk) {
|
||||
self.fold.reveal(file, hunk);
|
||||
}
|
||||
|
||||
pub(in crate::guided_review) fn reconcile_folded_selection(&mut self, files: &[ReviewFile]) {
|
||||
let hunks = files
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(file_index, file)| {
|
||||
file.hunks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(move |(hunk_index, hunk)| (file_index, hunk_index, hunk.id.clone()))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let Some(start) = self
|
||||
.position
|
||||
.hunk_id
|
||||
.as_ref()
|
||||
.and_then(|selected| hunks.iter().position(|(_, _, hunk_id)| hunk_id == selected))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some((file_index, hunk_index, _)) =
|
||||
hunks.iter().cycle().skip(start).take(hunks.len()).find(
|
||||
|(file_index, hunk_index, _)| {
|
||||
let file = &files[*file_index];
|
||||
!self.fold.hides(file, &file.hunks[*hunk_index])
|
||||
},
|
||||
)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let (file_index, hunk_index) = (*file_index, *hunk_index);
|
||||
let file = &files[file_index];
|
||||
self.position.file_id = Some(file.id.clone());
|
||||
self.select_hunk(file, hunk_index);
|
||||
}
|
||||
|
||||
/// Keeps a semantic chapter selection when its stable identity survives refresh.
|
||||
pub(crate) fn reconcile_chapter(&mut self, chapters: &[ReviewChapter]) {
|
||||
if self
|
||||
.position
|
||||
.chapter_id
|
||||
.as_ref()
|
||||
.is_some_and(|id| chapters.iter().any(|chapter| &chapter.id == id))
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.position.chapter_id = chapters.first().map(|chapter| chapter.id.clone());
|
||||
}
|
||||
|
||||
pub(crate) fn reconcile_position(&mut self, files: &[ReviewFile]) {
|
||||
self.fold.reconcile(files);
|
||||
let retained = self.position.file_id.as_ref().and_then(|file_id| {
|
||||
files.iter().find(|file| &file.id == file_id).and_then(|file| {
|
||||
match &self.position.hunk_id {
|
||||
Some(hunk_id) => file
|
||||
.hunks
|
||||
.iter()
|
||||
.any(|hunk| &hunk.id == hunk_id)
|
||||
.then(|| (file_id.clone(), Some(hunk_id.clone()))),
|
||||
None if file.non_text.is_some() => Some((file_id.clone(), None)),
|
||||
None => None,
|
||||
}
|
||||
})
|
||||
});
|
||||
// Open on something the reviewer can actually read: the first hunk the fold leaves open,
|
||||
// then a non-text item, and only then a file that is nothing but collapsed churn. Landing
|
||||
// on a collapsed hunk would open the review on a blank pane.
|
||||
let next = retained.or_else(|| {
|
||||
files
|
||||
.iter()
|
||||
.find_map(|file| {
|
||||
file.hunks
|
||||
.iter()
|
||||
.find(|hunk| !self.fold.hides(file, hunk))
|
||||
.map(|hunk| (file.id.clone(), Some(hunk.id.clone())))
|
||||
})
|
||||
.or_else(|| {
|
||||
files
|
||||
.iter()
|
||||
.find(|file| file.non_text.is_some())
|
||||
.map(|file| (file.id.clone(), None))
|
||||
})
|
||||
.or_else(|| {
|
||||
files
|
||||
.iter()
|
||||
.find(|file| file.is_text() && !file.hunks.is_empty())
|
||||
.map(|file| (file.id.clone(), None))
|
||||
})
|
||||
});
|
||||
|
||||
match next {
|
||||
Some((file_id, hunk_id))
|
||||
if self.position.file_id.as_ref() == Some(&file_id)
|
||||
&& self.position.hunk_id == hunk_id => {}
|
||||
Some((file_id, hunk_id)) => {
|
||||
self.position = ReviewPosition {
|
||||
chapter_id: self.position.chapter_id.clone(),
|
||||
file_id: Some(file_id),
|
||||
hunk_id,
|
||||
line_offset: 0,
|
||||
};
|
||||
}
|
||||
None => {
|
||||
self.position = ReviewPosition::default();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
73
crates/luxe-tui/src/guided_review/preview_guard.rs
Normal file
73
crates/luxe-tui/src/guided_review/preview_guard.rs
Normal file
@@ -0,0 +1,73 @@
|
||||
//! Preview guard — a review dialog the reader cannot see takes only esc.
|
||||
//!
|
||||
//! A confirm the reader cannot see is not one, so what the last frame drew is recorded by the view
|
||||
//! and read by the keys. Every frame that draws the review settles it: below the surface's minimum
|
||||
//! nothing is drawn and every open dialog waits, and above it a preview drawn or a notice standing
|
||||
//! in for one says which. It guards open dialogs only, and the review's keys are read only while
|
||||
//! it is the view, so nothing is held back outside it.
|
||||
|
||||
use super::GuidedReviewWorkspace;
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
|
||||
/// What the last frame of the review drew.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Drawn {
|
||||
/// The open preview, or there was none to draw
|
||||
pub(crate) preview: bool,
|
||||
/// The surface at all, rather than its minimum-size notice
|
||||
pub(crate) surface: bool,
|
||||
}
|
||||
|
||||
impl Drawn {
|
||||
/// Everything, as before a first frame.
|
||||
pub(crate) const ALL: Self = Self { preview: true, surface: true };
|
||||
}
|
||||
|
||||
impl GuidedReviewWorkspace {
|
||||
/// Whether a dialog that fits itself to the screen is open: the finish dialog, a finding's
|
||||
/// details, or a confirming preview — stack, worktree fix, thread answers or the post.
|
||||
fn previewing(&self) -> bool {
|
||||
self.finish_review_choice.is_some()
|
||||
|| (self.findings_visible && self.finding_details_visible)
|
||||
|| self.stack_opening.is_some()
|
||||
|| self.pull_request_fix.is_some()
|
||||
|| self.thread_answers.is_some()
|
||||
|| self.github_post.is_some()
|
||||
}
|
||||
|
||||
/// Whether anything that acts on a key is open over the review: a dialog, a composer, the
|
||||
/// feedback window (whose `x` deletes), or the source picker and its reference prompt.
|
||||
fn dialog_open(&self) -> bool {
|
||||
self.previewing()
|
||||
|| self.send_preview.is_some()
|
||||
|| self.commit_preview.is_some()
|
||||
|| self.pull_request_opening.is_some()
|
||||
|| self.finding_draft.is_some()
|
||||
|| self.findings_visible
|
||||
|| self.selected_source_picker().is_some()
|
||||
|| self.source_reference_entry.is_some()
|
||||
}
|
||||
|
||||
/// Starts a frame: whether the surface fits at all, and no preview drawn yet. Returns `fits`.
|
||||
pub(crate) fn settle_surface(&self, fits: bool) -> bool {
|
||||
self.drawn.set(Drawn { preview: !self.previewing(), surface: fits });
|
||||
fits
|
||||
}
|
||||
|
||||
/// Records whether the open preview drew this frame.
|
||||
pub(crate) fn settle_preview(&self, drawn: bool) {
|
||||
let surface = self.drawn.get().surface;
|
||||
self.drawn.set(Drawn { preview: drawn || !self.previewing(), surface });
|
||||
}
|
||||
|
||||
/// Whether `key` is swallowed because the dialog it would reach was not drawn: every open
|
||||
/// dialog below the surface's minimum, or a preview behind its notice. A summary composer
|
||||
/// opened over the post is drawn on its own, so it keeps its keys while the surface is drawn.
|
||||
pub(crate) fn hidden_preview_takes(&self, key: KeyEvent) -> bool {
|
||||
let drawn = self.drawn.get();
|
||||
let composing = self.github_post.is_some() && self.finding_draft.is_some();
|
||||
let undrawn = !drawn.surface && self.dialog_open();
|
||||
let hidden = undrawn || (!drawn.preview && self.previewing() && !composing);
|
||||
hidden && key.code != KeyCode::Esc
|
||||
}
|
||||
}
|
||||
130
crates/luxe-tui/src/guided_review/progress.rs
Normal file
130
crates/luxe-tui/src/guided_review/progress.rs
Normal file
@@ -0,0 +1,130 @@
|
||||
//! Guided Review progress — which chapters the reviewer has walked, and the pending send preview.
|
||||
//!
|
||||
//! Progress is deliberately chapter-shaped. Per-hunk reviewed marks made the review an inspection
|
||||
//! with a completion target ("Reviewed 0/92"), which is a task nobody can finish on an agent-scale
|
||||
//! change and which makes the correct behavior — read the core sections closely, judge the rest —
|
||||
//! look like failure. What a resumed review needs is where the reading stopped.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl GuidedReviewWorkspace {
|
||||
/// Marks the current chapter walked once the cursor has nothing further to offer in it.
|
||||
pub(super) fn note_chapter_walked(&mut self, review: &GuidedReview) {
|
||||
if let Some(chapter_id) = self.position.chapter_id.clone() {
|
||||
if self.at_scope_end(review) {
|
||||
self.walked_chapters.insert(chapter_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_chapter_walked(&self, chapter: &ChapterId) -> bool {
|
||||
self.walked_chapters.contains(chapter)
|
||||
}
|
||||
|
||||
/// `(walked, total)` chapters, the review's only progress readout.
|
||||
pub(crate) fn chapters_walked(&self, review: &GuidedReview) -> (usize, usize) {
|
||||
let walked = review
|
||||
.chapters
|
||||
.iter()
|
||||
.filter(|chapter| self.walked_chapters.contains(&chapter.id))
|
||||
.count();
|
||||
(walked, review.chapters.len())
|
||||
}
|
||||
|
||||
/// Snapshots progress for persistence with the feedback session.
|
||||
pub(crate) fn progress_state(
|
||||
&self,
|
||||
review: &GuidedReview,
|
||||
) -> luxe_core::guided_review::ReviewProgress {
|
||||
let mut walked_chapter_ids: Vec<ChapterId> = review
|
||||
.chapters
|
||||
.iter()
|
||||
.filter(|chapter| self.walked_chapters.contains(&chapter.id))
|
||||
.map(|chapter| chapter.id.clone())
|
||||
.collect();
|
||||
walked_chapter_ids.sort_by(|left, right| left.as_str().cmp(right.as_str()));
|
||||
luxe_core::guided_review::ReviewProgress {
|
||||
walked_chapter_ids,
|
||||
// Written only when a review is finished; a session that is still open has not "seen"
|
||||
// anything it can subtract from the next one.
|
||||
seen_item_ids: Vec::new(),
|
||||
seen_revision: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Restores which chapters were walked, keeping only chapters the pinned source still has.
|
||||
pub(crate) fn restore_progress(
|
||||
&mut self,
|
||||
progress: &luxe_core::guided_review::ReviewProgress,
|
||||
chapters: &[ReviewChapter],
|
||||
) {
|
||||
self.walked_chapters = chapters
|
||||
.iter()
|
||||
.filter(|chapter| progress.walked_chapter_ids.contains(&chapter.id))
|
||||
.map(|chapter| chapter.id.clone())
|
||||
.collect();
|
||||
}
|
||||
|
||||
/// Drops walked marks for chapters a refresh has replaced.
|
||||
pub(crate) fn reconcile_walked_chapters(&mut self, chapters: &[ReviewChapter]) {
|
||||
self.walked_chapters.retain(|walked| chapters.iter().any(|chapter| &chapter.id == walked));
|
||||
}
|
||||
}
|
||||
|
||||
impl GuidedReviewWorkspace {
|
||||
/// Opens the send preview. `outcome`/`mode` are set only when the Finish dialog opened it.
|
||||
///
|
||||
/// Nothing is dispatched unseen: the reviewer confirms exactly which comments travel, which is
|
||||
/// how silent drops went unnoticed before.
|
||||
pub(crate) fn open_send_preview(
|
||||
&mut self,
|
||||
outcome: Option<luxe_core::guided_review::ReviewOutcome>,
|
||||
mode: Option<luxe_core::guided_review::ReviewFeedbackMode>,
|
||||
) {
|
||||
self.feedback_scroll = 0;
|
||||
self.send_preview = Some(SendPreview {
|
||||
excluded: std::collections::HashSet::new(),
|
||||
selected: 0,
|
||||
outcome,
|
||||
mode,
|
||||
});
|
||||
self.help_visible = false;
|
||||
self.close_feedback_window();
|
||||
self.finish_review_choice = None;
|
||||
}
|
||||
|
||||
/// Closes the send preview without dispatching.
|
||||
pub(crate) fn close_send_preview(&mut self) {
|
||||
self.send_preview = None;
|
||||
}
|
||||
|
||||
/// Moves the preview cursor through the candidate comments.
|
||||
pub(crate) fn move_send_preview(&mut self, rows: usize, forward: bool) {
|
||||
self.feedback_scroll = 0;
|
||||
let Some(preview) = self.send_preview.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if rows == 0 {
|
||||
preview.selected = 0;
|
||||
return;
|
||||
}
|
||||
preview.selected = if forward {
|
||||
(preview.selected + 1) % rows
|
||||
} else {
|
||||
preview.selected.checked_sub(1).unwrap_or(rows - 1)
|
||||
};
|
||||
}
|
||||
|
||||
/// Includes or excludes the comment under the preview cursor.
|
||||
pub(crate) fn toggle_send_preview_row(&mut self, candidates: &[FindingId]) {
|
||||
let Some(preview) = self.send_preview.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let Some(finding_id) = candidates.get(preview.selected) else {
|
||||
return;
|
||||
};
|
||||
if !preview.excluded.insert(finding_id.clone()) {
|
||||
preview.excluded.remove(finding_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
23
crates/luxe-tui/src/guided_review/source.rs
Normal file
23
crates/luxe-tui/src/guided_review/source.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
//! Review source — loading a review, and what the surface says when it is ready or failed.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl GuidedReviewWorkspace {
|
||||
/// Starts displaying a target without discarding any pinned review already on screen.
|
||||
pub(crate) fn begin_loading(&mut self, target: ReviewTarget) {
|
||||
self.source_picker = ReviewSourcePickerState::Closed;
|
||||
self.source_reference_entry = None;
|
||||
self.load_state = GuidedReviewLoadState::Loading { target };
|
||||
}
|
||||
|
||||
/// Records that the active target produced a ready pinned review.
|
||||
pub(crate) fn mark_ready(&mut self) {
|
||||
self.load_state = GuidedReviewLoadState::Ready;
|
||||
self.noise_details_visible = false;
|
||||
}
|
||||
|
||||
/// Records a typed source failure for recovery controls.
|
||||
pub(crate) fn mark_failed(&mut self, target: ReviewTarget, error: GuidedReviewFailure) {
|
||||
self.load_state = GuidedReviewLoadState::Failed { target, error };
|
||||
}
|
||||
}
|
||||
127
crates/luxe-tui/src/guided_review/source_picker.rs
Normal file
127
crates/luxe-tui/src/guided_review/source_picker.rs
Normal file
@@ -0,0 +1,127 @@
|
||||
//! The source picker — choosing what a review covers, and the reference field it opens for a base
|
||||
//! or a commit.
|
||||
|
||||
use super::{
|
||||
GuidedReviewWorkspace, ReviewSourcePickerSelection, ReviewSourcePickerState,
|
||||
ReviewSourceReferenceEntry, ReviewSourceReferenceKind,
|
||||
};
|
||||
use luxe_core::guided_review::ReviewTarget;
|
||||
|
||||
impl GuidedReviewWorkspace {
|
||||
/// Opens or closes the local source picker without mutating the pinned review.
|
||||
pub(crate) fn toggle_source_picker(&mut self) {
|
||||
self.source_picker = match self.source_picker {
|
||||
ReviewSourcePickerState::Closed => ReviewSourcePickerState::Open {
|
||||
selection: ReviewSourcePickerSelection::picker_order()[0],
|
||||
},
|
||||
ReviewSourcePickerState::Open { .. } => {
|
||||
self.source_reference_entry = None;
|
||||
ReviewSourcePickerState::Closed
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Whether the source picker is open.
|
||||
pub(crate) fn source_picker_open(&self) -> bool {
|
||||
matches!(self.source_picker, ReviewSourcePickerState::Open { .. })
|
||||
}
|
||||
|
||||
/// Whether the source reference field is open.
|
||||
pub(crate) fn source_reference_open(&self) -> bool {
|
||||
self.source_reference_entry.is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn selected_source_picker(&self) -> Option<ReviewSourcePickerSelection> {
|
||||
match self.source_picker {
|
||||
ReviewSourcePickerState::Closed => None,
|
||||
ReviewSourcePickerState::Open { selection } => Some(selection),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn begin_source_reference_entry(&mut self, kind: ReviewSourceReferenceKind) {
|
||||
self.source_reference_entry =
|
||||
Some(ReviewSourceReferenceEntry { kind, value: String::new(), error: None });
|
||||
}
|
||||
|
||||
pub(crate) fn push_source_reference_char(&mut self, character: char) {
|
||||
if let Some(entry) = &mut self.source_reference_entry {
|
||||
entry.value.push(character);
|
||||
entry.error = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn pop_source_reference_char(&mut self) {
|
||||
if let Some(entry) = &mut self.source_reference_entry {
|
||||
entry.value.pop();
|
||||
entry.error = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the source picker to target selection without replacing the pinned review.
|
||||
pub(crate) fn cancel_source_reference_entry(&mut self) {
|
||||
self.source_reference_entry = None;
|
||||
}
|
||||
|
||||
/// Validates a pending source reference and resolves it into an immutable review target.
|
||||
pub(crate) fn submit_source_reference(&mut self) -> Option<ReviewTarget> {
|
||||
let entry = self.source_reference_entry.as_mut()?;
|
||||
let reference = entry.value.trim();
|
||||
let target = match entry.kind {
|
||||
ReviewSourceReferenceKind::Base => {
|
||||
if reference.is_empty() {
|
||||
entry.error = Some("Type a base reference.");
|
||||
return None;
|
||||
}
|
||||
if reference.len() > 256 || reference.chars().any(char::is_control) {
|
||||
entry.error = Some("Base reference is not valid.");
|
||||
return None;
|
||||
}
|
||||
if reference.split_whitespace().count() != 1 {
|
||||
entry.error = Some("Base reference must be one token.");
|
||||
return None;
|
||||
}
|
||||
ReviewTarget::Base { reference: reference.to_owned() }
|
||||
}
|
||||
ReviewSourceReferenceKind::Commit => {
|
||||
if reference.is_empty() {
|
||||
entry.error = Some("Type a commit object ID.");
|
||||
return None;
|
||||
}
|
||||
if !(4..=64).contains(&reference.len())
|
||||
|| !reference.bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||
{
|
||||
entry.error = Some("Commit ID must be 4–64 hexadecimal characters.");
|
||||
return None;
|
||||
}
|
||||
ReviewTarget::Commit { oid: reference.to_owned() }
|
||||
}
|
||||
};
|
||||
entry.error = None;
|
||||
Some(target)
|
||||
}
|
||||
|
||||
/// Moves the source-picker selection one row with wraparound when it is open.
|
||||
pub(crate) fn move_source_picker_selection(
|
||||
&mut self,
|
||||
forward: bool,
|
||||
last_turn_available: bool,
|
||||
) {
|
||||
let ReviewSourcePickerState::Open { selection } = &mut self.source_picker else {
|
||||
return;
|
||||
};
|
||||
let options = ReviewSourcePickerSelection::picker_order();
|
||||
let index = options.iter().position(|candidate| candidate == selection).unwrap_or(0);
|
||||
for step in 1..=options.len() {
|
||||
let next = if forward {
|
||||
(index + step) % options.len()
|
||||
} else {
|
||||
(index + options.len() - step) % options.len()
|
||||
};
|
||||
let candidate = options[next];
|
||||
if candidate != ReviewSourcePickerSelection::LastTurn || last_turn_available {
|
||||
*selection = candidate;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
134
crates/luxe-tui/src/guided_review/state.rs
Normal file
134
crates/luxe-tui/src/guided_review/state.rs
Normal file
@@ -0,0 +1,134 @@
|
||||
//! Guided Review surface value types — enums, drafts, and the triage ordering.
|
||||
//!
|
||||
//! Pure presentation state referenced by the workspace, view, and diff layers; no behavior
|
||||
//! that touches the pinned review lives here.
|
||||
|
||||
mod finding_draft;
|
||||
mod opening;
|
||||
mod outcomes;
|
||||
mod post;
|
||||
|
||||
pub(crate) use finding_draft::FindingDraft;
|
||||
use luxe_core::event::GuidedReviewFailure;
|
||||
use luxe_core::guided_review::{
|
||||
ChapterId, FileId, FindingSeverity, FindingState, HunkId, ReviewFinding, ReviewTarget,
|
||||
};
|
||||
pub use opening::OpeningField;
|
||||
pub(crate) use opening::{
|
||||
AnswerRow, PreparedOpening, PullRequestFix, PullRequestOpening, StackOpening, ThreadAnswers,
|
||||
};
|
||||
pub(crate) use outcomes::{CommitPreview, FinishReviewChoice};
|
||||
pub(crate) use post::{GithubPost, PreparedPost, SendPreview};
|
||||
|
||||
/// Returns findings in the stable triage order used by the inspector.
|
||||
pub(crate) fn ordered_findings(findings: &[ReviewFinding]) -> Vec<&ReviewFinding> {
|
||||
let mut ordered = findings.iter().collect::<Vec<_>>();
|
||||
ordered.sort_by(|left, right| {
|
||||
finding_state_rank(left)
|
||||
.cmp(&finding_state_rank(right))
|
||||
.then_with(|| right.severity.cmp(&left.severity))
|
||||
.then_with(|| left.title.cmp(&right.title))
|
||||
.then_with(|| left.id.as_str().cmp(right.id.as_str()))
|
||||
});
|
||||
ordered
|
||||
}
|
||||
|
||||
fn finding_state_rank(finding: &ReviewFinding) -> u8 {
|
||||
match (finding.state, finding.severity) {
|
||||
(FindingState::Open, FindingSeverity::Blocking) => 0,
|
||||
(FindingState::Open, _) => 1,
|
||||
(FindingState::NeedsVerification, _) => 2,
|
||||
(FindingState::Draft, _) => 3,
|
||||
(FindingState::Resolved, _) => 4,
|
||||
(FindingState::Stale, _) => 5,
|
||||
}
|
||||
}
|
||||
|
||||
/// Runtime state for the full-screen Guided Review surface.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) enum GuidedReviewLoadState {
|
||||
/// The surface has not requested a review yet.
|
||||
Idle,
|
||||
/// A target is being captured while any pinned revision remains available.
|
||||
Loading { target: ReviewTarget },
|
||||
/// The current pinned review is ready to present.
|
||||
Ready,
|
||||
/// The requested target failed without discarding an existing pinned revision.
|
||||
Failed { target: ReviewTarget, error: GuidedReviewFailure },
|
||||
}
|
||||
|
||||
/// Selectable source kinds in the local review-source picker.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub(crate) enum ReviewSourcePickerSelection {
|
||||
/// Capture the current working tree.
|
||||
#[default]
|
||||
WorkingTree,
|
||||
/// Compare the most recently completed agent turn.
|
||||
LastTurn,
|
||||
/// Prompt for a merge-base reference.
|
||||
Base,
|
||||
/// Prompt for a commit object identifier.
|
||||
Commit,
|
||||
}
|
||||
|
||||
impl ReviewSourcePickerSelection {
|
||||
/// Returns source kinds in the picker presentation order.
|
||||
pub(crate) const fn picker_order() -> [Self; 4] {
|
||||
[Self::WorkingTree, Self::LastTurn, Self::Base, Self::Commit]
|
||||
}
|
||||
}
|
||||
|
||||
/// Reference kinds that need typed input before a review can load.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum ReviewSourceReferenceKind {
|
||||
/// A merge-base reference.
|
||||
Base,
|
||||
/// A commit object identifier.
|
||||
Commit,
|
||||
}
|
||||
|
||||
/// Local in-progress reference input for the review-source picker.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct ReviewSourceReferenceEntry {
|
||||
/// Reference kind that will receive the text.
|
||||
pub(crate) kind: ReviewSourceReferenceKind,
|
||||
/// Unvalidated user input.
|
||||
pub(crate) value: String,
|
||||
/// Validation message for the current input.
|
||||
pub(crate) error: Option<&'static str>,
|
||||
}
|
||||
|
||||
/// Local visibility and selection state for the review-source picker.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub(crate) enum ReviewSourcePickerState {
|
||||
/// The picker is not shown.
|
||||
#[default]
|
||||
Closed,
|
||||
/// The picker is open with one source kind selected.
|
||||
Open { selection: ReviewSourcePickerSelection },
|
||||
}
|
||||
|
||||
/// Stable semantic location inside a pinned review source.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub(crate) struct ReviewPosition {
|
||||
/// Selected semantic chapter, if the source provides one.
|
||||
pub(crate) chapter_id: Option<ChapterId>,
|
||||
/// Selected file lineage, if the review contains text hunks.
|
||||
pub(crate) file_id: Option<FileId>,
|
||||
/// Selected hunk within the selected file.
|
||||
pub(crate) hunk_id: Option<HunkId>,
|
||||
/// First visible unified-diff row within the selected file.
|
||||
pub(crate) line_offset: usize,
|
||||
}
|
||||
|
||||
impl ReviewPosition {
|
||||
/// A cheap value identifying where the cursor is, for comparing against a remembered one.
|
||||
pub(crate) fn fingerprint(&self) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
self.chapter_id.as_ref().map(|id| id.as_str()).hash(&mut hasher);
|
||||
self.file_id.as_ref().map(|id| id.as_str()).hash(&mut hasher);
|
||||
self.hunk_id.as_ref().map(|id| id.as_str()).hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
}
|
||||
145
crates/luxe-tui/src/guided_review/state/finding_draft.rs
Normal file
145
crates/luxe-tui/src/guided_review/state/finding_draft.rs
Normal file
@@ -0,0 +1,145 @@
|
||||
//! The finding draft — one anchor and the comment written against it, and what saving makes of it.
|
||||
|
||||
use luxe_core::guided_review::{
|
||||
FindingAnchor, FindingId, FindingSeverity, FindingState, ReviewFinding,
|
||||
ReviewSessionValidationError,
|
||||
};
|
||||
|
||||
/// Unsaved reviewer input associated with one immutable diff anchor.
|
||||
///
|
||||
/// One anchor and one piece of prose. The composer briefly asked for a title, a proposed fix and a
|
||||
/// severity around it; all three asked the reviewer to split a thought that arrives whole, and none
|
||||
/// told the agent anything the comment had not already said. Severity survives as a field because
|
||||
/// the verb sets it — `c` means the agent should act, `a` means it must answer and not edit — but
|
||||
/// nothing picks it once the box is open.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct FindingDraft {
|
||||
/// The source location captured when the draft opens.
|
||||
pub(crate) anchor: FindingAnchor,
|
||||
/// What this asks of the agent, fixed by the verb that opened the draft
|
||||
pub(crate) severity: FindingSeverity,
|
||||
/// A remediation an *earlier* draft carried, preserved untouched through a reopen.
|
||||
///
|
||||
/// Nothing writes this any more. It exists so reopening a draft persisted by a build that
|
||||
/// still had the field does not silently throw the reviewer's suggestion away on the next save.
|
||||
carried_fix: Option<String>,
|
||||
/// The real editor backing the comment.
|
||||
///
|
||||
/// This is the one place a reviewer writes prose, so it reuses Luxe's composer wholesale and
|
||||
/// behaves like every other text input: a cursor, arrow keys, word operations.
|
||||
editor: crate::editor::Editor,
|
||||
/// Why the last save was rejected, cleared by the next edit. Shown on screen, or `Ctrl+Enter`
|
||||
/// would look like a dead key.
|
||||
pub(crate) error: Option<String>,
|
||||
/// Send this straight to the agent on save instead of holding it as a draft.
|
||||
///
|
||||
/// A question left sitting in a draft answers nothing, so `a` dispatches immediately while `c`
|
||||
/// batches for a later send.
|
||||
pub(crate) dispatch_on_save: bool,
|
||||
/// Existing finding this draft replies to, when it is a thread reply rather than a new comment.
|
||||
pub(crate) reply_to: Option<FindingId>,
|
||||
}
|
||||
|
||||
impl FindingDraft {
|
||||
/// Builds an empty draft against one anchor.
|
||||
pub(crate) fn new(
|
||||
anchor: FindingAnchor,
|
||||
severity: FindingSeverity,
|
||||
dispatch_on_save: bool,
|
||||
reply_to: Option<FindingId>,
|
||||
) -> Self {
|
||||
Self {
|
||||
anchor,
|
||||
severity,
|
||||
carried_fix: None,
|
||||
editor: crate::editor::Editor::new(),
|
||||
error: None,
|
||||
dispatch_on_save,
|
||||
reply_to,
|
||||
}
|
||||
}
|
||||
|
||||
/// The reviewer's comment, read live off the editor.
|
||||
pub(crate) fn body(&self) -> &str {
|
||||
self.editor.current_input()
|
||||
}
|
||||
|
||||
/// Replaces the comment, loading it into the editor.
|
||||
pub(crate) fn set_body(&mut self, text: impl Into<String>) {
|
||||
let text = text.into();
|
||||
self.editor.cancel();
|
||||
self.editor.insert_text(&text);
|
||||
self.error = None;
|
||||
}
|
||||
|
||||
/// Keeps a remediation an earlier build authored, so a reopen does not drop it.
|
||||
pub(crate) fn carry_fix(&mut self, fix: Option<String>) {
|
||||
self.carried_fix = fix.filter(|fix| !fix.trim().is_empty());
|
||||
}
|
||||
|
||||
/// The live editor, so the overlay can draw a real cursor.
|
||||
pub(crate) fn editor(&self) -> &crate::editor::Editor {
|
||||
&self.editor
|
||||
}
|
||||
|
||||
/// The width the field is drawn at, so `↑/↓` moves by the rows the reader sees.
|
||||
pub(crate) fn set_width(&mut self, width: u16) {
|
||||
self.editor.set_viewport_width(width);
|
||||
}
|
||||
|
||||
/// Routes one key to the focused field's editor.
|
||||
///
|
||||
/// `Enter` inserts a newline instead of submitting: the composer's save is `Ctrl+Enter`, and a
|
||||
/// stray `Enter` must never fire the chat submit behind the review.
|
||||
pub(crate) fn handle_key(&mut self, key: crossterm::event::KeyEvent) {
|
||||
use crossterm::event::KeyCode;
|
||||
self.error = None;
|
||||
match key.code {
|
||||
KeyCode::Enter => self.editor.insert_newline(),
|
||||
_ => self.editor.handle_key(key),
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts pasted text into the focused field.
|
||||
///
|
||||
/// Without this, a paste while the composer was open reached the *chat* editor behind the
|
||||
/// review — from the reviewer's point of view the text simply vanished.
|
||||
pub(crate) fn paste(&mut self, text: &str) {
|
||||
self.error = None;
|
||||
self.editor.paste_text(text);
|
||||
}
|
||||
|
||||
/// The title the comment will carry: its own opening line.
|
||||
///
|
||||
/// There is no title field. Requiring one made the common case — a sentence of feedback — fail
|
||||
/// to save, and once it was optional it became a box that echoed what you were already typing
|
||||
/// into the box above it, one line behind. The durable record still has a title because the
|
||||
/// drawer, the send preview and the agent's message all need something short to name a comment
|
||||
/// by; deriving it costs the reviewer nothing.
|
||||
pub(crate) fn resolved_title(&self) -> String {
|
||||
luxe_core::guided_review::title_from_body(self.body())
|
||||
}
|
||||
|
||||
/// Builds a validated core finding without consuming the local draft.
|
||||
pub(crate) fn to_review_finding(
|
||||
&self,
|
||||
id: FindingId,
|
||||
) -> Result<ReviewFinding, ReviewSessionValidationError> {
|
||||
let finding = ReviewFinding {
|
||||
posted: None,
|
||||
github_thread: None,
|
||||
id,
|
||||
// The session assigns the next `R<n>` on insert; an edit keeps the one it already has.
|
||||
label: String::new(),
|
||||
anchor: self.anchor.clone(),
|
||||
severity: self.severity,
|
||||
title: self.resolved_title(),
|
||||
body: self.body().to_owned(),
|
||||
proposed_fix: self.carried_fix.clone(),
|
||||
state: FindingState::Draft,
|
||||
thread: Vec::new(),
|
||||
};
|
||||
finding.validate()?;
|
||||
Ok(finding)
|
||||
}
|
||||
}
|
||||
143
crates/luxe-tui/src/guided_review/state/opening.rs
Normal file
143
crates/luxe-tui/src/guided_review/state/opening.rs
Normal file
@@ -0,0 +1,143 @@
|
||||
//! Opening and answering — a pull request opened, a stack of them, a fix on another's, and answers
|
||||
//! to one's own threads.
|
||||
|
||||
use luxe_core::guided_review::FindingId;
|
||||
|
||||
/// A branch's review as a stack of pull requests, before it opens.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct StackOpening {
|
||||
/// The attempt in flight
|
||||
pub(crate) request_id: luxe_core::guided_review::PullRequestOpenId,
|
||||
/// The pull requests, bottom first, once drafted
|
||||
pub(crate) layers: Option<Vec<luxe_core::github::NewPullRequest>>,
|
||||
/// Whether they open as drafts
|
||||
pub(crate) draft: bool,
|
||||
/// Whether it is opening
|
||||
pub(crate) opening: bool,
|
||||
/// Why it cannot, or what stopped it
|
||||
pub(crate) error: Option<String>,
|
||||
}
|
||||
|
||||
/// Fixing someone else's pull request in a worktree, before the session is left to do it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct PullRequestFix {
|
||||
/// Number within its repository
|
||||
pub(crate) number: u64,
|
||||
/// The local branch it would be checked out on, once GitHub said it can be
|
||||
pub(crate) branch: Option<String>,
|
||||
/// Why it cannot be, once GitHub said so
|
||||
pub(crate) refusal: Option<String>,
|
||||
/// Unsent comments that go with it
|
||||
pub(crate) comments: usize,
|
||||
}
|
||||
|
||||
/// A branch's pull request, drafted from its review, before it opens.
|
||||
///
|
||||
/// Modal from open to settled, like the post preview: closing it while it opens would lose the
|
||||
/// answer that says where the pull request is.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct PullRequestOpening {
|
||||
/// The attempt in flight
|
||||
pub(crate) request_id: luxe_core::guided_review::PullRequestOpenId,
|
||||
/// The draft and what opening it involves, once the engine has read them
|
||||
pub(crate) prepared: Option<PreparedOpening>,
|
||||
/// The field being edited, when one is
|
||||
pub(crate) editing: Option<(OpeningField, crate::editor::Editor)>,
|
||||
/// Rows the description is scrolled down, clamped where it is drawn
|
||||
pub(crate) body_scroll: u16,
|
||||
/// Rows the description can scroll, as last drawn
|
||||
pub(crate) body_room: std::cell::Cell<u16>,
|
||||
/// Whether it has been sent and not yet answered
|
||||
pub(crate) opening: bool,
|
||||
/// The last failure, as a sentence
|
||||
pub(crate) error: Option<String>,
|
||||
}
|
||||
|
||||
/// What opening a pull request involves, as the preview shows it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct PreparedOpening {
|
||||
/// The pull request, with the reader's edits
|
||||
pub(crate) pull_request: luxe_core::github::NewPullRequest,
|
||||
/// Whether the branch is on GitHub yet
|
||||
pub(crate) publication: luxe_core::github::Publication,
|
||||
/// Paths with changes not committed
|
||||
pub(crate) uncommitted: usize,
|
||||
/// Subjects of the commits written first
|
||||
pub(crate) commits: Vec<String>,
|
||||
}
|
||||
|
||||
/// The part of a pull request the reader is editing.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum OpeningField {
|
||||
/// The one-line title
|
||||
Title,
|
||||
/// The description
|
||||
Body,
|
||||
}
|
||||
|
||||
/// Answers on their way to your own pull request's review threads.
|
||||
///
|
||||
/// Modal from open to settled, like the post preview, and for the same reason: closing it while
|
||||
/// answers are in flight would drop the results that mark them answered.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct ThreadAnswers {
|
||||
/// The attempt in flight
|
||||
pub(crate) request_id: luxe_core::guided_review::ThreadAnswersId,
|
||||
/// One per unanswered thread, in review order
|
||||
pub(crate) rows: Vec<AnswerRow>,
|
||||
/// Row under the cursor
|
||||
pub(crate) selected: usize,
|
||||
/// The reply being written for the selected row, when one is
|
||||
pub(crate) replying: Option<crate::editor::Editor>,
|
||||
/// Whether the fix is on GitHub, once asked: `(pushed, uncommitted)`
|
||||
pub(crate) prepared: Option<(bool, bool)>,
|
||||
/// Whether answers have been sent and not yet reported on
|
||||
pub(crate) sending: bool,
|
||||
/// A failure before any thread was touched
|
||||
pub(crate) error: Option<String>,
|
||||
}
|
||||
|
||||
/// One thread in the answers preview.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct AnswerRow {
|
||||
/// The finding the thread became
|
||||
pub(crate) finding_id: FindingId,
|
||||
/// Whether to resolve it
|
||||
pub(crate) resolve: bool,
|
||||
/// The reader's reply, empty for none
|
||||
pub(crate) reply: String,
|
||||
/// How the last attempt at this thread went, when it failed
|
||||
pub(crate) error: Option<String>,
|
||||
}
|
||||
|
||||
impl ThreadAnswers {
|
||||
/// Opens on every thread not yet resolved on GitHub, resolving by default the ones the reader
|
||||
/// verified and may resolve.
|
||||
pub(crate) fn new(
|
||||
request_id: luxe_core::guided_review::ThreadAnswersId,
|
||||
findings: &[luxe_core::guided_review::ReviewFinding],
|
||||
) -> Self {
|
||||
let rows = findings
|
||||
.iter()
|
||||
.filter_map(|finding| {
|
||||
let thread = finding.github_thread.as_ref().filter(|thread| !thread.resolved)?;
|
||||
Some(AnswerRow {
|
||||
finding_id: finding.id.clone(),
|
||||
resolve: thread.can_resolve
|
||||
&& finding.state == luxe_core::guided_review::FindingState::Resolved,
|
||||
reply: String::new(),
|
||||
error: None,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
request_id,
|
||||
rows,
|
||||
selected: 0,
|
||||
replying: None,
|
||||
prepared: None,
|
||||
sending: false,
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
68
crates/luxe-tui/src/guided_review/state/outcomes.rs
Normal file
68
crates/luxe-tui/src/guided_review/state/outcomes.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
//! Review outcomes — the finish chooser's choices and the commit preview.
|
||||
|
||||
/// A pending commit, showing the messages before any history is written.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct CommitPreview {
|
||||
/// Collapse every chapter into one commit.
|
||||
pub(crate) squash: bool,
|
||||
/// Whether the request is in flight.
|
||||
pub(crate) running: bool,
|
||||
}
|
||||
|
||||
/// Explicit user choice shown before closing or submitting a review.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum FinishReviewChoice {
|
||||
/// Record an accepted outcome without contacting the agent.
|
||||
Accept,
|
||||
/// Record acceptance and turn the reviewed chapters into commits.
|
||||
AcceptAndCommit,
|
||||
/// Send actionable findings to the active agent.
|
||||
RequestFixes,
|
||||
/// Send review comments without requesting edits.
|
||||
CommentOnly,
|
||||
/// Reply to and resolve your own pull request's threads on GitHub.
|
||||
AnswerOnGitHub,
|
||||
/// Commit the reviewed work, push the branch, and open its pull request.
|
||||
OpenPullRequest,
|
||||
/// Commit the reviewed work chapter by chapter and open it as a stack of pull requests.
|
||||
OpenStack,
|
||||
/// Close the local chooser without changing durable review state.
|
||||
Cancel,
|
||||
}
|
||||
|
||||
impl FinishReviewChoice {
|
||||
/// Moves through the finish-review choices in presentation order; `answers` offers answering
|
||||
/// on GitHub, which only your own pull request's review has, and `opens` offers opening the
|
||||
/// branch's pull request, which only a branch without one has.
|
||||
pub(in crate::guided_review) fn next(
|
||||
self,
|
||||
forward: bool,
|
||||
answers: bool,
|
||||
opens: bool,
|
||||
stacks: bool,
|
||||
) -> Self {
|
||||
const ORDER: [FinishReviewChoice; 8] = [
|
||||
FinishReviewChoice::Accept,
|
||||
FinishReviewChoice::AcceptAndCommit,
|
||||
FinishReviewChoice::RequestFixes,
|
||||
FinishReviewChoice::CommentOnly,
|
||||
FinishReviewChoice::AnswerOnGitHub,
|
||||
FinishReviewChoice::OpenPullRequest,
|
||||
FinishReviewChoice::OpenStack,
|
||||
FinishReviewChoice::Cancel,
|
||||
];
|
||||
let order: Vec<FinishReviewChoice> = ORDER
|
||||
.into_iter()
|
||||
.filter(|choice| answers || *choice != FinishReviewChoice::AnswerOnGitHub)
|
||||
.filter(|choice| opens || *choice != FinishReviewChoice::OpenPullRequest)
|
||||
.filter(|choice| stacks || *choice != FinishReviewChoice::OpenStack)
|
||||
.collect();
|
||||
let index = order.iter().position(|choice| *choice == self).unwrap_or(0);
|
||||
let next = if forward {
|
||||
(index + 1) % order.len()
|
||||
} else {
|
||||
index.checked_sub(1).unwrap_or(order.len() - 1)
|
||||
};
|
||||
order[next]
|
||||
}
|
||||
}
|
||||
91
crates/luxe-tui/src/guided_review/state/post.rs
Normal file
91
crates/luxe-tui/src/guided_review/state/post.rs
Normal file
@@ -0,0 +1,91 @@
|
||||
//! Sending and posting — the send preview, and a review's post to GitHub with its verdict.
|
||||
|
||||
use luxe_core::guided_review::FindingId;
|
||||
|
||||
/// Which comments a pending send will carry, and what it records when it lands.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct SendPreview {
|
||||
/// Comments excluded by the reviewer; everything else in the session ships.
|
||||
pub(crate) excluded: std::collections::HashSet<FindingId>,
|
||||
/// Row under the cursor.
|
||||
pub(crate) selected: usize,
|
||||
/// Outcome to record on send — `Some` only when the Finish dialog opened this.
|
||||
pub(crate) outcome: Option<luxe_core::guided_review::ReviewOutcome>,
|
||||
/// Mode pinned by the Finish dialog, else derived from what is included.
|
||||
pub(crate) mode: Option<luxe_core::guided_review::ReviewFeedbackMode>,
|
||||
}
|
||||
|
||||
/// A pull request's review on its way to GitHub.
|
||||
///
|
||||
/// Opens by asking GitHub what the preview needs, and stays modal until the post settles: closing
|
||||
/// it mid-post would drop the answer that marks the comments posted, and the next post would send
|
||||
/// them again.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct GithubPost {
|
||||
/// The attempt in flight, so a late answer to an earlier one is ignored
|
||||
pub(crate) request_id: luxe_core::guided_review::PullRequestPostId,
|
||||
/// Verdict chosen
|
||||
pub(crate) verdict: luxe_core::github::ReviewEvent,
|
||||
/// What GitHub said about the pull request, once it has
|
||||
pub(crate) prepared: Option<PreparedPost>,
|
||||
/// Whether the post has been sent and not yet answered
|
||||
pub(crate) posting: bool,
|
||||
/// The last failure, as a sentence
|
||||
pub(crate) error: Option<String>,
|
||||
/// The item under the cursor: the review itself, then each line comment in order
|
||||
pub(crate) selected: usize,
|
||||
/// Rows the selected item's text is scrolled by
|
||||
pub(crate) scroll: u16,
|
||||
/// The summary the agent is drafting, by its request id
|
||||
pub(crate) drafting: Option<String>,
|
||||
/// When that draft was asked for, so the wait can count
|
||||
pub(crate) drafting_since: Option<std::time::Instant>,
|
||||
/// What the agent said beside the summary it drafted, read with it
|
||||
pub(crate) draft_note: Option<String>,
|
||||
}
|
||||
|
||||
/// What a post's preview needs from GitHub.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct PreparedPost {
|
||||
/// GitHub's patches, which decide where each comment lands
|
||||
pub(crate) patches: Vec<luxe_core::github::FilePatch>,
|
||||
/// Whether the author pushed after the review was pinned
|
||||
pub(crate) head_moved: bool,
|
||||
/// Whether the reader opened the pull request, so only a comment is possible
|
||||
pub(crate) own_pull_request: bool,
|
||||
}
|
||||
|
||||
impl GithubPost {
|
||||
/// The verdicts GitHub will take from this reader, in the order the dialog lists them.
|
||||
pub(crate) fn verdicts(&self) -> &'static [luxe_core::github::ReviewEvent] {
|
||||
use luxe_core::github::ReviewEvent;
|
||||
if self.prepared.as_ref().is_some_and(|prepared| prepared.own_pull_request) {
|
||||
&[ReviewEvent::Comment]
|
||||
} else {
|
||||
&[ReviewEvent::Comment, ReviewEvent::Approve, ReviewEvent::RequestChanges]
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the cursor through `count` items, wrapping, and puts the new item's text at its top.
|
||||
pub(crate) fn move_selection(&mut self, forward: bool, count: usize) {
|
||||
if count == 0 {
|
||||
return;
|
||||
}
|
||||
let at = self.selected.min(count - 1);
|
||||
self.selected = if forward { (at + 1) % count } else { (at + count - 1) % count };
|
||||
self.scroll = 0;
|
||||
}
|
||||
|
||||
/// Scrolls the selected item's text; the render clamps it to what there is.
|
||||
pub(crate) fn scroll_by(&mut self, rows: i32) {
|
||||
self.scroll = u16::try_from((i32::from(self.scroll) + rows).max(0)).unwrap_or(u16::MAX);
|
||||
}
|
||||
|
||||
/// Steps the verdict through the ones on offer, wrapping.
|
||||
pub(crate) fn move_verdict(&mut self, forward: bool) {
|
||||
let verdicts = self.verdicts();
|
||||
let at = verdicts.iter().position(|verdict| *verdict == self.verdict).unwrap_or(0);
|
||||
let step = if forward { 1 } else { verdicts.len() - 1 };
|
||||
self.verdict = verdicts[(at + step) % verdicts.len()];
|
||||
}
|
||||
}
|
||||
103
crates/luxe-tui/src/guided_review/tests.rs
Normal file
103
crates/luxe-tui/src/guided_review/tests.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
mod findings;
|
||||
mod layout;
|
||||
mod navigation;
|
||||
mod refresh;
|
||||
mod search;
|
||||
mod sources;
|
||||
|
||||
use super::*;
|
||||
use luxe_core::guided_review::{
|
||||
LineRange, NoiseKind, ReviewFileStatus, ReviewHunk, ReviewLine, ReviewLineKind,
|
||||
};
|
||||
use std::path::Path;
|
||||
|
||||
/// A minimal pinned review over `files`, with deterministic chapters, for exercising navigation
|
||||
/// (which is chapter-scoped and therefore needs the whole review, not just its files).
|
||||
fn review_of(files: &[ReviewFile]) -> luxe_core::guided_review::GuidedReview {
|
||||
use luxe_core::guided_review::{
|
||||
CheckSummary, ReviewContext, ReviewId, ReviewRevisionId, ReviewStats, ReviewTarget,
|
||||
};
|
||||
let revision_id = ReviewRevisionId::from_canonical_bytes(b"navigation fixture");
|
||||
luxe_core::guided_review::GuidedReview {
|
||||
conversation: None,
|
||||
id: ReviewId::new(),
|
||||
revision_id: revision_id.clone(),
|
||||
target: ReviewTarget::WorkingTree,
|
||||
source: luxe_core::guided_review::ReviewSource {
|
||||
includes_unstaged: true,
|
||||
..crate::fixture::fixture_source(revision_id)
|
||||
},
|
||||
context: ReviewContext::bounded(
|
||||
"Navigation fixture",
|
||||
None::<&str>,
|
||||
None,
|
||||
None::<&str>,
|
||||
None::<&str>,
|
||||
None::<&str>,
|
||||
),
|
||||
chapters: luxe_core::guided_review::fallback_chapters(files).unwrap_or_default(),
|
||||
stats: ReviewStats::from_files(files),
|
||||
files: files.to_vec(),
|
||||
checks: CheckSummary::default(),
|
||||
generated_at_ms: 0,
|
||||
insight: None,
|
||||
provenance: None,
|
||||
seen: None,
|
||||
brief: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A file with both a removal and its replacement, which is what side-by-side needs to pair up.
|
||||
///
|
||||
/// [`text_file`] is `Added` and therefore one-sided, so it can never split however wide the pane
|
||||
/// is — the layout rule asks about the content, not only the room.
|
||||
fn changed_file(path: &str) -> ReviewFile {
|
||||
let mut file = text_file(path);
|
||||
file.status = ReviewFileStatus::Modified;
|
||||
file.hunks[0].lines = vec![
|
||||
ReviewLine {
|
||||
old_line: Some(1),
|
||||
new_line: None,
|
||||
kind: ReviewLineKind::Deletion,
|
||||
text: "let value = 1;".into(),
|
||||
},
|
||||
ReviewLine {
|
||||
old_line: None,
|
||||
new_line: Some(1),
|
||||
kind: ReviewLineKind::Addition,
|
||||
text: "let value = 2;".into(),
|
||||
},
|
||||
];
|
||||
file
|
||||
}
|
||||
|
||||
fn text_file(path: &str) -> ReviewFile {
|
||||
let id = FileId::from_path_lineage(None, Some(Path::new(path)));
|
||||
let hunk = ReviewHunk {
|
||||
id: HunkId::from_content(&id, "fixture", "let value = 1;"),
|
||||
old_range: LineRange::new(1, 1),
|
||||
new_range: LineRange::new(1, 1),
|
||||
heading: None,
|
||||
symbol: None,
|
||||
lines: vec![ReviewLine {
|
||||
old_line: Some(1),
|
||||
new_line: Some(1),
|
||||
kind: ReviewLineKind::Context,
|
||||
text: "let value = 1;".into(),
|
||||
}],
|
||||
noise: NoiseKind::Semantic,
|
||||
};
|
||||
ReviewFile {
|
||||
id,
|
||||
old_path: None,
|
||||
new_path: Some(path.into()),
|
||||
status: ReviewFileStatus::Added,
|
||||
language: Some("rust".into()),
|
||||
additions: Some(1),
|
||||
deletions: Some(0),
|
||||
hunks: vec![hunk],
|
||||
binary: false,
|
||||
generated: false,
|
||||
non_text: None,
|
||||
}
|
||||
}
|
||||
243
crates/luxe-tui/src/guided_review/tests/findings.rs
Normal file
243
crates/luxe-tui/src/guided_review/tests/findings.rs
Normal file
@@ -0,0 +1,243 @@
|
||||
//! Findings: the finish chooser, drafts, triage order, jumps and anchors.
|
||||
|
||||
use super::super::*;
|
||||
use super::text_file;
|
||||
use crate::fixture::{seeded_app, FixtureScenario};
|
||||
use luxe_core::guided_review::{ReviewLine, ReviewLineKind, ReviewSessionValidationError};
|
||||
|
||||
#[test]
|
||||
fn finish_review_chooser_cycles_and_cancels_without_mutating_review_state() {
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
|
||||
workspace.open_finish_review(false);
|
||||
assert_eq!(
|
||||
workspace.finish_review_choice,
|
||||
Some(FinishReviewChoice::Accept),
|
||||
"nothing to send, so nothing to ask fixes with"
|
||||
);
|
||||
workspace.open_finish_review(true);
|
||||
assert_eq!(workspace.finish_review_choice, Some(FinishReviewChoice::RequestFixes));
|
||||
workspace.move_finish_review_choice(true);
|
||||
assert_eq!(workspace.finish_review_choice, Some(FinishReviewChoice::CommentOnly));
|
||||
workspace.move_finish_review_choice(false);
|
||||
workspace.close_finish_review();
|
||||
assert_eq!(workspace.finish_review_choice, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finding_draft_captures_the_selection_and_never_overwrites_unsaved_input() {
|
||||
let file = text_file("src/draft.rs");
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
workspace.position.file_id = Some(file.id.clone());
|
||||
workspace.position.hunk_id = Some(file.hunks[0].id.clone());
|
||||
workspace.position.line_offset = 1;
|
||||
|
||||
assert!(workspace.begin_finding_draft(std::slice::from_ref(&file)));
|
||||
let draft = workspace.finding_draft.as_mut().unwrap();
|
||||
assert_eq!(draft.severity, FindingSeverity::Issue);
|
||||
assert!(matches!(draft.anchor, FindingAnchor::Line { side: DiffSide::New, .. }));
|
||||
draft.set_body("keep this");
|
||||
|
||||
workspace.position.line_offset = 0;
|
||||
assert!(!workspace.begin_finding_draft(&[file]));
|
||||
assert_eq!(workspace.finding_draft.as_ref().unwrap().body(), "keep this");
|
||||
|
||||
workspace.discard_finding_draft();
|
||||
assert!(workspace.finding_draft.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finding_draft_conversion_validates_without_consuming_unsaved_input() {
|
||||
let file = text_file("src/draft.rs");
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
workspace.position.file_id = Some(file.id.clone());
|
||||
workspace.position.hunk_id = Some(file.hunks[0].id.clone());
|
||||
workspace.position.line_offset = 1;
|
||||
assert!(workspace.begin_finding_draft(&[file]));
|
||||
|
||||
let draft = workspace.finding_draft.as_mut().expect("open draft");
|
||||
draft.set_body("This branch reorders externally visible messages.");
|
||||
let finding = draft.to_review_finding(FindingId::new()).expect("valid draft");
|
||||
|
||||
assert_eq!(finding.state, FindingState::Draft);
|
||||
assert!(finding.proposed_fix.is_none(), "the composer has no proposed-fix field to fill");
|
||||
assert_eq!(finding.body, draft.body());
|
||||
|
||||
// There is no title field: the durable record derives one from the comment's first line, so a
|
||||
// sentence of feedback saves and nothing echoes it back a line behind as you type.
|
||||
assert_eq!(finding.title, "This branch reorders externally visible messages.");
|
||||
|
||||
draft.set_body("");
|
||||
assert_eq!(
|
||||
draft.to_review_finding(FindingId::new()),
|
||||
Err(ReviewSessionValidationError::EmptyFindingTitle),
|
||||
"with nothing to derive from, the empty draft is rejected"
|
||||
);
|
||||
|
||||
// A long comment elides its derived title rather than carrying a paragraph as a summary.
|
||||
draft.set_body("x".repeat(200));
|
||||
let elided = draft.to_review_finding(FindingId::new()).expect("long body derives a title");
|
||||
assert_eq!(elided.title.chars().count(), 80);
|
||||
assert!(elided.title.ends_with('…'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draft_finding_editor_prefills_without_mutating_persisted_evidence() {
|
||||
let finding = ReviewFinding {
|
||||
posted: None,
|
||||
github_thread: None,
|
||||
id: FindingId::new(),
|
||||
label: String::new(),
|
||||
anchor: FindingAnchor::Review,
|
||||
severity: FindingSeverity::Suggestion,
|
||||
title: "Keep retry bounds".into(),
|
||||
body: "The retry path needs a bounded error.".into(),
|
||||
proposed_fix: Some("Return the typed timeout error.".into()),
|
||||
state: FindingState::Draft,
|
||||
thread: Vec::new(),
|
||||
};
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
|
||||
assert!(workspace.begin_edit_finding_draft(&finding));
|
||||
let draft = workspace.finding_draft.expect("editor draft");
|
||||
assert_eq!(workspace.editing_finding_id, Some(finding.id.clone()));
|
||||
assert_eq!(draft.anchor, finding.anchor);
|
||||
assert_eq!(draft.body(), finding.body);
|
||||
// Nothing can author a remediation any more, but a draft written by a build that could must
|
||||
// not lose it just because the reviewer reopened it to fix a typo.
|
||||
assert_eq!(
|
||||
draft.to_review_finding(finding.id.clone()).expect("valid draft").proposed_fix,
|
||||
finding.proposed_fix
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finding_selection_uses_stable_actionable_triage_order() {
|
||||
let finding = |title: &str, state: FindingState, severity: FindingSeverity| ReviewFinding {
|
||||
posted: None,
|
||||
github_thread: None,
|
||||
id: FindingId::new(),
|
||||
label: String::new(),
|
||||
anchor: FindingAnchor::Review,
|
||||
severity,
|
||||
title: title.into(),
|
||||
body: "Fixture feedback.".into(),
|
||||
proposed_fix: None,
|
||||
state,
|
||||
thread: Vec::new(),
|
||||
};
|
||||
let findings = vec![
|
||||
finding("stale", FindingState::Stale, FindingSeverity::Note),
|
||||
finding("draft", FindingState::Draft, FindingSeverity::Suggestion),
|
||||
finding("open", FindingState::Open, FindingSeverity::Issue),
|
||||
finding("blocking", FindingState::Open, FindingSeverity::Blocking),
|
||||
];
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
|
||||
assert!(workspace.move_finding_selection(&findings, true));
|
||||
assert_eq!(workspace.selected_finding_id, Some(findings[3].id.clone()));
|
||||
assert!(workspace.move_finding_selection(&findings, true));
|
||||
assert_eq!(workspace.selected_finding_id, Some(findings[2].id.clone()));
|
||||
assert!(workspace.move_finding_selection(&findings, false));
|
||||
assert_eq!(workspace.selected_finding_id, Some(findings[3].id.clone()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finding_jump_restores_an_exact_line_anchor() {
|
||||
let app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
|
||||
let review = app.guided_review.expect("fixture review");
|
||||
let file = &review.files[0];
|
||||
let hunk = &file.hunks[0];
|
||||
let finding = ReviewFinding {
|
||||
posted: None,
|
||||
github_thread: None,
|
||||
id: FindingId::new(),
|
||||
label: String::new(),
|
||||
anchor: FindingAnchor::Line {
|
||||
file_id: file.id.clone(),
|
||||
hunk_id: hunk.id.clone(),
|
||||
side: DiffSide::New,
|
||||
line: hunk.lines[0].new_line.expect("fixture new line"),
|
||||
context_hash: hunk.lines[0].context_hash(),
|
||||
},
|
||||
severity: FindingSeverity::Issue,
|
||||
title: "Jump target".into(),
|
||||
body: "Jump to this immutable line.".into(),
|
||||
proposed_fix: None,
|
||||
state: FindingState::Open,
|
||||
thread: Vec::new(),
|
||||
};
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
|
||||
assert!(workspace.jump_to_finding(&finding, &review));
|
||||
assert_eq!(workspace.position.file_id, Some(file.id.clone()));
|
||||
assert_eq!(workspace.position.hunk_id, Some(hunk.id.clone()));
|
||||
assert_eq!(workspace.position.line_offset, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_diff_row_maps_to_side_specific_line_anchor() {
|
||||
let mut file = text_file("src/anchor.rs");
|
||||
file.hunks[0].lines = vec![
|
||||
ReviewLine {
|
||||
old_line: Some(7),
|
||||
new_line: None,
|
||||
kind: ReviewLineKind::Deletion,
|
||||
text: "old value".into(),
|
||||
},
|
||||
ReviewLine {
|
||||
old_line: None,
|
||||
new_line: Some(7),
|
||||
kind: ReviewLineKind::Addition,
|
||||
text: "new value".into(),
|
||||
},
|
||||
ReviewLine {
|
||||
old_line: None,
|
||||
new_line: None,
|
||||
kind: ReviewLineKind::NoNewlineMarker,
|
||||
text: "\\ No newline at end of file".into(),
|
||||
},
|
||||
];
|
||||
let hunk_id = file.hunks[0].id.clone();
|
||||
let expected_old_hash = file.hunks[0].lines[0].context_hash();
|
||||
let expected_new_hash = file.hunks[0].lines[1].context_hash();
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
workspace.position.file_id = Some(file.id.clone());
|
||||
workspace.position.hunk_id = Some(hunk_id.clone());
|
||||
|
||||
workspace.position.line_offset = 1;
|
||||
assert_eq!(
|
||||
workspace.selected_finding_anchor(&[file.clone()]),
|
||||
FindingAnchor::Line {
|
||||
file_id: file.id.clone(),
|
||||
hunk_id: hunk_id.clone(),
|
||||
side: DiffSide::Old,
|
||||
line: 7,
|
||||
context_hash: expected_old_hash,
|
||||
}
|
||||
);
|
||||
|
||||
workspace.position.line_offset = 2;
|
||||
assert_eq!(
|
||||
workspace.selected_finding_anchor(&[file.clone()]),
|
||||
FindingAnchor::Line {
|
||||
file_id: file.id.clone(),
|
||||
hunk_id: hunk_id.clone(),
|
||||
side: DiffSide::New,
|
||||
line: 7,
|
||||
context_hash: expected_new_hash,
|
||||
}
|
||||
);
|
||||
|
||||
workspace.position.line_offset = 3;
|
||||
assert_eq!(
|
||||
workspace.selected_finding_anchor(&[file.clone()]),
|
||||
FindingAnchor::Hunk { file_id: file.id.clone(), hunk_id: hunk_id.clone() }
|
||||
);
|
||||
|
||||
workspace.position.line_offset = 0;
|
||||
assert_eq!(
|
||||
workspace.selected_finding_anchor(&[file]),
|
||||
FindingAnchor::Hunk { file_id: workspace.position.file_id.clone().unwrap(), hunk_id }
|
||||
);
|
||||
}
|
||||
198
crates/luxe-tui/src/guided_review/tests/layout.rs
Normal file
198
crates/luxe-tui/src/guided_review/tests/layout.rs
Normal file
@@ -0,0 +1,198 @@
|
||||
//! Layout: split preference and fallback, columns, and horizontal scrolling.
|
||||
|
||||
use super::super::*;
|
||||
use super::{changed_file, text_file};
|
||||
|
||||
/// Asking for two columns on a pane that cannot seat them is still asking. The preference has to
|
||||
/// survive the fallback, or widening the terminal would silently leave the diff unified.
|
||||
#[test]
|
||||
fn split_preference_survives_a_narrow_width_fallback() {
|
||||
let file = changed_file("src/split.rs");
|
||||
let files = std::slice::from_ref(&file);
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(file.id.clone()),
|
||||
hunk_id: None,
|
||||
line_offset: 0,
|
||||
},
|
||||
diff_viewport_columns: 40,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
workspace.toggle_split_preference(files);
|
||||
assert_eq!(workspace.layout, DiffLayout::Split);
|
||||
assert!(!workspace.split_layout_showing(files), "40 cells are not two columns on any setting");
|
||||
|
||||
workspace.diff_viewport_columns = 200;
|
||||
assert!(workspace.split_layout_showing(files), "and the preference was still standing");
|
||||
assert_eq!(workspace.layout, DiffLayout::Split);
|
||||
}
|
||||
|
||||
/// The toggle records the opposite of what is *showing*, so it always changes the screen. Pressing
|
||||
/// it on a pane `auto` had declined now pairs the sides rather than doing nothing: `split` asks
|
||||
/// for less width than `auto` does, which is the whole reason the two are different settings.
|
||||
#[test]
|
||||
fn the_toggle_pairs_the_sides_on_a_pane_auto_turned_down() {
|
||||
let file = changed_file("src/cramped.rs");
|
||||
let files = std::slice::from_ref(&file);
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(file.id.clone()),
|
||||
hunk_id: None,
|
||||
line_offset: 0,
|
||||
},
|
||||
diff_viewport_columns: 80,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!workspace.split_layout_showing(files), "auto leaves a cramped pane unified");
|
||||
|
||||
workspace.toggle_split_preference(files);
|
||||
assert!(workspace.split_layout_showing(files), "and the key the footer offers does something");
|
||||
|
||||
workspace.toggle_split_preference(files);
|
||||
assert_eq!(workspace.layout, DiffLayout::Unified, "pressing it again puts it back");
|
||||
assert!(!workspace.split_layout_showing(files));
|
||||
}
|
||||
|
||||
/// `auto` is the width rule; `split` is someone overruling it; `unified` is neither. One setting,
|
||||
/// the same three meanings the tool cards and the peek pane read.
|
||||
#[test]
|
||||
fn the_configured_layout_decides_what_the_pane_can_do_with_its_width() {
|
||||
let file = changed_file("src/layouts.rs");
|
||||
let files = std::slice::from_ref(&file);
|
||||
let workspace = |layout, columns| GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(file.id.clone()),
|
||||
hunk_id: None,
|
||||
line_offset: 0,
|
||||
},
|
||||
layout,
|
||||
diff_viewport_columns: columns,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(workspace(DiffLayout::Auto, 200).split_layout_showing(files));
|
||||
assert!(!workspace(DiffLayout::Auto, 80).split_layout_showing(files), "auto wants a column");
|
||||
assert!(
|
||||
workspace(DiffLayout::Split, 80).split_layout_showing(files),
|
||||
"split takes a cramped one"
|
||||
);
|
||||
assert!(
|
||||
!workspace(DiffLayout::Split, 40).split_layout_showing(files),
|
||||
"but not a hopeless one"
|
||||
);
|
||||
assert!(!workspace(DiffLayout::Unified, 200).split_layout_showing(files));
|
||||
}
|
||||
|
||||
/// A one-sided file has nothing for the second column, on any width, under any setting.
|
||||
#[test]
|
||||
fn a_one_sided_file_is_never_drawn_side_by_side() {
|
||||
let added = text_file("src/new.rs");
|
||||
let workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(added.id.clone()),
|
||||
hunk_id: None,
|
||||
line_offset: 0,
|
||||
},
|
||||
layout: DiffLayout::Split,
|
||||
diff_viewport_columns: 400,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(!workspace.split_layout_active_for(&added));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_split_fallback_and_restoration_preserve_the_selected_hunk_anchor() {
|
||||
let file = changed_file("src/resize.rs");
|
||||
let position = ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(file.id.clone()),
|
||||
hunk_id: Some(file.hunks[0].id.clone()),
|
||||
line_offset: 1,
|
||||
};
|
||||
let files = std::slice::from_ref(&file);
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: position.clone(),
|
||||
layout: DiffLayout::Auto,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
workspace.set_terminal_size(200, 30);
|
||||
assert!(workspace.split_layout_showing(files));
|
||||
workspace.set_terminal_size(100, 30);
|
||||
|
||||
assert!(!workspace.split_layout_showing(files));
|
||||
assert_eq!(workspace.layout, DiffLayout::Auto);
|
||||
assert_eq!(workspace.position, position);
|
||||
|
||||
workspace.set_terminal_size(200, 30);
|
||||
assert!(workspace.split_layout_showing(files));
|
||||
assert_eq!(workspace.position, position);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn home_resets_the_diff_column_offset() {
|
||||
let mut workspace = GuidedReviewWorkspace { diff_column_offset: 24, ..Default::default() };
|
||||
|
||||
workspace.reset_column_offset();
|
||||
assert_eq!(workspace.diff_column_offset, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn column_navigation_is_bounded_by_terminal_cell_width() {
|
||||
let mut file = text_file("src/columns.rs");
|
||||
file.hunks[0].lines[0].text = "wide-界-source".into();
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(file.id.clone()),
|
||||
hunk_id: Some(file.hunks[0].id.clone()),
|
||||
line_offset: 0,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
// 18 diff cells, less a unified row's chrome around its one-digit numbers, leaves 11 for a
|
||||
// source 14 cells wide: the wide glyph counts twice
|
||||
workspace.set_terminal_size(20, 8);
|
||||
|
||||
workspace.next_column(std::slice::from_ref(&file));
|
||||
assert_eq!(workspace.diff_column_offset, 3);
|
||||
workspace.previous_column();
|
||||
assert_eq!(workspace.diff_column_offset, 0);
|
||||
|
||||
file.hunks[0].lines[0].text = "x".repeat(120);
|
||||
workspace.diff_viewport_columns = 100;
|
||||
workspace.next_column(std::slice::from_ref(&file));
|
||||
assert_eq!(workspace.diff_column_offset, COLUMN_SCROLL_STEP);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn horizontal_offset_clamps_to_the_active_split_or_unified_presentation() {
|
||||
let mut file = changed_file("src/split-columns.rs");
|
||||
file.hunks[0].lines[0].text = "x".repeat(90);
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(file.id.clone()),
|
||||
hunk_id: Some(file.hunks[0].id.clone()),
|
||||
line_offset: 0,
|
||||
},
|
||||
layout: DiffLayout::Split,
|
||||
diff_viewport_columns: 100,
|
||||
diff_column_offset: 90,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Each column gets (100 - 5) / 2 = 47 cells, three of them gutter: 44 of source for 90
|
||||
workspace.clamp_column_offset(std::slice::from_ref(&file));
|
||||
assert_eq!(workspace.diff_column_offset, 46);
|
||||
|
||||
workspace.layout = DiffLayout::Unified;
|
||||
workspace.clamp_column_offset(std::slice::from_ref(&file));
|
||||
assert_eq!(workspace.diff_column_offset, 0);
|
||||
}
|
||||
588
crates/luxe-tui/src/guided_review/tests/navigation.rs
Normal file
588
crates/luxe-tui/src/guided_review/tests/navigation.rs
Normal file
@@ -0,0 +1,588 @@
|
||||
//! Navigation: lines, pages, hunks, files and chapters, folds, and the walkthrough's order.
|
||||
|
||||
use super::super::*;
|
||||
use super::{review_of, text_file};
|
||||
use crate::fixture::{seeded_app, FixtureScenario};
|
||||
use luxe_core::guided_review::{
|
||||
LineRange, NoiseKind, NonTextChange, NonTextChangeKind, ReviewHunk, ReviewLine, ReviewLineKind,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn line_navigation_stays_within_selected_file_rows() {
|
||||
let file = text_file("src/lines.rs");
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(file.id.clone()),
|
||||
hunk_id: Some(file.hunks[0].id.clone()),
|
||||
line_offset: 0,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
workspace.next_line(&review_of(std::slice::from_ref(&file)));
|
||||
workspace.next_line(&review_of(std::slice::from_ref(&file)));
|
||||
assert_eq!(workspace.position.line_offset, 1);
|
||||
|
||||
workspace.previous_line(&review_of(std::slice::from_ref(&file)));
|
||||
workspace.previous_line(&review_of(std::slice::from_ref(&file)));
|
||||
assert_eq!(workspace.position.line_offset, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chapter_navigation_moves_the_position_to_the_next_section() {
|
||||
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
|
||||
let mut review = app.guided_review.take().expect("fixture review");
|
||||
let mut supporting = review.chapters[0].clone();
|
||||
supporting.id = ChapterId::from_item_keys("supporting", &["fixture-supporting"]);
|
||||
supporting.title = "Supporting changes".into();
|
||||
review.chapters.push(supporting.clone());
|
||||
let mut workspace = app.guided_review_workspace;
|
||||
|
||||
workspace.next_chapter(&review);
|
||||
|
||||
assert_eq!(workspace.position.chapter_id, Some(supporting.id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chapter_navigation_selects_a_referenced_non_text_file() {
|
||||
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
|
||||
let mut review = app.guided_review.take().expect("fixture review");
|
||||
let mut non_text = text_file("assets/chapter.bin");
|
||||
non_text.hunks.clear();
|
||||
non_text.binary = true;
|
||||
non_text.non_text = Some(NonTextChange {
|
||||
kind: NonTextChangeKind::Binary,
|
||||
summary: "Binary files differ".into(),
|
||||
});
|
||||
let mut chapter = review.chapters[0].clone();
|
||||
chapter.id = ChapterId::from_item_keys("binary", &[non_text.id.as_str()]);
|
||||
chapter.items = vec![ReviewItemRef::File(non_text.id.clone())];
|
||||
let first_chapter_id = review.chapters[0].id.clone();
|
||||
review.files.push(non_text.clone());
|
||||
review.chapters.push(chapter);
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: Some(first_chapter_id),
|
||||
file_id: Some(review.files[0].id.clone()),
|
||||
hunk_id: Some(review.files[0].hunks[0].id.clone()),
|
||||
line_offset: 0,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
workspace.next_chapter(&review);
|
||||
|
||||
assert_eq!(workspace.position.file_id, Some(non_text.id));
|
||||
assert_eq!(workspace.position.hunk_id, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_navigation_selects_text_files_and_sensible_hunk_anchors() {
|
||||
let first = text_file("src/first.rs");
|
||||
let mut second = text_file("src/second.rs");
|
||||
let mut second_hunk = second.hunks[0].clone();
|
||||
second_hunk.id = HunkId::from_content(&second.id, "second", "let next = 2;");
|
||||
second.hunks.push(second_hunk.clone());
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(first.id.clone()),
|
||||
hunk_id: Some(first.hunks[0].id.clone()),
|
||||
line_offset: 0,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let files = vec![first.clone(), second.clone()];
|
||||
|
||||
workspace.next_chapter_file(&review_of(&files));
|
||||
assert_eq!(workspace.position.file_id, Some(second.id.clone()));
|
||||
assert_eq!(workspace.position.hunk_id, Some(second.hunks[0].id.clone()));
|
||||
assert_eq!(workspace.position.line_offset, 0);
|
||||
workspace.previous_chapter_file(&review_of(&files));
|
||||
assert_eq!(workspace.position.file_id, Some(first.id));
|
||||
assert_eq!(workspace.position.hunk_id, Some(first.hunks[0].id.clone()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_navigation_selects_non_text_files_without_a_hunk_anchor() {
|
||||
let first = text_file("src/first.rs");
|
||||
let mut non_text = text_file("assets/icon.bin");
|
||||
non_text.hunks.clear();
|
||||
non_text.binary = true;
|
||||
non_text.non_text = Some(NonTextChange {
|
||||
kind: NonTextChangeKind::Binary,
|
||||
summary: "Binary files differ".into(),
|
||||
});
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(first.id.clone()),
|
||||
hunk_id: Some(first.hunks[0].id.clone()),
|
||||
line_offset: 0,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let files = vec![first.clone(), non_text.clone()];
|
||||
|
||||
workspace.next_chapter_file(&review_of(&files));
|
||||
assert_eq!(workspace.position.file_id, Some(non_text.id));
|
||||
assert_eq!(workspace.position.hunk_id, None);
|
||||
workspace.previous_chapter_file(&review_of(&files));
|
||||
assert_eq!(workspace.position.file_id, Some(first.id));
|
||||
assert_eq!(workspace.position.hunk_id, Some(first.hunks[0].id.clone()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chapter_file_navigation_selects_a_referenced_non_text_file() {
|
||||
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
|
||||
let mut review = app.guided_review.take().expect("fixture review");
|
||||
let first = review.files[0].clone();
|
||||
let mut non_text = text_file("assets/chapter-file.bin");
|
||||
non_text.hunks.clear();
|
||||
non_text.binary = true;
|
||||
non_text.non_text = Some(NonTextChange {
|
||||
kind: NonTextChangeKind::Binary,
|
||||
summary: "Binary files differ".into(),
|
||||
});
|
||||
review.chapters[0].items.push(ReviewItemRef::File(non_text.id.clone()));
|
||||
review.files.push(non_text.clone());
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: Some(review.chapters[0].id.clone()),
|
||||
file_id: Some(first.id.clone()),
|
||||
hunk_id: Some(first.hunks[0].id.clone()),
|
||||
line_offset: 0,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
workspace.next_chapter_file(&review);
|
||||
|
||||
assert_eq!(workspace.position.file_id, Some(non_text.id));
|
||||
assert_eq!(workspace.position.hunk_id, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guide_file_navigation_stays_within_active_chapter() {
|
||||
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
|
||||
let mut review = app.guided_review.take().expect("fixture review");
|
||||
let first = review.files[0].clone();
|
||||
let second = text_file("src/chapter_second.rs");
|
||||
let unrelated = text_file("src/unrelated.rs");
|
||||
review.chapters[0].items.push(ReviewItemRef::Hunk(second.hunks[0].id.clone()));
|
||||
review.files.extend([second.clone(), unrelated]);
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: Some(review.chapters[0].id.clone()),
|
||||
file_id: Some(first.id.clone()),
|
||||
hunk_id: Some(first.hunks[0].id.clone()),
|
||||
line_offset: 0,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
workspace.next_chapter_file(&review);
|
||||
assert_eq!(workspace.position.file_id, Some(second.id.clone()));
|
||||
workspace.next_chapter_file(&review);
|
||||
assert_eq!(workspace.position.file_id, Some(second.id));
|
||||
workspace.previous_chapter_file(&review);
|
||||
assert_eq!(workspace.position.file_id, Some(first.id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_fold_preserves_a_selected_non_text_item() {
|
||||
let mut text = text_file("src/format.rs");
|
||||
text.hunks[0].noise = NoiseKind::FormattingOnly;
|
||||
let mut non_text = text_file("assets/icon.bin");
|
||||
non_text.hunks.clear();
|
||||
non_text.binary = true;
|
||||
non_text.non_text = Some(NonTextChange {
|
||||
kind: NonTextChangeKind::Binary,
|
||||
summary: "Binary files differ".into(),
|
||||
});
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(non_text.id.clone()),
|
||||
hunk_id: None,
|
||||
line_offset: 0,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let files = vec![text, non_text.clone()];
|
||||
|
||||
workspace.toggle_noise(&files);
|
||||
workspace.toggle_noise(&files);
|
||||
|
||||
assert_eq!(workspace.position.file_id, Some(non_text.id));
|
||||
assert_eq!(workspace.position.hunk_id, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hunk_navigation_continues_across_reviewable_file_boundaries() {
|
||||
let first = text_file("src/first.rs");
|
||||
let second = text_file("src/second.rs");
|
||||
let files = vec![first.clone(), second.clone()];
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(first.id.clone()),
|
||||
hunk_id: Some(first.hunks[0].id.clone()),
|
||||
line_offset: 0,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
workspace.next_hunk(&review_of(&files));
|
||||
assert_eq!(workspace.position.file_id, Some(second.id.clone()));
|
||||
assert_eq!(workspace.position.hunk_id, Some(second.hunks[0].id.clone()));
|
||||
workspace.previous_hunk(&review_of(&files));
|
||||
assert_eq!(workspace.position.file_id, Some(first.id));
|
||||
assert_eq!(workspace.position.hunk_id, Some(first.hunks[0].id.clone()));
|
||||
}
|
||||
|
||||
/// Scrolling used to roll into the neighboring file at either end. The pane draws one file at a
|
||||
/// time, so a single row too many put the reviewer in a different diff with nothing on screen
|
||||
/// saying so; moving between files belongs to the keys that also carry the narration.
|
||||
#[test]
|
||||
fn scrolling_stops_at_the_files_edges_instead_of_changing_file() {
|
||||
let first = text_file("src/first.rs");
|
||||
let second = text_file("src/second.rs");
|
||||
let files = vec![first.clone(), second.clone()];
|
||||
let review = review_of(&files);
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(second.id.clone()),
|
||||
hunk_id: Some(second.hunks[0].id.clone()),
|
||||
line_offset: 0,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
for _ in 0..20 {
|
||||
workspace.next_line(&review);
|
||||
}
|
||||
assert_eq!(workspace.position.file_id, Some(second.id.clone()), "forward stays put");
|
||||
|
||||
for _ in 0..20 {
|
||||
workspace.previous_line(&review);
|
||||
}
|
||||
assert_eq!(workspace.position.file_id, Some(second.id.clone()), "and so does backward");
|
||||
assert_eq!(workspace.position.line_offset, 0, "clamped, not wrapped");
|
||||
|
||||
// Paging obeys the same edge, so the two vertical keys cannot disagree about what a boundary
|
||||
// means.
|
||||
workspace.previous_page(&review);
|
||||
assert_eq!(workspace.position.file_id, Some(second.id), "paging stops there too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hunk_navigation_selects_stable_ids_and_header_offsets() {
|
||||
let mut file = text_file("src/hunks.rs");
|
||||
let mut second = file.hunks[0].clone();
|
||||
second.id = HunkId::from_content(&file.id, "second", "let next = 2;");
|
||||
second.lines[0].old_line = Some(2);
|
||||
second.lines[0].new_line = Some(2);
|
||||
file.hunks.push(second.clone());
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(file.id.clone()),
|
||||
hunk_id: Some(file.hunks[0].id.clone()),
|
||||
line_offset: 1,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
workspace.next_hunk(&review_of(std::slice::from_ref(&file)));
|
||||
assert_eq!(workspace.position.hunk_id, Some(second.id.clone()));
|
||||
assert_eq!(workspace.position.line_offset, 2);
|
||||
workspace.previous_hunk(&review_of(std::slice::from_ref(&file)));
|
||||
assert_eq!(workspace.position.hunk_id, Some(file.hunks[0].id.clone()));
|
||||
assert_eq!(workspace.position.line_offset, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_navigation_uses_the_rendered_diff_viewport() {
|
||||
let mut file = text_file("src/page.rs");
|
||||
file.hunks[0].lines.extend((2..=10).map(|number| ReviewLine {
|
||||
old_line: Some(number),
|
||||
new_line: Some(number),
|
||||
kind: ReviewLineKind::Context,
|
||||
text: format!("let value_{number} = {number};"),
|
||||
}));
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(file.id.clone()),
|
||||
hunk_id: Some(file.hunks[0].id.clone()),
|
||||
line_offset: 0,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
workspace.set_terminal_size(80, 7);
|
||||
|
||||
workspace.next_page(&review_of(std::slice::from_ref(&file)));
|
||||
assert_eq!(workspace.position.line_offset, 4);
|
||||
workspace.previous_page(&review_of(std::slice::from_ref(&file)));
|
||||
assert_eq!(workspace.position.line_offset, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_fold_reports_exact_hunk_and_line_counts_until_expanded() {
|
||||
let mut file = text_file("src/noise.rs");
|
||||
let mut noise = file.hunks[0].clone();
|
||||
noise.id = HunkId::from_content(&file.id, "format", "let value=1;");
|
||||
noise.lines.push(ReviewLine {
|
||||
old_line: Some(2),
|
||||
new_line: Some(2),
|
||||
kind: ReviewLineKind::Context,
|
||||
text: "let unchanged = true;".into(),
|
||||
});
|
||||
noise.noise = NoiseKind::FormattingOnly;
|
||||
file.hunks.push(noise.clone());
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(file.id.clone()),
|
||||
hunk_id: Some(noise.id.clone()),
|
||||
line_offset: 2,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(workspace.is_hunk_hidden(&file, &noise));
|
||||
assert!(!workspace.noise_details_visible);
|
||||
workspace.toggle_noise_details();
|
||||
assert!(workspace.noise_details_visible);
|
||||
assert_eq!(workspace.hidden_counts(&[file.clone()]), (1, 2));
|
||||
workspace.toggle_noise(&[file.clone()]);
|
||||
assert!(!workspace.is_hunk_hidden(&file, &noise));
|
||||
assert_eq!(workspace.hidden_counts(&[file.clone()]), (0, 0));
|
||||
workspace.toggle_noise(&[file.clone()]);
|
||||
assert_eq!(workspace.position.hunk_id, Some(file.hunks[0].id.clone()));
|
||||
assert_eq!(workspace.position.line_offset, 0);
|
||||
// Two source rows for the open hunk, then the collapsed run's own row — scrolling reaches it
|
||||
// rather than stopping short of content the renderer draws.
|
||||
workspace.next_line(&review_of(std::slice::from_ref(&file)));
|
||||
workspace.next_line(&review_of(std::slice::from_ref(&file)));
|
||||
assert_eq!(workspace.position.line_offset, 2);
|
||||
assert!(workspace.position.hunk_id.is_none(), "the cursor sits on the collapsed run");
|
||||
}
|
||||
|
||||
/// Regression: the diff renderer lays out only *visible* hunks, so a selection offset counted over
|
||||
/// every hunk dropped the cursor rows deep inside the target whenever a folded hunk preceded it.
|
||||
#[test]
|
||||
fn hunk_selection_lands_on_the_header_with_folded_noise_ahead_of_it() {
|
||||
let mut file = text_file("src/folded.rs");
|
||||
let formatting = ReviewHunk {
|
||||
id: HunkId::from_content(&file.id, "formatting", "use std::fmt;"),
|
||||
old_range: LineRange::new(1, 1),
|
||||
new_range: LineRange::new(1, 1),
|
||||
heading: Some("imports".into()),
|
||||
symbol: None,
|
||||
lines: vec![
|
||||
ReviewLine {
|
||||
old_line: Some(1),
|
||||
new_line: None,
|
||||
kind: ReviewLineKind::Deletion,
|
||||
text: "use std::{fmt,io};".into(),
|
||||
},
|
||||
ReviewLine {
|
||||
old_line: None,
|
||||
new_line: Some(1),
|
||||
kind: ReviewLineKind::Addition,
|
||||
text: "use std::{fmt, io};".into(),
|
||||
},
|
||||
],
|
||||
noise: NoiseKind::FormattingOnly,
|
||||
};
|
||||
let semantic = file.hunks[0].clone();
|
||||
file.hunks = vec![formatting.clone(), semantic.clone()];
|
||||
let review = review_of(std::slice::from_ref(&file));
|
||||
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
workspace.position.file_id = Some(file.id.clone());
|
||||
workspace.position.hunk_id = Some(formatting.id.clone());
|
||||
assert!(workspace.is_hunk_hidden(&file, &file.hunks[0]), "formatting folds by default");
|
||||
|
||||
workspace.next_hunk(&review);
|
||||
|
||||
assert_eq!(workspace.position.hunk_id.as_ref(), Some(&semantic.id));
|
||||
assert_eq!(
|
||||
workspace.position.line_offset, 1,
|
||||
"the collapsed run holds row 0, so the semantic hunk's header is row 1"
|
||||
);
|
||||
let groups = crate::guided_review::visible_groups(&file, &workspace.fold);
|
||||
let all = crate::guided_review::diff::visible_rows(&groups, 0, 8);
|
||||
assert!(
|
||||
matches!(all.first(), Some(crate::guided_review::diff::UnifiedDiffRow::Folded(run)) if run.hunks == 1),
|
||||
"the collapsed formatting hunk still says it is there: {all:?}"
|
||||
);
|
||||
let rows = crate::guided_review::diff::visible_rows(&groups, workspace.position.line_offset, 4);
|
||||
assert!(
|
||||
matches!(rows.first(), Some(crate::guided_review::diff::UnifiedDiffRow::HunkHeader { .. })),
|
||||
"the first rendered row is the selected hunk's header"
|
||||
);
|
||||
}
|
||||
|
||||
/// Regression: hunk stepping used to roll into the next file in canonical *source* order without
|
||||
/// touching the chapter, so the rail narrated one chapter beside another chapter's diff.
|
||||
#[test]
|
||||
fn hunk_navigation_walks_sections_in_order_and_keeps_the_narrative_with_it() {
|
||||
let core = text_file("src/core.rs");
|
||||
let test = text_file("tests/core.rs");
|
||||
let files = vec![core.clone(), test.clone()];
|
||||
let review = review_of(&files);
|
||||
assert_eq!(review.chapters.len(), 2, "path evidence splits core from tests");
|
||||
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
workspace.position.chapter_id = Some(review.chapters[0].id.clone());
|
||||
workspace.position.file_id = Some(core.id.clone());
|
||||
workspace.position.hunk_id = Some(core.hunks[0].id.clone());
|
||||
|
||||
assert!(workspace.at_scope_end(&review), "the core chapter owns exactly one hunk");
|
||||
|
||||
// Stepping carries on into the next section and takes the narrative with it, so the prose on
|
||||
// screen always owns the diff on screen. A boundary that ate the keystroke made the reviewer
|
||||
// discover `]` in order to keep reading, which is not a walkthrough.
|
||||
workspace.next_hunk(&review);
|
||||
assert_eq!(workspace.position.chapter_id.as_ref(), Some(&review.chapters[1].id));
|
||||
assert_eq!(workspace.position.file_id.as_ref(), Some(&test.id));
|
||||
|
||||
// `]` remains the explicit way across.
|
||||
workspace.position.chapter_id = Some(review.chapters[0].id.clone());
|
||||
workspace.position.file_id = Some(core.id.clone());
|
||||
workspace.position.hunk_id = Some(core.hunks[0].id.clone());
|
||||
workspace.next_chapter(&review);
|
||||
assert_eq!(workspace.position.chapter_id.as_ref(), Some(&review.chapters[1].id));
|
||||
assert_eq!(workspace.position.file_id.as_ref(), Some(&test.id));
|
||||
assert_eq!(workspace.position.hunk_id.as_ref(), Some(&test.hunks[0].id));
|
||||
|
||||
// Outside the walkthrough there is no chapter to stay inside, so traversal is unscoped and
|
||||
// walks the whole review in canonical order.
|
||||
workspace.position.chapter_id = Some(review.chapters[0].id.clone());
|
||||
workspace.position.file_id = Some(core.id.clone());
|
||||
workspace.position.hunk_id = Some(core.hunks[0].id.clone());
|
||||
workspace.next_hunk(&review);
|
||||
assert_eq!(workspace.position.file_id.as_ref(), Some(&test.id));
|
||||
}
|
||||
|
||||
/// An explicit jump (a rail click, next-unreviewed, a finding anchor) may legitimately leave the
|
||||
/// current chapter — so it re-points the narrative rather than stranding it.
|
||||
#[test]
|
||||
fn explicit_jumps_repoint_the_narrative_at_the_owning_chapter() {
|
||||
let core = text_file("src/core.rs");
|
||||
let test = text_file("tests/core.rs");
|
||||
let files = vec![core.clone(), test.clone()];
|
||||
let review = review_of(&files);
|
||||
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
workspace.position.chapter_id = Some(review.chapters[0].id.clone());
|
||||
workspace.position.file_id = Some(core.id.clone());
|
||||
workspace.position.hunk_id = Some(core.hunks[0].id.clone());
|
||||
|
||||
workspace.select_file_by_id(&review, &test.id);
|
||||
assert_eq!(workspace.position.file_id.as_ref(), Some(&test.id));
|
||||
assert_eq!(
|
||||
workspace.position.chapter_id.as_ref(),
|
||||
Some(&review.chapters[1].id),
|
||||
"clicking a file outside the chapter moves the narrative with it"
|
||||
);
|
||||
}
|
||||
|
||||
/// The walkthrough follows the order the guide chose, not the filesystem's.
|
||||
///
|
||||
/// A section lists its items in the order the work was reasoned in — the schema before the logic
|
||||
/// that consumes it, the call sites before the tests. Walking `review.files` and merely *filtering*
|
||||
/// by membership threw that away and served the same alphabetical order a plain diff would.
|
||||
#[test]
|
||||
fn stepping_a_section_follows_the_order_the_guide_chose() {
|
||||
use luxe_core::guided_review::{ChapterId, ChapterKind, ReviewChapter, ReviewItemRef};
|
||||
|
||||
let ui = text_file("src/ui.rs");
|
||||
let model = text_file("src/model.rs");
|
||||
let tests = text_file("tests/model.rs");
|
||||
let files = vec![ui.clone(), model.clone(), tests.clone()];
|
||||
let mut review = review_of(&files);
|
||||
// The guide's order: the model first, then the UI that renders it, then the tests.
|
||||
let items = vec![
|
||||
ReviewItemRef::Hunk(model.hunks[0].id.clone()),
|
||||
ReviewItemRef::Hunk(ui.hunks[0].id.clone()),
|
||||
ReviewItemRef::Hunk(tests.hunks[0].id.clone()),
|
||||
];
|
||||
review.chapters = vec![ReviewChapter {
|
||||
id: ChapterId::from_items("core", &[]),
|
||||
title: "The category becomes a type".into(),
|
||||
rationale: "Model first, then its readers.".into(),
|
||||
impact: None,
|
||||
kind: ChapterKind::Core,
|
||||
items,
|
||||
notes: Vec::new(),
|
||||
}];
|
||||
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
workspace.position.chapter_id = Some(review.chapters[0].id.clone());
|
||||
workspace.position.file_id = Some(model.id.clone());
|
||||
workspace.position.hunk_id = Some(model.hunks[0].id.clone());
|
||||
|
||||
workspace.next_hunk(&review);
|
||||
assert_eq!(
|
||||
workspace.position.file_id.as_ref(),
|
||||
Some(&ui.id),
|
||||
"the guide put the UI second; source order would have gone to tests/model.rs"
|
||||
);
|
||||
workspace.next_hunk(&review);
|
||||
assert_eq!(workspace.position.file_id.as_ref(), Some(&tests.id));
|
||||
assert!(workspace.at_scope_end(&review), "three items, three stops");
|
||||
|
||||
workspace.previous_hunk(&review);
|
||||
assert_eq!(workspace.position.file_id.as_ref(), Some(&ui.id), "and back again in that order");
|
||||
}
|
||||
|
||||
/// Outside a section the order is the source's, because there is no narrative to follow.
|
||||
#[test]
|
||||
fn all_files_walks_canonical_source_order() {
|
||||
let ui = text_file("src/ui.rs");
|
||||
let model = text_file("src/model.rs");
|
||||
let files = vec![ui.clone(), model.clone()];
|
||||
let review = review_of(&files);
|
||||
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
workspace.position.file_id = Some(ui.id.clone());
|
||||
workspace.position.hunk_id = Some(ui.hunks[0].id.clone());
|
||||
|
||||
workspace.next_hunk(&review);
|
||||
|
||||
assert_eq!(workspace.position.file_id.as_ref(), Some(&model.id));
|
||||
}
|
||||
|
||||
/// `]` enters a generated chapter, and walking off the end of the chapter before it does not.
|
||||
///
|
||||
/// The break this catches: the two callers that find a neighboring chapter share a lookup and
|
||||
/// differ only in that refusal, so folding them together can quietly give the walkthrough `]`'s
|
||||
/// policy, or `]` the walkthrough's.
|
||||
#[test]
|
||||
fn explicit_chapter_step_enters_generated_but_walkthrough_boundary_stops() {
|
||||
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
|
||||
let mut review = app.guided_review.take().expect("fixture review");
|
||||
let mut generated = review.chapters[0].clone();
|
||||
generated.id = ChapterId::from_item_keys("generated", &["fixture-generated"]);
|
||||
generated.kind = luxe_core::guided_review::ChapterKind::Generated;
|
||||
review.chapters.push(generated.clone());
|
||||
let first = review.chapters[0].id.clone();
|
||||
|
||||
let mut walking = app.guided_review_workspace.clone();
|
||||
walking.position.chapter_id = Some(first.clone());
|
||||
for _ in 0..64 {
|
||||
walking.next_hunk(&review);
|
||||
}
|
||||
assert_eq!(walking.position.chapter_id, Some(first.clone()), "the walk stops at the boundary");
|
||||
|
||||
let mut jumping = app.guided_review_workspace;
|
||||
jumping.position.chapter_id = Some(first);
|
||||
jumping.next_chapter(&review);
|
||||
assert_eq!(jumping.position.chapter_id, Some(generated.id), "`]` opens it");
|
||||
}
|
||||
168
crates/luxe-tui/src/guided_review/tests/refresh.rs
Normal file
168
crates/luxe-tui/src/guided_review/tests/refresh.rs
Normal file
@@ -0,0 +1,168 @@
|
||||
//! Refresh: what the position keeps, and where it falls back to, when the review is recaptured.
|
||||
|
||||
use super::super::*;
|
||||
use super::{review_of, text_file};
|
||||
use luxe_core::guided_review::{NonTextChange, NonTextChangeKind};
|
||||
|
||||
#[test]
|
||||
fn accepting_a_refreshed_review_closes_noise_details() {
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
workspace.toggle_noise_details();
|
||||
|
||||
workspace.mark_ready();
|
||||
|
||||
assert!(!workspace.noise_details_visible);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refresh_retains_selected_non_text_file_without_a_hunk_anchor() {
|
||||
let mut file = text_file("assets/selected.bin");
|
||||
file.hunks.clear();
|
||||
file.binary = true;
|
||||
file.non_text = Some(NonTextChange {
|
||||
kind: NonTextChangeKind::Binary,
|
||||
summary: "Binary files differ".into(),
|
||||
});
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(file.id.clone()),
|
||||
hunk_id: None,
|
||||
line_offset: 0,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
workspace.reconcile_position(&[file.clone()]);
|
||||
|
||||
assert_eq!(workspace.position.file_id, Some(file.id));
|
||||
assert_eq!(workspace.position.hunk_id, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn position_reconciliation_falls_back_to_first_non_text_file() {
|
||||
let mut first = text_file("assets/first.bin");
|
||||
first.hunks.clear();
|
||||
first.binary = true;
|
||||
first.non_text = Some(NonTextChange {
|
||||
kind: NonTextChangeKind::Binary,
|
||||
summary: "Binary files differ".into(),
|
||||
});
|
||||
let mut second = text_file("assets/second.bin");
|
||||
second.hunks.clear();
|
||||
second.binary = true;
|
||||
second.non_text = Some(NonTextChange {
|
||||
kind: NonTextChangeKind::Binary,
|
||||
summary: "Binary files differ".into(),
|
||||
});
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
|
||||
workspace.reconcile_position(&[first.clone(), second]);
|
||||
|
||||
assert_eq!(workspace.position.file_id, Some(first.id));
|
||||
assert_eq!(workspace.position.hunk_id, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refresh_falls_back_when_selected_non_text_file_disappears() {
|
||||
let mut retained = text_file("assets/retained.bin");
|
||||
retained.hunks.clear();
|
||||
retained.binary = true;
|
||||
retained.non_text = Some(NonTextChange {
|
||||
kind: NonTextChangeKind::Binary,
|
||||
summary: "Binary files differ".into(),
|
||||
});
|
||||
let mut removed = text_file("assets/removed.bin");
|
||||
removed.hunks.clear();
|
||||
removed.binary = true;
|
||||
removed.non_text = Some(NonTextChange {
|
||||
kind: NonTextChangeKind::Binary,
|
||||
summary: "Binary files differ".into(),
|
||||
});
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(removed.id),
|
||||
hunk_id: None,
|
||||
line_offset: 9,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
workspace.reconcile_position(&[retained.clone()]);
|
||||
|
||||
assert_eq!(workspace.position.file_id, Some(retained.id));
|
||||
assert_eq!(workspace.position.hunk_id, None);
|
||||
assert_eq!(workspace.position.line_offset, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refresh_falls_back_to_a_retained_file_when_its_selected_hunk_changes() {
|
||||
let file = text_file("src/retained.rs");
|
||||
let mut refreshed = file.clone();
|
||||
refreshed.hunks[0].id = HunkId::from_content(&refreshed.id, "changed", "let replacement = 2;");
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(file.id.clone()),
|
||||
hunk_id: Some(file.hunks[0].id.clone()),
|
||||
line_offset: 7,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
workspace.reconcile_position(std::slice::from_ref(&refreshed));
|
||||
|
||||
assert_eq!(workspace.position.file_id, Some(file.id));
|
||||
assert_eq!(workspace.position.hunk_id, Some(refreshed.hunks[0].id.clone()));
|
||||
assert_eq!(workspace.position.line_offset, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_hunk_fallback_keeps_navigation_in_the_retained_file() {
|
||||
let file = text_file("src/retained-navigation.rs");
|
||||
let mut refreshed = file.clone();
|
||||
refreshed.hunks[0].id = HunkId::from_content(&refreshed.id, "changed", "let replacement = 2;");
|
||||
let mut following = refreshed.hunks[0].clone();
|
||||
following.id = HunkId::from_content(&refreshed.id, "following", "let following = 3;");
|
||||
refreshed.hunks.push(following.clone());
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(file.id.clone()),
|
||||
hunk_id: Some(file.hunks[0].id.clone()),
|
||||
line_offset: 7,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
workspace.reconcile_position(std::slice::from_ref(&refreshed));
|
||||
workspace.next_hunk(&review_of(std::slice::from_ref(&refreshed)));
|
||||
|
||||
assert_eq!(workspace.position.file_id, Some(file.id));
|
||||
assert_eq!(workspace.position.hunk_id, Some(following.id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refresh_keeps_stable_position_and_resets_only_when_it_disappears() {
|
||||
let first = text_file("src/first.rs");
|
||||
let replacement = text_file("src/replacement.rs");
|
||||
let mut workspace = GuidedReviewWorkspace {
|
||||
position: ReviewPosition {
|
||||
chapter_id: None,
|
||||
file_id: Some(first.id.clone()),
|
||||
hunk_id: Some(first.hunks[0].id.clone()),
|
||||
line_offset: 7,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
workspace.reconcile_position(std::slice::from_ref(&first));
|
||||
assert_eq!(workspace.position.line_offset, 7);
|
||||
assert_eq!(workspace.position.file_id, Some(first.id));
|
||||
|
||||
workspace.reconcile_position(std::slice::from_ref(&replacement));
|
||||
assert_eq!(workspace.position.line_offset, 0);
|
||||
assert_eq!(workspace.position.file_id, Some(replacement.id));
|
||||
assert_eq!(workspace.position.hunk_id, Some(replacement.hunks[0].id.clone()));
|
||||
}
|
||||
46
crates/luxe-tui/src/guided_review/tests/search.rs
Normal file
46
crates/luxe-tui/src/guided_review/tests/search.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
//! Search in the diff.
|
||||
|
||||
use super::super::*;
|
||||
use super::{review_of, text_file};
|
||||
|
||||
#[test]
|
||||
fn find_in_diff_jumps_across_files_and_wraps() {
|
||||
let file_a = text_file("src/a.rs");
|
||||
let file_b = text_file("src/b.rs");
|
||||
let files = vec![file_a.clone(), file_b.clone()];
|
||||
let review = review_of(&files);
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
workspace.position.file_id = Some(file_a.id.clone());
|
||||
workspace.position.hunk_id = Some(file_a.hunks[0].id.clone());
|
||||
workspace.position.line_offset = 0;
|
||||
workspace.begin_search();
|
||||
for character in "value".chars() {
|
||||
workspace.search_input(character);
|
||||
}
|
||||
|
||||
// Row 0 is the hunk header; row 1 is the matching "let value = 1;" line.
|
||||
assert!(workspace.jump_search(&review, true));
|
||||
assert_eq!(workspace.position.file_id.as_ref(), Some(&file_a.id));
|
||||
assert_eq!(workspace.position.line_offset, 1);
|
||||
|
||||
// No further match in file A, so the next jump crosses into file B.
|
||||
assert!(workspace.jump_search(&review, true));
|
||||
assert_eq!(
|
||||
workspace.position.file_id.as_ref(),
|
||||
Some(&file_b.id),
|
||||
"the search jumps to the next file's match"
|
||||
);
|
||||
assert_eq!(workspace.position.line_offset, 1);
|
||||
|
||||
// And once more wraps back to file A.
|
||||
assert!(workspace.jump_search(&review, true));
|
||||
assert_eq!(
|
||||
workspace.position.file_id.as_ref(),
|
||||
Some(&file_a.id),
|
||||
"the search wraps back to the first file"
|
||||
);
|
||||
|
||||
// Backward from file A crosses to file B's last match.
|
||||
assert!(workspace.jump_search(&review, false));
|
||||
assert_eq!(workspace.position.file_id.as_ref(), Some(&file_b.id));
|
||||
}
|
||||
147
crates/luxe-tui/src/guided_review/tests/sources.rs
Normal file
147
crates/luxe-tui/src/guided_review/tests/sources.rs
Normal file
@@ -0,0 +1,147 @@
|
||||
//! Sources: the picker, and a load that fails.
|
||||
|
||||
use super::super::*;
|
||||
use luxe_core::event::GuidedReviewFailureKind;
|
||||
|
||||
#[test]
|
||||
fn failed_refresh_keeps_typed_target_and_error() {
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
workspace.begin_loading(ReviewTarget::WorkingTree);
|
||||
workspace.mark_failed(
|
||||
ReviewTarget::WorkingTree,
|
||||
GuidedReviewFailure {
|
||||
kind: GuidedReviewFailureKind::Capture,
|
||||
message: "source changed while capturing".into(),
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
workspace.load_state,
|
||||
GuidedReviewLoadState::Failed {
|
||||
target: ReviewTarget::WorkingTree,
|
||||
error: GuidedReviewFailure {
|
||||
kind: GuidedReviewFailureKind::Capture,
|
||||
message: "source changed while capturing".into(),
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_picker_opens_at_the_working_tree_and_closes_locally() {
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
|
||||
workspace.toggle_source_picker();
|
||||
assert_eq!(
|
||||
workspace.source_picker,
|
||||
ReviewSourcePickerState::Open { selection: ReviewSourcePickerSelection::WorkingTree }
|
||||
);
|
||||
workspace.toggle_source_picker();
|
||||
assert_eq!(workspace.source_picker, ReviewSourcePickerState::Closed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_picker_recovers_from_a_failed_review_without_replacing_pinned_state() {
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
workspace.mark_failed(
|
||||
ReviewTarget::WorkingTree,
|
||||
GuidedReviewFailure {
|
||||
kind: GuidedReviewFailureKind::Capture,
|
||||
message: "capture failed".into(),
|
||||
},
|
||||
);
|
||||
|
||||
workspace.toggle_source_picker();
|
||||
|
||||
assert_eq!(
|
||||
workspace.source_picker,
|
||||
ReviewSourcePickerState::Open { selection: ReviewSourcePickerSelection::WorkingTree }
|
||||
);
|
||||
assert!(matches!(workspace.load_state, GuidedReviewLoadState::Failed { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_picker_skips_unavailable_last_turn_when_navigating() {
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
workspace.toggle_source_picker();
|
||||
|
||||
workspace.move_source_picker_selection(true, false);
|
||||
assert_eq!(
|
||||
workspace.source_picker,
|
||||
ReviewSourcePickerState::Open { selection: ReviewSourcePickerSelection::Base }
|
||||
);
|
||||
workspace.move_source_picker_selection(false, false);
|
||||
assert_eq!(
|
||||
workspace.source_picker,
|
||||
ReviewSourcePickerState::Open { selection: ReviewSourcePickerSelection::WorkingTree }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_picker_selection_wraps_in_presentation_order() {
|
||||
let mut workspace = GuidedReviewWorkspace::default();
|
||||
workspace.toggle_source_picker();
|
||||
|
||||
workspace.move_source_picker_selection(false, true);
|
||||
assert_eq!(
|
||||
workspace.source_picker,
|
||||
ReviewSourcePickerState::Open { selection: ReviewSourcePickerSelection::Commit }
|
||||
);
|
||||
workspace.move_source_picker_selection(true, true);
|
||||
workspace.move_source_picker_selection(true, true);
|
||||
assert_eq!(
|
||||
workspace.source_picker,
|
||||
ReviewSourcePickerState::Open { selection: ReviewSourcePickerSelection::LastTurn }
|
||||
);
|
||||
|
||||
workspace.begin_source_reference_entry(ReviewSourceReferenceKind::Base);
|
||||
assert_eq!(
|
||||
workspace.source_reference_entry,
|
||||
Some(ReviewSourceReferenceEntry {
|
||||
kind: ReviewSourceReferenceKind::Base,
|
||||
value: String::new(),
|
||||
error: None,
|
||||
})
|
||||
);
|
||||
|
||||
assert_eq!(workspace.submit_source_reference(), None);
|
||||
assert_eq!(
|
||||
workspace.source_reference_entry.as_ref().and_then(|entry| entry.error),
|
||||
Some("Type a base reference.")
|
||||
);
|
||||
workspace.push_source_reference_char('m');
|
||||
workspace.push_source_reference_char('a');
|
||||
workspace.pop_source_reference_char();
|
||||
assert_eq!(
|
||||
workspace.source_reference_entry.as_ref().map(|entry| entry.value.as_str()),
|
||||
Some("m")
|
||||
);
|
||||
assert_eq!(
|
||||
workspace.submit_source_reference(),
|
||||
Some(ReviewTarget::Base { reference: "m".into() })
|
||||
);
|
||||
|
||||
workspace.begin_source_reference_entry(ReviewSourceReferenceKind::Commit);
|
||||
assert_eq!(workspace.submit_source_reference(), None);
|
||||
assert_eq!(
|
||||
workspace.source_reference_entry.as_ref().and_then(|entry| entry.error),
|
||||
Some("Type a commit object ID.")
|
||||
);
|
||||
for character in "zzzz".chars() {
|
||||
workspace.push_source_reference_char(character);
|
||||
}
|
||||
assert_eq!(workspace.submit_source_reference(), None);
|
||||
assert_eq!(
|
||||
workspace.source_reference_entry.as_ref().and_then(|entry| entry.error),
|
||||
Some("Commit ID must be 4–64 hexadecimal characters.")
|
||||
);
|
||||
workspace.source_reference_entry.as_mut().expect("commit entry").value = "a1b2c3d4".into();
|
||||
assert_eq!(
|
||||
workspace.submit_source_reference(),
|
||||
Some(ReviewTarget::Commit { oid: "a1b2c3d4".into() })
|
||||
);
|
||||
|
||||
workspace.begin_loading(ReviewTarget::WorkingTree);
|
||||
assert_eq!(workspace.source_picker, ReviewSourcePickerState::Closed);
|
||||
assert_eq!(workspace.source_reference_entry, None);
|
||||
}
|
||||
151
crates/luxe-tui/src/guided_review/viewport.rs
Normal file
151
crates/luxe-tui/src/guided_review/viewport.rs
Normal file
@@ -0,0 +1,151 @@
|
||||
//! Review viewport — the terminal's size, the guide's width, the diff's layout, wrapping and
|
||||
//! scrolling by lines and pages.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl GuidedReviewWorkspace {
|
||||
/// Toggles soft word-wrap for long unified-diff source lines. Wrapping supersedes horizontal
|
||||
/// scrolling, so the column offset is reset when it turns on.
|
||||
pub(crate) fn toggle_word_wrap(&mut self) {
|
||||
self.word_wrap = !self.word_wrap;
|
||||
if self.word_wrap {
|
||||
self.diff_column_offset = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Flips the diff between one column and two for this session.
|
||||
///
|
||||
/// Records the opposite of what is *showing* rather than cycling the setting, so the first
|
||||
/// press always changes something: moving `auto` to `split` on a pane already wide enough to
|
||||
/// pair the sides would be a key that does nothing.
|
||||
pub(crate) fn toggle_split_preference(&mut self, files: &[ReviewFile]) {
|
||||
self.layout = match self.split_layout_showing(files) {
|
||||
true => DiffLayout::Unified,
|
||||
// `split` rather than `auto`, because a reader who reached for the key on a pane
|
||||
// `auto` had already declined wants the pairing, not the rule that refused it.
|
||||
false => DiffLayout::Split,
|
||||
};
|
||||
}
|
||||
|
||||
/// Cells of code one column would get for a file whose line numbers need `gutter` of them.
|
||||
///
|
||||
/// The quantity [`DiffLayout::splits`] is written in, so the review reaches the same verdict a
|
||||
/// tool card would on the same content — it just has different chrome to pay for first.
|
||||
fn split_column_cells(&self, gutter: usize) -> usize {
|
||||
(self.diff_viewport_columns.saturating_sub(SPLIT_PANE_CHROME) / 2)
|
||||
.saturating_sub(gutter + 2)
|
||||
}
|
||||
|
||||
/// The farthest right the diff may scroll on `file`: until its widest line's last cell shows.
|
||||
///
|
||||
/// Measured over the whole file, because the pane draws the whole file at one offset. Bounding
|
||||
/// it by the hunk under the cursor left every longer line in the other hunks out of reach.
|
||||
pub(crate) fn column_maximum(&self, file: &ReviewFile) -> usize {
|
||||
let gutter = diff::gutter_width(&file.hunks);
|
||||
let room = if self.split_layout_active_for(file) {
|
||||
self.split_column_cells(gutter)
|
||||
} else {
|
||||
self.diff_viewport_columns.saturating_sub(gutter * 2 + UNIFIED_ROW_CHROME)
|
||||
};
|
||||
file_source_width(file).saturating_sub(room)
|
||||
}
|
||||
|
||||
/// Whether *this file* renders side by side.
|
||||
///
|
||||
/// Side-by-side is a *view* of the unified row space rather than a mode with its own scroll
|
||||
/// position, so this is the only state the renderer needs.
|
||||
pub(crate) fn split_layout_active_for(&self, file: &ReviewFile) -> bool {
|
||||
self.layout
|
||||
.splits(self.split_column_cells(diff::gutter_width(&file.hunks)), has_two_sides(file))
|
||||
}
|
||||
|
||||
/// Whether the file the reviewer is on is drawn side by side.
|
||||
///
|
||||
/// For the callers that hold the file list rather than the file: horizontal scroll bounds, and
|
||||
/// the toggle deciding what it is flipping away from.
|
||||
pub(crate) fn split_layout_showing(&self, files: &[ReviewFile]) -> bool {
|
||||
self.selected_file(files).is_some_and(|file| self.split_layout_active_for(file))
|
||||
}
|
||||
|
||||
/// The file the reviewer is on, when the position names one the review still has.
|
||||
pub(super) fn selected_file<'a>(&self, files: &'a [ReviewFile]) -> Option<&'a ReviewFile> {
|
||||
let id = self.position.file_id.as_ref()?;
|
||||
files.iter().find(|file| &file.id == id)
|
||||
}
|
||||
|
||||
/// Updates the usable full-screen diff size after a terminal resize.
|
||||
///
|
||||
/// What the *diff pane* has, not what the terminal has: the layout decisions that hang off this
|
||||
/// — whether side by side fits, how far a horizontal scroll may run — are wrong by the width of
|
||||
/// the guide pane otherwise, and a side-by-side diff runs its right column off the edge.
|
||||
pub(crate) fn set_terminal_size(&mut self, terminal_columns: u16, terminal_rows: u16) {
|
||||
self.diff_viewport_rows = usize::from(terminal_rows.saturating_sub(3)).max(1);
|
||||
self.diff_viewport_columns = usize::from(self.diff_columns(terminal_columns)).max(1);
|
||||
self.terminal_columns = terminal_columns;
|
||||
}
|
||||
|
||||
/// Sizes the guide to `width`, the reader's drag, or back to the terminal's share with `None`.
|
||||
///
|
||||
/// The diff's column count follows at once, because everything that scrolls it horizontally
|
||||
/// reads that rather than the frame.
|
||||
pub(crate) fn set_guide_width(&mut self, width: Option<u16>) {
|
||||
self.guide_width = width;
|
||||
self.diff_viewport_columns = usize::from(self.diff_columns(self.terminal_columns)).max(1);
|
||||
}
|
||||
|
||||
/// Cells the guide pane takes in a `terminal_columns`-wide review.
|
||||
pub(crate) fn guide_width(&self, terminal_columns: u16) -> u16 {
|
||||
crate::workspace_layout::guide_width(terminal_columns, self.guide_width)
|
||||
}
|
||||
|
||||
/// Cells the diff pane gets at `terminal_columns`, the guide's share already taken out.
|
||||
fn diff_columns(&self, terminal_columns: u16) -> u16 {
|
||||
let guide = if terminal_columns >= crate::workspace_layout::WIDE_LAYOUT_MIN_WIDTH
|
||||
&& self.guide_visible
|
||||
{
|
||||
self.guide_width(terminal_columns)
|
||||
+ crate::workspace_layout::CONTEXT_DOCK_SEPARATOR_WIDTH
|
||||
} else {
|
||||
0
|
||||
};
|
||||
terminal_columns.saturating_sub(guide).saturating_sub(DIFF_PANE_CHROME)
|
||||
}
|
||||
|
||||
/// Advances the visible source-row window by one row, stopping at the file's last row.
|
||||
pub(crate) fn next_line(&mut self, review: &GuidedReview) {
|
||||
self.scroll_lines(review, 1, true);
|
||||
}
|
||||
|
||||
/// Moves the visible source-row window up by one row, stopping at the file's first row.
|
||||
pub(crate) fn previous_line(&mut self, review: &GuidedReview) {
|
||||
self.scroll_lines(review, 1, false);
|
||||
}
|
||||
|
||||
/// Advances by the rendered diff viewport, stopping at the file's last row.
|
||||
pub(crate) fn next_page(&mut self, review: &GuidedReview) {
|
||||
self.scroll_lines(review, self.diff_viewport_rows, true);
|
||||
}
|
||||
|
||||
/// Moves back by the rendered diff viewport, stopping at the file's first row.
|
||||
pub(crate) fn previous_page(&mut self, review: &GuidedReview) {
|
||||
self.scroll_lines(review, self.diff_viewport_rows, false);
|
||||
}
|
||||
|
||||
/// Moves half the rendered diff viewport, as `Ctrl+D` and `Ctrl+U` do in vim.
|
||||
pub(crate) fn half_page(&mut self, review: &GuidedReview, forward: bool) {
|
||||
self.scroll_lines(review, (self.diff_viewport_rows / 2).max(1), forward);
|
||||
}
|
||||
|
||||
/// Hides the guide pane, or brings it back.
|
||||
///
|
||||
/// A reviewer who wants every cell for the code, on a terminal that has room for both. Below
|
||||
/// the wide tier the guide is not shown at all and this changes nothing visible — which is why
|
||||
/// the footer only offers the key where it can act.
|
||||
pub(crate) fn toggle_guide(&mut self) {
|
||||
self.guide_visible = !self.guide_visible;
|
||||
// The diff pane just grew or shrank by the guide's width, and everything that hangs off
|
||||
// that — the side-by-side threshold, the horizontal scroll bound — is stale until it is
|
||||
// told so.
|
||||
self.diff_viewport_columns = usize::from(self.diff_columns(self.terminal_columns)).max(1);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user