From 3814086da37a97cbbeef331fe2c8a69b6844c8e0 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Tue, 24 Nov 2026 18:13:10 -0500 Subject: [PATCH 01/12] feat(review): draw notes in the diff, in boxes under their lines A Notes setting (panel, inline, both; [review] notes, the settings menu after Wrap, remembered) draws each note in a box under the last line it is about, over its side of a split diff, the file's notes under its heading. The cursor stops on a box: enter or e edits it over the box, delete removes it; a click picks its note. Boxes never move the line the cursor is on. Uses the insets of diffs-rs (plannotator/diffs-rs#23). --- Cargo.lock | 12 +- Cargo.toml | 7 + README.md | 20 +- crates/plannotator-tui/src/config/review.rs | 31 +- crates/plannotator-tui/src/keys.rs | 8 + .../plannotator-tui/src/review/compose_at.rs | 18 +- crates/plannotator-tui/src/review/diff.rs | 11 + .../plannotator-tui/src/review/diff/insets.rs | 131 ++++++ .../plannotator-tui/src/review/diff/place.rs | 2 + crates/plannotator-tui/src/review/drafts.rs | 33 +- crates/plannotator-tui/src/review/draw.rs | 12 +- crates/plannotator-tui/src/review/footer.rs | 41 +- crates/plannotator-tui/src/review/inline.rs | 239 ++++++++++ .../plannotator-tui/src/review/inline/card.rs | 168 +++++++ .../src/review/inline/paint.rs | 99 +++++ crates/plannotator-tui/src/review/input.rs | 7 +- crates/plannotator-tui/src/review/mod.rs | 24 +- crates/plannotator-tui/src/review/overlays.rs | 14 +- crates/plannotator-tui/src/review/settings.rs | 19 +- .../src/review/settings/state.rs | 27 +- .../src/review/tests/inline_flow.rs | 396 +++++++++++++++++ .../src/review/tests/inline_support.rs | 144 ++++++ .../src/review/tests/inline_view.rs | 409 ++++++++++++++++++ .../plannotator-tui/src/review/tests/mod.rs | 3 + .../src/review/tests/save_keeps_view.rs | 12 +- .../src/review/tests/settings_flow.rs | 16 +- .../src/review/tests/whitespace_flow.rs | 2 +- 27 files changed, 1859 insertions(+), 46 deletions(-) create mode 100644 crates/plannotator-tui/src/review/diff/insets.rs create mode 100644 crates/plannotator-tui/src/review/inline.rs create mode 100644 crates/plannotator-tui/src/review/inline/card.rs create mode 100644 crates/plannotator-tui/src/review/inline/paint.rs create mode 100644 crates/plannotator-tui/src/review/tests/inline_flow.rs create mode 100644 crates/plannotator-tui/src/review/tests/inline_support.rs create mode 100644 crates/plannotator-tui/src/review/tests/inline_view.rs diff --git a/Cargo.lock b/Cargo.lock index b5d3bd37..6d534fce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -524,8 +524,7 @@ checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" [[package]] name = "diffs-fancy-regex" version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c8bafb03bb9ed9eeb28ac231849ae6be395c8bf483f6a6f46db0616828e8fbc" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#8eac7f92607632e293500ca1fdcd08a6c27b70ba" dependencies = [ "bit-set 0.8.0", "regex-automata", @@ -535,8 +534,7 @@ dependencies = [ [[package]] name = "diffs-rs" version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcdfed9710ded23e6bc48a1175f879fc530ad6ba367177f1447af89e297d989b" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#8eac7f92607632e293500ca1fdcd08a6c27b70ba" dependencies = [ "anyhow", "clap", @@ -562,8 +560,7 @@ dependencies = [ [[package]] name = "diffs-syntect" version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf57443c937ba79afc5d9c7ca4b63d411dad8fb25fa72f0a5f063c71234e0e4d" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#8eac7f92607632e293500ca1fdcd08a6c27b70ba" dependencies = [ "bincode", "diffs-fancy-regex", @@ -583,8 +580,7 @@ dependencies = [ [[package]] name = "diffs-two-face" version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fc53b9992dd1e96ffd1daf26d10ee81cfa0bbbe356b8eaf39a971d8819cd67e" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#8eac7f92607632e293500ca1fdcd08a6c27b70ba" dependencies = [ "diffs-syntect", "serde", diff --git a/Cargo.toml b/Cargo.toml index d4f03b01..c0eff1f5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,6 +52,13 @@ cast_sign_loss = "allow" cast_possible_wrap = "allow" cast_precision_loss = "allow" +# diffs-rs: rows between the diff's rows for the notes drawn inline (plannotator/diffs-rs#23), +# until it is published. Its two forks come from the same checkout, so one copy of each is built. +[patch.crates-io] +diffs-rs = { git = "https://github.com/plannotator/diffs-rs", branch = "feat/insets" } +diffs-syntect = { git = "https://github.com/plannotator/diffs-rs", branch = "feat/insets" } +diffs-two-face = { git = "https://github.com/plannotator/diffs-rs", branch = "feat/insets" } + [profile.release] lto = "thin" # Shipped binaries carry no debug info; profile locally with `--profile profiling`. diff --git a/README.md b/README.md index 5c73805e..2e8da842 100644 --- a/README.md +++ b/README.md @@ -298,8 +298,8 @@ The header shows the layout as a switch, `Split Unified` with the one in force the line between the old and the new side to give one side more of the width, or press `(` and `)`; a double click on the line makes the sides even again. Each side keeps at least 20 columns. `,` (or the header's `Settings` button) opens the diff settings: layout, split -ratio, wrap, line numbers, whitespace, tab width, changed text, colours and background, each -with its value. `↑`/`↓` pick one, +ratio, wrap, notes, line numbers, whitespace, tab width, changed text, colours and background, +each with its value. `↑`/`↓` pick one, `←`/`→` change it, `enter` or `space` moves it on (and evens the split ratio), a click on a row does the same, and `esc` closes the menu. Every change applies at once and is remembered for the next review, however you made it (the menu, the switches, a key or a drag); the menu's @@ -308,6 +308,21 @@ last row, **Reset to defaults**, forgets those choices and goes back to the key hints first, then the `Wrap` switch, the `Settings` button and the `Review` button, and keeps the layout switch longest (as `S U` when it must). +The settings' **Notes** row draws the notes in the diff, as a pull request's comments sit +in its diff: `panel` (the default) keeps them in the notes panel only, `inline` draws each in +a box under the last line it is about, and `both` does both. A box sits over its side of a +split diff (across both sides when that side is too narrow), several on one line stack in the +order they were made, and a note on the whole file sits under the file's heading. The box +shows the note's kind and lines, its author when it is not you, `sent` once sent, and up to +six lines of its text (a suggestion's code as `-`/`+` lines); `… enter for more` says there +is more. The cursor stops once on each box: `enter` or `e` opens the note in the comment box +over it, `delete` removes it, and a click on a box picks its note (in the panel too). A drag +selects code only, and boxes never move the line you are on. Notes on the whole change, and +notes whose lines the diff does not show now (outdated, in a hunk hidden with `W`, in a +filtered-out file), get no box: the footer counts them (`2 notes not shown inline · z`) and +the panel lists them. With `inline` the panel starts away whatever notes there are; `z` +opens it for the session. The whole-file view (`o`/`O`) keeps its notes in the panel. + The changed files are listed left of the diff as a folder tree. A chain of folders with one folder each is one row (`crates/app/src/`), and the list is as wide as its names need, up to two fifths of the screen. A name that does not fit is cut in the middle, so @@ -535,6 +550,7 @@ file without the table opens diffs as before: layout = "auto" # auto (split in a terminal 141 columns wide or more; default) | split | unified split_ratio = 0.5 # the old side's share of a split row, 0.1 to 0.9; the new side gets the rest wrap = false # wrap long lines instead of scrolling them sideways +notes = "panel" # panel (the notes panel only; default) | inline (boxes in the diff) | both line_numbers = true # line numbers in the gutter; off keeps the +/- signs theme = "auto" # the diff's colours: auto (follow [ui] theme, default) | dark | light background = "terminal" # terminal (the terminal's own background, default) | theme (the diff theme's) diff --git a/crates/plannotator-tui/src/config/review.rs b/crates/plannotator-tui/src/config/review.rs index 0f94ac3e..ba0d3af1 100644 --- a/crates/plannotator-tui/src/config/review.rs +++ b/crates/plannotator-tui/src/config/review.rs @@ -30,6 +30,9 @@ pub(crate) struct ReviewConfig { pub(crate) tab_width: TabWidth, /// How the changed text inside a changed line is marked, by Pierre's names. pub(crate) inline_changes: InlineChanges, + /// Where the notes show: the panel beside the diff, boxes in the diff under their lines, + /// or both. + pub(crate) notes: Notes, } impl ReviewConfig { @@ -44,6 +47,7 @@ impl ReviewConfig { whitespace: Whitespace::Show, tab_width: TabWidth::DEFAULT, inline_changes: InlineChanges::Word, + notes: Notes::Panel, }; } @@ -112,6 +116,19 @@ pub(crate) enum InlineChanges { None, } +/// `[review] notes`: where the code review shows its notes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(crate) enum Notes { + /// In the notes panel beside the diff, with a mark in the gutter. + #[default] + Panel, + /// In boxes in the diff under their lines; the panel opens only by hand. + Inline, + /// In boxes in the diff and in the panel. + Both, +} + /// `[review] tab_width`: the columns a tab advances to, from 1 to 16. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub(crate) struct TabWidth(u8); @@ -239,6 +256,7 @@ mod tests { whitespace: Whitespace::Show, tab_width: TabWidth::new(4), inline_changes: InlineChanges::Word, + notes: Notes::Panel, } ); } @@ -280,7 +298,7 @@ mod tests { #[test] fn every_review_setting_is_read_and_roundtrips() { - let text = "[review]\nlayout = \"unified\"\nwrap = true\nline_numbers = false\ntheme = \"light\"\nbackground = \"theme\"\nsplit_ratio = 0.62\nwhitespace = \"ignore-all\"\ntab_width = 8\ninline_changes = \"word-alt\"\n"; + let text = "[review]\nlayout = \"unified\"\nwrap = true\nline_numbers = false\ntheme = \"light\"\nbackground = \"theme\"\nsplit_ratio = 0.62\nwhitespace = \"ignore-all\"\ntab_width = 8\ninline_changes = \"word-alt\"\nnotes = \"both\"\n"; let config = Config::parse(text).expect("parses"); let review = config.review; assert_eq!(review.layout, Layout::Unified); @@ -291,11 +309,14 @@ mod tests { assert_eq!(review.whitespace, Whitespace::IgnoreAll); assert_eq!(review.tab_width.get(), 8); assert_eq!(review.inline_changes, InlineChanges::WordAlt); + assert_eq!(review.notes, Notes::Both); let shown = config.to_toml().expect("toml"); assert!(shown.contains("[review]\nlayout = \"unified\""), "{shown}"); assert!(shown.contains("split_ratio = 0.62\n"), "{shown}"); assert!( - shown.contains("whitespace = \"ignore-all\"\ntab_width = 8\ninline_changes = \"word-alt\"\n"), + shown.contains( + "whitespace = \"ignore-all\"\ntab_width = 8\ninline_changes = \"word-alt\"\nnotes = \"both\"\n" + ), "{shown}" ); assert_eq!(Config::parse(&shown).expect("reparses"), config); @@ -317,6 +338,10 @@ mod tests { let config = Config::parse(&format!("[review]\ninline_changes = \"{name}\"\n")).expect("parses"); assert_eq!(config.review.inline_changes, value, "{name}"); } + for (name, value) in [("panel", Notes::Panel), ("inline", Notes::Inline), ("both", Notes::Both)] { + let config = Config::parse(&format!("[review]\nnotes = \"{name}\"\n")).expect("parses"); + assert_eq!(config.review.notes, value, "{name}"); + } for width in 1..=16 { let config = Config::parse(&format!("[review]\ntab_width = {width}\n")).expect("parses"); assert_eq!(config.review.tab_width.get(), width); @@ -338,6 +363,8 @@ mod tests { ("[review]\nwhitespace = \"hide\"\n", "hide"), ("[review]\nwhitespace = true\n", "wanted string"), ("[review]\ninline_changes = \"words\"\n", "words"), + ("[review]\nnotes = \"rail\"\n", "rail"), + ("[review]\nnotes = true\n", "wanted string"), ] { let err = Config::parse(text).expect_err("rejected"); assert!(err.to_string().contains(named), "{text:?}: {err}"); diff --git a/crates/plannotator-tui/src/keys.rs b/crates/plannotator-tui/src/keys.rs index e59b93ac..acaaf0a3 100644 --- a/crates/plannotator-tui/src/keys.rs +++ b/crates/plannotator-tui/src/keys.rs @@ -636,6 +636,14 @@ impl Keymap { self.keys(action).first().map(|key| key.hint()).unwrap_or_default() } + /// The action's first key that no action of `context` takes, as the hints spell it; + /// empty when there is none. + pub(crate) fn hint_besides(&self, action: Action, context: &[Action]) -> String { + let taken = + |key: &Key| context.iter().any(|&other| other != action && self.keys(other).contains(key)); + self.keys(action).iter().find(|key| !taken(key)).map(|key| key.hint()).unwrap_or_default() + } + /// `key label` for a hint line, or nothing when the action is unbound, so an unbound /// action leaves no bare label behind. pub(crate) fn labelled(&self, action: Action, label: &str) -> Option { diff --git a/crates/plannotator-tui/src/review/compose_at.rs b/crates/plannotator-tui/src/review/compose_at.rs index be893a73..2c98f515 100644 --- a/crates/plannotator-tui/src/review/compose_at.rs +++ b/crates/plannotator-tui/src/review/compose_at.rs @@ -7,6 +7,8 @@ //! the room keep the box at the end the person last moved to, the cursor's end. //! - A file (`C`, editing a file note): under the file's heading, else at the top of the pane. //! - The whole change (`M`, editing its note), or lines no longer on screen: centred. +//! - Editing a note whose box the diff shows (`inline`): over the box, as wide as it. Notes' +//! boxes under the lines of a new one count as theirs: the box opens below them. //! //! The box only draws over the diff: opening, typing in and closing it never move the view //! or the cursor. It grows with its text on the side it opened on and, out of room there, @@ -23,7 +25,7 @@ use crate::ui::compose; pub(super) const MAX_WIDTH: u16 = 84; /// A split diff's side narrower than this is too narrow for the box, which then spans the /// other side too. -const MIN_SIDE_WIDTH: u16 = 48; +pub(super) const MIN_SIDE_WIDTH: u16 = 48; /// One row of text and its borders. const MIN_HEIGHT: u16 = 3; /// The room a side needs for the box to open there: three rows of text to grow into. @@ -52,6 +54,8 @@ enum Anchor { Lines(Lines), File(String), Centre, + /// A note's box in the diff, as last drawn. + Over(Rect), } impl Screen { @@ -64,15 +68,24 @@ impl Screen { let (x, width) = match &anchor { Anchor::Lines(lines) => columns(pane, middle, lines.side), Anchor::File(_) | Anchor::Centre => (pane.x, pane.width.min(MAX_WIDTH)), + Anchor::Over(rect) => (rect.x, rect.width), }; let wrap = usize::from(width.saturating_sub(compose::CHROME)); let wanted = compose::height(&self.compose, wrap).min(pane.height); + if let Anchor::Over(rect) = anchor { + // From the box's top down, else as low as it fits. + let y = rect.y.min(pane.bottom().saturating_sub(wanted.max(ROOM.min(pane.height)))); + return Rect { x, y, width, height: wanted.min(pane.bottom() - y) }; + } let diff = self.active_diff(); + let boxes = self.notes_inline() && self.whole.is_none(); let rows = match &anchor { Anchor::Lines(lines) => diff.and_then(|diff| diff.rows_showing(lines)).map(|(first, last)| { let at_first = diff.and_then(|diff| diff.line_on(lines.side).ok().flatten()); let top = lines.first < lines.last && at_first.is_some_and(|(path, line)| path == lines.path && line == lines.first); + // Below the notes' boxes under the lines, never over them. + let last = if boxes { diff.map_or(last, |diff| diff.under_boxes(last)) } else { last }; (first, last, top) }), Anchor::File(path) => match diff.and_then(|diff| diff.heading_row(path)) { @@ -80,7 +93,7 @@ impl Screen { // No heading on screen: at the top of the pane. None => return Rect { x, y: pane.y, width, height: wanted }, }, - Anchor::Centre => None, + Anchor::Centre | Anchor::Over(_) => None, }; let Some((first, last, top)) = rows else { let x = pane.x + (pane.width - width) / 2; @@ -103,6 +116,7 @@ impl Screen { } Draft::File(path) => Anchor::File(path.clone()), Draft::Change => Anchor::Centre, + Draft::Edit(id) if let Some(rect) = self.drawn_box(id) => Anchor::Over(rect), Draft::Edit(id) => match self.store.annotations().iter().find(|note| note.id == *id) { Some(note) if note.scope == NoteScope::File => Anchor::File(note.file_path.clone()), Some(note) if note.scope == NoteScope::Line => Anchor::Lines(Lines { diff --git a/crates/plannotator-tui/src/review/diff.rs b/crates/plannotator-tui/src/review/diff.rs index 9f7997b4..7e9b2469 100644 --- a/crates/plannotator-tui/src/review/diff.rs +++ b/crates/plannotator-tui/src/review/diff.rs @@ -20,11 +20,13 @@ use ratatui::crossterm::event::{Event, MouseEventKind}; use ratatui::layout::Rect; use ratatui::style::Style; +mod insets; mod place; mod sections; mod settings; mod whitespace; +pub(super) use insets::{Columns, Slot}; use sections::Sections; use settings::{layout, options}; @@ -75,6 +77,9 @@ pub(super) struct Diff { terminal_background: bool, /// The whole-file view: always unified, so no layout or split ratio applies. whole: bool, + /// Nothing moved the cursor or the view since the files were opened: the notes' boxes, + /// laid out for the first time, start from the top (`insets`). + at_start: bool, } impl std::fmt::Debug for Diff { @@ -123,6 +128,7 @@ impl Diff { notice: None, drawn: false, terminal_background: false, + at_start: true, } } @@ -156,6 +162,7 @@ impl Diff { self.paths.clear(); self.generation = next_generation(); self.drawn = false; + self.at_start = true; Ok(()) } @@ -245,6 +252,7 @@ impl Diff { } pub(super) fn run(&mut self, command: Command) -> Result<()> { + self.at_start = false; let growing = self.growing(); let effect = self.engine.execute(command)?; let step = match command { @@ -269,6 +277,7 @@ impl Diff { }; let growing = self.growing(); let acted = self.engine.handle_event(event, true)? != InputEffect::Ignored; + self.at_start &= !acted; if acted { self.keep_in_hunk(growing, step)?; } @@ -351,6 +360,7 @@ impl Diff { first: lines.first, last: lines.last, }; + self.at_start = false; self.engine.select_range(range)?; Ok(()) } @@ -389,6 +399,7 @@ impl Diff { /// Put the cursor on `lines.first`. An error means the diff does not show that line. pub(super) fn reveal(&mut self, path: &str, side: Side, line: u32) -> Result<()> { let file = self.index(path).with_context(|| format!("{path} is not in the diff"))?; + self.at_start = false; self.engine.reveal(file, engine_side(side), line)?; Ok(()) } diff --git a/crates/plannotator-tui/src/review/diff/insets.rs b/crates/plannotator-tui/src/review/diff/insets.rs new file mode 100644 index 00000000..b6d92ac8 --- /dev/null +++ b/crates/plannotator-tui/src/review/diff/insets.rs @@ -0,0 +1,131 @@ +//! Rows the viewer keeps free between the diff's rows, for the notes drawn there +//! (`review::inline`): diffs-rs's insets, by this app's paths. The viewer keeps the reader's +//! place whenever they change (the cursor's line stays on its screen row), so setting them +//! is safe at any time. + +use anyhow::Result; +use diffs_rs::engine::{self, DiffRowKind, Inset, InsetAnchor}; +use plannotator_tui_review::Side; + +use super::{Diff, engine_side}; + +pub(in crate::review) use diffs_rs::engine::InsetArea as BoxArea; + +/// Rows kept for one box: under `line` of `side`, or under the file's heading (`None`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub(in crate::review) struct Slot<'a> { + pub(in crate::review) id: u64, + pub(in crate::review) path: &'a str, + pub(in crate::review) line: Option<(Side, u32)>, + pub(in crate::review) height: u16, +} + +/// The columns a box in one file can draw in, as the last frame laid them out. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(in crate::review) struct Columns { + /// The code column of each side; unified, the one code column twice. + pub(in crate::review) old: u16, + pub(in crate::review) new: u16, + /// From the old side's code to the diff's right edge; unified, the code column. + pub(in crate::review) whole: u16, + /// Split, each side's pane, its gutter included; `None` unified. + pub(in crate::review) panes: Option<(u16, u16)>, +} + +impl Diff { + /// Keep rows for `slots`, in their order where several share a row. Slots in files the + /// viewer does not have (not arrived, filtered out) keep none until the next call. True + /// when the set changed; the same set again changes nothing. + pub(in crate::review) fn set_boxes(&mut self, slots: &[Slot<'_>]) -> Result { + let review = self.engine.review_id(); + let index: std::collections::HashMap<&str, usize> = + self.paths.iter().enumerate().map(|(i, path)| (path.as_str(), i)).collect(); + let insets: Vec = slots + .iter() + .filter_map(|slot| { + let file = *index.get(slot.path)?; + let anchor = match slot.line { + Some((side, line)) if line >= 1 => InsetAnchor::Line { side: engine_side(side), line }, + Some(_) => return None, + None => InsetAnchor::FileHeading, + }; + Some(Inset { review, id: slot.id, file, anchor, height: slot.height }) + }) + .collect(); + if self.engine.insets() == insets.as_slice() { + return Ok(false); + } + let first = self.engine.insets().is_empty(); + self.engine.set_insets(&insets)?; + // The view as the diff opened, its first heading at the top and the cursor on its + // first line, now with the boxes: the viewer keeps the cursor's row when boxes come, + // so a box under the first heading would start above the top. + let in_first = self.engine.cursor_row().is_some_and(|row| row.file == 0); + if first && self.at_start && in_first && !insets.is_empty() { + self.show_heading(0)?; + self.engine.execute(engine::Command::FirstSource)?; + } + Ok(true) + } + + /// The boxes on screen in the last frame, top to bottom. + pub(in crate::review) fn box_areas(&self) -> &[BoxArea] { + self.engine.inset_areas() + } + + /// The boxes set whose lines the diff does not show now (a hunk drawn as its heading + /// because whitespace is hidden, say): they keep no rows. + pub(in crate::review) fn hidden_boxes(&self) -> Vec { + self.engine.hidden_insets() + } + + /// The columns a box in the file at `path` has, as the last frame laid them out. `None` + /// before the first frame and for a file the viewer does not have. + pub(in crate::review) fn box_columns(&self, path: &str) -> Option { + let file = self.index(path)?; + let old = self.engine.inset_width(file, engine::Side::Old)?; + let new = self.engine.inset_width(file, engine::Side::New)?; + // Split, the viewer's box runs from the old side's code over the line between the + // sides to the right edge: the old code column, then all of the new side's pane. + let Some(line) = self.split_line() else { + return Some(Columns { old, new, whole: new, panes: None }); + }; + let (left, right) = (line.saturating_sub(self.area.x), self.area.right().saturating_sub(line + 1)); + Some(Columns { old, new, whole: old + 1 + right, panes: Some((left, right)) }) + } + + /// The box the cursor is on, by id. + pub(in crate::review) fn cursor_box(&self) -> Option { + match self.engine.cursor_row()?.kind { + DiffRowKind::Inset { id } => Some(id), + _ => None, + } + } + + /// The box drawn at screen cell (`column`, `row`) in the last frame, by id. + pub(in crate::review) fn box_at(&self, column: u16, row: u16) -> Option { + match self.engine.row_at(column, row)?.kind { + DiffRowKind::Inset { id } => Some(id), + _ => None, + } + } + + /// The last screen row of the boxes right under screen row `row`, or `row` itself when + /// none hangs there. + pub(in crate::review) fn under_boxes(&self, row: u16) -> u16 { + let column = self.area.right().saturating_sub(2); + let mut last = row; + while last + 1 < self.area.bottom() && self.box_at(column, last + 1).is_some() { + last += 1; + } + last + } +} + +#[cfg(test)] +impl Diff { + /// The viewer's boxes as set, for tests. + pub(in crate::review) fn boxes_set(&self) -> Vec { + self.engine.insets().to_vec() + } +} diff --git a/crates/plannotator-tui/src/review/diff/place.rs b/crates/plannotator-tui/src/review/diff/place.rs index 357dc7a6..05a6ca8b 100644 --- a/crates/plannotator-tui/src/review/diff/place.rs +++ b/crates/plannotator-tui/src/review/diff/place.rs @@ -85,6 +85,7 @@ impl Diff { let kind = MouseEventKind::Down(MouseButton::Left); Event::Mouse(MouseEvent { kind, column, row, modifiers: KeyModifiers::NONE }) }; + self.at_start = false; self.engine.execute(Command::ClearSelection)?; self.engine.handle_event(click(from), true)?; self.engine.execute(Command::SelectLines)?; @@ -128,6 +129,7 @@ impl Diff { if index >= self.paths.len() { return Ok(()); } + self.at_start = false; for _ in 0..=self.paths.len() { let Some(row) = self.cursor_row() else { return Ok(()) }; let command = match row.file.cmp(&index) { diff --git a/crates/plannotator-tui/src/review/drafts.rs b/crates/plannotator-tui/src/review/drafts.rs index 69891ca2..1993a117 100644 --- a/crates/plannotator-tui/src/review/drafts.rs +++ b/crates/plannotator-tui/src/review/drafts.rs @@ -1,5 +1,5 @@ -//! Making and changing notes: what `c`, `s`, `C`, `M` and the rail's `e` and `x` do, and -//! saving what the comment box holds. +//! Making and changing notes: what `c`, `s`, `C`, `M` and the rail's `e` and `x` do (and +//! Enter and Delete on a note's box in the diff), and saving what the comment box holds. use anyhow::Result; use plannotator_tui_review::{CodeAnnotation, NoteType, Side}; @@ -66,14 +66,22 @@ impl Screen { /// `e` in the rail: the comment box with the note's comment, or its code for a /// suggestion. pub(super) fn start_edit(&mut self) { - let Some(note) = self.selected_note() else { return }; + if let Some(id) = self.selected_note().map(|note| note.id.clone()) { + self.edit_note(&id); + } + } + + /// The comment box with note `id`'s comment, or its code for a suggestion; the rail + /// selects the note. + pub(super) fn edit_note(&mut self, id: &str) { + let Some(note) = self.store.annotations().iter().find(|note| note.id == id) else { return }; let text = match note.kind { NoteType::Suggestion => note.suggested_code.clone(), NoteType::Comment | NoteType::Concern => note.text.clone(), }; - let id = note.id.clone(); self.compose = Compose::with_text(&text.unwrap_or_default()); - self.mode = Mode::Compose(Draft::Edit(id)); + self.mode = Mode::Compose(Draft::Edit(id.to_owned())); + self.select_note(id); } /// Save what the comment box holds. An empty comment saves nothing. @@ -137,16 +145,21 @@ impl Screen { // The selection became the note; the next one starts fresh. let _ = self.diff.clear_selection(); self.after_note_change(); - if let Some(position) = self.rail_order().iter().position(|&i| self.note_id(i) == Some(id.as_str())) { - self.rail_cursor = position; - } + self.select_note(&id); Ok(()) } /// `x` in the rail. pub(super) fn remove_selected(&mut self) -> Result<()> { - let Some(id) = self.selected_note().map(|n| n.id.clone()) else { return Ok(()) }; - if self.store.remove(&id)? { + match self.selected_note().map(|n| n.id.clone()) { + Some(id) => self.remove_note(&id), + None => Ok(()), + } + } + + /// Remove note `id`, at once, as the rail's `x` does. + pub(super) fn remove_note(&mut self, id: &str) -> Result<()> { + if self.store.remove(id)? { self.status = Some("note removed".into()); } self.after_note_change(); diff --git a/crates/plannotator-tui/src/review/draw.rs b/crates/plannotator-tui/src/review/draw.rs index 0a307b40..10462b14 100644 --- a/crates/plannotator-tui/src/review/draw.rs +++ b/crates/plannotator-tui/src/review/draw.rs @@ -88,7 +88,16 @@ impl Screen { let cursor_selected = self.cursor_selected(); match &mut self.whole { Some(whole) => whole.draw(frame, diff)?, - None => self.diff.draw(frame, diff)?, + None => { + // The notes' boxes as the last frame's columns size them, then again for this + // frame's when those changed (a resize, a pane opened or closed, the line + // between the sides moved), drawn again before anything shows. + self.sync_boxes(); + self.diff.draw(frame, diff)?; + if self.sync_boxes() { + self.diff.draw(frame, diff)?; + } + } } let (middle, code) = match self.active_diff_mut() { Some(shown) => { @@ -99,6 +108,7 @@ impl Screen { }; let code = |y: u16| code.get(usize::from(y - diff.y)).copied().unwrap_or(true); let selected = super::mouse::tint_selection(frame.buffer_mut(), diff, middle, cursor_selected, code); + self.draw_boxes(frame); if files.width > 0 { let listing = self.listing(); self.draw_files(frame, files, &listing); diff --git a/crates/plannotator-tui/src/review/footer.rs b/crates/plannotator-tui/src/review/footer.rs index e20c3fed..e0338570 100644 --- a/crates/plannotator-tui/src/review/footer.rs +++ b/crates/plannotator-tui/src/review/footer.rs @@ -134,9 +134,28 @@ impl Screen { }; parts.push(format!("selected {span} {}", lines.side.as_str())); } + // Notes drawn in the diff: the ones that are not, and where they are. + let away = self.notes_not_inline(); + if away > 0 { + let what = if away == 1 { + "1 note not shown inline".to_owned() + } else { + format!("{away} notes not shown inline") + }; + let key = self.keys.hint(Action::ToggleNotes); + parts.push(if key.is_empty() || self.rail_shown() { + what + } else { + format!("{what} \u{b7} {key}") + }); + } // Closed by the person, or away since the review opened without notes: the notes' // marks are in the gutter, and the footer says where the notes themselves are. - if self.notes_rail.closed() || (!self.rail_shown() && !notes.is_empty()) { + if self.settings.now.notes == crate::config::review::Notes::Inline { + if self.rail_shown() && width < RAIL_MIN_TOTAL_WIDTH { + parts.push("rail hidden: widen to \u{2265}80 cols".into()); + } + } else if self.notes_rail.closed() || (!self.rail_shown() && !notes.is_empty()) { parts.push(match self.keys.hint(Action::ToggleNotes) { key if key.is_empty() => "notes hidden".to_owned(), key => format!("notes hidden: {key} shows them"), @@ -217,6 +236,26 @@ impl Screen { return Vec::new(); } let hints: Vec> = match self.focus { + Focus::Diff if self.cursor_note().is_some() => { + let besides = |action| self.keys.hint_besides(action, crate::keys::DIFF); + let edit: Vec = [self.keys.hint(Action::Confirm), besides(Action::Edit)] + .into_iter() + .filter(|k| !k.is_empty()) + .collect(); + let remove = besides(Action::Remove); + [ + (!edit.is_empty()).then(|| format!("{} edit", edit.join("/"))), + (!remove.is_empty()).then(|| format!("{remove} remove")), + pair(Action::Down, Action::Up, "move"), + key(Action::ToggleViewed, "viewed"), + (!self.store.annotations().is_empty()) + .then(|| key(Action::CycleFocus, "notes")) + .flatten(), + ] + .into_iter() + .chain(tail) + .collect() + } Focus::Diff if self.diff.selection().is_some() => vec![ self.diff.selecting().then(|| key(Action::Visual, "end selection")).flatten(), key(Action::Comment, "comment"), diff --git a/crates/plannotator-tui/src/review/inline.rs b/crates/plannotator-tui/src/review/inline.rs new file mode 100644 index 00000000..3b84bb80 --- /dev/null +++ b/crates/plannotator-tui/src/review/inline.rs @@ -0,0 +1,239 @@ +//! Notes drawn in the diff (`[review] notes = "inline"` or `"both"`): a box per note under +//! the last line it is about, or under its file's heading for a note on the whole file, as a +//! pull request's comments sit in its diff. The viewer keeps rows free for each box +//! (`diff::insets`) and keeps the reader's place when they come, go or change height; this +//! module decides the boxes, sizes them to the width they draw in, and draws them. +//! +//! - Several notes on one line stack in the order they were made. +//! - In a split diff a box sits over its side's half, or across both when that half is too +//! narrow for the comment box (`compose_at`'s rule). +//! - Notes on the whole change, notes whose lines the diff does not show (outdated, made in +//! the whole file, in a hunk hidden with whitespace changes, in a file the filter hides) get +//! no box; the footer counts them, and the panel lists them. +//! - The cursor stops on a box once. There Enter (or the panel's edit key) opens the note in +//! the comment box, over its box, and the panel's remove key removes it, unless the diff +//! gives that key to something else (`x` marks the file viewed there). +//! - `inline` starts with the panel away whatever notes there are; `z` opens it for the +//! session. `both` keeps the panel's own rule (`notes_rail`). +//! - `panel`, the default, sets no rows at all: the diff draws as it always has. +//! +//! A box is laid out once per note revision and width ([`card::Card`]), and only the boxes +//! on screen are drawn. + +mod card; +mod paint; + +use std::collections::HashMap; + +use anyhow::Result; +use plannotator_tui_review::{CodeAnnotation, NoteScope, Side}; +use ratatui::crossterm::event::KeyEvent; + +use super::compose_at::{MAX_WIDTH, MIN_SIDE_WIDTH}; +use super::diff::{Columns, Slot}; +use super::{Screen, notes}; +use crate::config::review::Notes; +use crate::keys::{self, Action}; + +/// Narrower than this a box would show next to nothing: the note gets none. +const MIN_WIDTH: u16 = 12; + +/// The boxes' state for one review. +#[derive(Debug, Default)] +pub(super) struct Inline { + /// Each note's box id, by note id. Ids are never reused within a review. + ids: HashMap, + notes: HashMap, + /// Each box's layout, by id, for the width it last drew at. + cards: HashMap, + /// Notes that got no box at the last count: on the whole change, not in the diff, or + /// with no room. + skipped: usize, + /// While notes show inline only, whether the panel was opened by hand. + pub(super) rail: bool, + /// The Notes setting the screen last followed. + pub(super) view: Notes, +} + +impl Inline { + pub(super) fn new(view: Notes) -> Self { + Self { view, ..Self::default() } + } + + fn id(&mut self, note: &str) -> u64 { + if let Some(&id) = self.ids.get(note) { + return id; + } + let id = self.ids.len() as u64 + 1; + self.ids.insert(note.to_owned(), id); + self.notes.insert(id, note.to_owned()); + id + } + + /// The card for `note` at `width`, laid out again only when either changed. + fn card(&mut self, id: u64, note: &CodeAnnotation, width: u16, tab: u8) -> &card::Card { + let card = self.cards.entry(id).or_insert_with(|| card::Card::of(note, width, tab)); + if !card.is_for(note, width, tab) { + *card = card::Card::of(note, width, tab); + } + card + } +} + +/// Which of a box's columns it draws in. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Part { + Old, + New, + /// Across the diff: a file's note, or a side too narrow for the box. + Whole, +} + +/// Where `note`'s box goes: under its last line on its side, or under its file's heading +/// (`Some(None)`). `None` for a note with no box. +fn place(note: &CodeAnnotation) -> Option> { + match note.scope { + NoteScope::Line if notes::in_diff(note) => Some(Some((note.side, note.line_end))), + NoteScope::File if !notes::is_outdated(note) => Some(None), + _ => None, + } +} + +/// The columns `note`'s box draws in, and its width there. +fn part(note: &CodeAnnotation, columns: Columns) -> (Part, u16) { + let part = match (note.scope, columns.panes) { + (NoteScope::Line, None) => Part::New, + (NoteScope::Line, Some((old, _))) if note.side == Side::Old && old >= MIN_SIDE_WIDTH => Part::Old, + (NoteScope::Line, Some((_, new))) if note.side == Side::New && new >= MIN_SIDE_WIDTH => Part::New, + _ => Part::Whole, + }; + let width = match part { + Part::Old => columns.old, + Part::New => columns.new, + Part::Whole => columns.whole, + }; + (part, width.min(MAX_WIDTH)) +} + +impl Screen { + /// Whether notes show in the diff. + pub(super) fn notes_inline(&self) -> bool { + self.settings.now.notes != Notes::Panel + } + + /// Give the viewer the boxes the notes want now, sized for the columns of the last frame. + /// True when that changed the rows it keeps; the same boxes again change nothing, so this + /// is cheap to call on every frame. + pub(super) fn sync_boxes(&mut self) -> bool { + let notes = self.store.annotations(); + let mut slots = Vec::new(); + let mut skipped = 0; + if self.settings.now.notes != Notes::Panel { + let tab = self.settings.now.tab_width.get(); + let mut columns: HashMap<&str, Option> = HashMap::new(); + let mut order: Vec = (0..notes.len()).collect(); + order.sort_by_key(|&i| (notes.get(i).map_or(0, |note| note.created_at), i)); + for note in order.into_iter().filter_map(|i| notes.get(i)) { + let path = note.file_path.as_str(); + let shown = columns.entry(path).or_insert_with(|| self.diff.box_columns(path)); + let (Some(line), Some(columns)) = (place(note), *shown) else { + skipped += 1; + continue; + }; + let (_, width) = part(note, columns); + if width < MIN_WIDTH { + skipped += 1; + continue; + } + let id = self.inline.id(¬e.id); + let height = self.inline.card(id, note, width, tab).height(); + slots.push(Slot { id, path, line, height }); + } + } + self.inline.skipped = skipped; + match self.diff.set_boxes(&slots) { + Ok(changed) => changed, + Err(error) => { + self.status = Some(format!("could not show the notes in the diff: {error:#}")); + false + } + } + } + + /// How many notes have no box in the diff now, for the footer. + pub(super) fn notes_not_inline(&self) -> usize { + if !self.notes_inline() { + return 0; + } + self.inline.skipped + self.diff.hidden_boxes().len() + } + + /// The note whose box the cursor is on, in the diff (not the whole file). + pub(super) fn cursor_note(&self) -> Option<&CodeAnnotation> { + if self.whole.is_some() || !self.notes_inline() { + return None; + } + let id = self.inline.notes.get(&self.diff.cursor_box()?)?; + self.store.annotations().iter().find(|note| note.id == *id) + } + + /// A key on a box: Enter or the panel's edit key edits its note, the panel's remove key + /// removes it. A key the diff gives an action of its own keeps it. True when the key was + /// the box's. + pub(super) fn box_key(&mut self, key: &KeyEvent) -> Result { + let Some(id) = self.cursor_note().map(|note| note.id.clone()) else { return Ok(false) }; + let diff = self.keys.action(key, keys::DIFF); + let free = |action| diff.is_none() && self.keys.is(action, key); + if diff == Some(Action::Confirm) || free(Action::Edit) { + self.edit_note(&id); + } else if free(Action::Remove) { + self.remove_note(&id)?; + } else { + return Ok(false); + } + Ok(true) + } + + /// Where note `id`'s box was drawn in the last frame, when it was. + pub(super) fn drawn_box(&self, id: &str) -> Option { + let id = self.inline.ids.get(id)?; + self.geometry.boxes.iter().find(|(_, drawn)| drawn == id).map(|(rect, _)| *rect) + } + + /// After a click: a box the cursor landed on selects its note in the panel. + pub(super) fn follow_box(&mut self) { + let Some(id) = self.cursor_note().map(|note| note.id.clone()) else { return }; + self.select_note(&id); + } + + /// The panel's cursor onto the note `id`. + pub(super) fn select_note(&mut self, id: &str) { + if let Some(position) = self.rail_order().iter().position(|&i| self.note_id(i) == Some(id)) { + self.rail_cursor = position; + } + } + + /// The Notes setting changed: the panel follows its rule for the new one, and the boxes + /// come or go at once. + pub(super) fn notes_view_changed(&mut self) { + self.inline.rail = false; + if !self.rail_shown() && self.focus == super::Focus::Notes { + self.focus = super::Focus::Diff; + } + self.sync_boxes(); + } +} + +#[cfg(test)] +impl Screen { + /// The note box `id` shows, for tests. + pub(super) fn note_of_box(&self, id: u64) -> Option<&CodeAnnotation> { + let note = self.inline.notes.get(&id)?; + self.store.annotations().iter().find(|n| n.id == *note) + } + + /// What a box's title says for `note`, for tests. + pub(super) fn box_label(note: &CodeAnnotation) -> String { + card::label(note) + } +} diff --git a/crates/plannotator-tui/src/review/inline/card.rs b/crates/plannotator-tui/src/review/inline/card.rs new file mode 100644 index 00000000..e4eba521 --- /dev/null +++ b/crates/plannotator-tui/src/review/inline/card.rs @@ -0,0 +1,168 @@ +//! What a note's box in the diff says, wrapped to the box's width: a title (`comment · L42`, +//! the author when the note is not the person's own), then the comment, and for a suggestion +//! the lines it replaces and the code it suggests as `-` and `+` lines. At most +//! [`BODY_LINES`] lines show; the box says when there is more, which opening the note shows. + +use std::hash::{Hash as _, Hasher as _}; + +use plannotator_tui_review::{CodeAnnotation, NoteScope, NoteType, Side}; +use ratatui::style::Style; +use ratatui::text::{Line, Span}; + +use crate::theme::palette; +use crate::wrap::{split_line, wrap_line}; + +/// The most lines of text a box shows. +pub(super) const BODY_LINES: usize = 6; + +/// The columns a box keeps beside its text: a border and a space on each side. +pub(super) const CHROME: u16 = 4; + +/// A note's box, laid out for one width. +#[derive(Debug, Clone)] +pub(super) struct Card { + /// What it was laid out from: the note's revision and the box's width. + made_for: (u64, u16), + /// `comment · L42`. + pub(super) label: String, + /// Who wrote it, when the record names someone. + pub(super) author: Option, + pub(super) body: Vec>, + /// Lines that did not fit. + pub(super) more: bool, +} + +impl Card { + /// `note` in a box `width` columns wide, its tabs `tab` columns. + pub(super) fn of(note: &CodeAnnotation, width: u16, tab: u8) -> Self { + let text_width = usize::from(width.saturating_sub(CHROME)).max(1); + let tabs = " ".repeat(usize::from(tab)); + let plain = |text: &str| text.replace('\t', &tabs); + let mut body: Vec> = Vec::new(); + if let Some(text) = note.text.as_deref().map(str::trim_end).filter(|t| !t.is_empty()) { + for line in text.split('\n') { + let line = Line::from(plain(line.trim_end_matches('\r'))); + body.extend(wrap_line(&line, &[], text_width).into_iter().map(|row| row.line)); + } + } + if note.kind == NoteType::Suggestion { + let mut rows = Vec::new(); + let mut code = |code: Option<&str>, sign: &'static str, style: Style| { + for line in code.into_iter().flat_map(|code| code.split('\n')) { + let line = Line::from(Span::styled(plain(line.trim_end_matches('\r')), style)); + split_line(&mut rows, &Span::styled(sign, style), &line, &[], text_width); + } + }; + code(note.original_code.as_deref(), "- ", Style::new().fg(palette().delete)); + code(note.suggested_code.as_deref(), "+ ", Style::new().fg(palette().looks_good)); + body.extend(rows.into_iter().map(|row| row.line)); + } + let more = body.len() > BODY_LINES; + body.truncate(BODY_LINES); + if body.is_empty() { + body.push(Line::default()); + } + let author = note.author_name.as_deref().filter(|name| !name.is_empty()).map(str::to_owned); + Self { made_for: (revision(note, tab), width), label: label(note), author, body, more } + } + + /// Whether this is `note`'s card at `width`, as [`Self::of`] would make it now. + pub(super) fn is_for(&self, note: &CodeAnnotation, width: u16, tab: u8) -> bool { + self.made_for == (revision(note, tab), width) + } + + /// The rows the box takes: its text and two borders. + pub(super) fn height(&self) -> u16 { + self.body.len() as u16 + 2 + } +} + +/// `comment · L42`, `comment · L40–45`, `suggestion · L42`, `comment · L7 old` for lines of +/// the old file, `file comment` for a note on the whole file. +pub(super) fn label(note: &CodeAnnotation) -> String { + let kind = match note.kind { + NoteType::Suggestion => "suggestion", + NoteType::Comment | NoteType::Concern => "comment", + }; + if note.scope != NoteScope::Line { + return format!("file {kind}"); + } + let lines = if note.line_start == note.line_end { + format!("L{}", note.line_start) + } else { + format!("L{}\u{2013}{}", note.line_start, note.line_end) + }; + let old = if note.side == Side::Old { " old" } else { "" }; + format!("{kind} \u{b7} {lines}{old}") +} + +/// A number that changes whenever what the box shows of `note` does. +fn revision(note: &CodeAnnotation, tab: u8) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + (¬e.text, ¬e.suggested_code, ¬e.original_code, ¬e.author_name).hash(&mut hasher); + (note.kind == NoteType::Suggestion, note.scope == NoteScope::Line, note.side == Side::Old) + .hash(&mut hasher); + (note.line_start, note.line_end, tab).hash(&mut hasher); + hasher.finish() +} + +#[cfg(test)] +#[allow(clippy::expect_used, reason = "tests assert by panicking")] +mod tests { + use super::*; + + /// A note of `kind` on `scope`, lines `start..=end` of `side`, with the fields in `extra`. + fn note(kind: &str, scope: &str, side: &str, (start, end): (u32, u32), extra: &str) -> CodeAnnotation { + let json = format!( + r#"{{"id":"n","type":"{kind}","scope":"{scope}","filePath":"a.rs","side":"{side}","lineStart":{start},"lineEnd":{end},"createdAt":1{extra}}}"# + ); + serde_json::from_str(&json).expect("note") + } + + fn text(card: &Card) -> Vec { + card.body.iter().map(|line| line.spans.iter().map(|s| s.content.as_ref()).collect()).collect() + } + + #[test] + fn labels_name_the_kind_the_lines_and_an_old_side() { + assert_eq!(label(¬e("comment", "line", "new", (42, 42), "")), "comment \u{b7} L42"); + assert_eq!(label(¬e("comment", "line", "new", (40, 45), "")), "comment \u{b7} L40\u{2013}45"); + assert_eq!(label(¬e("comment", "line", "old", (7, 7), "")), "comment \u{b7} L7 old"); + assert_eq!(label(¬e("suggestion", "line", "new", (42, 42), "")), "suggestion \u{b7} L42"); + assert_eq!(label(¬e("comment", "file", "new", (1, 1), "")), "file comment"); + } + + #[test] + fn text_wraps_to_the_box_and_stops_after_six_lines() { + let words = "word ".repeat(40); + let long = note("comment", "line", "new", (1, 1), &format!(r#","text":"{words}""#)); + let card = Card::of(&long, 24, 4); + assert_eq!(card.body.len(), BODY_LINES); + assert!(card.more); + assert!(text(&card).iter().all(|line| line.chars().count() <= 20), "{:?}", text(&card)); + assert_eq!(card.height(), 8); + let short = note("comment", "line", "new", (1, 1), r#","text":"one\ntwo""#); + let card = Card::of(&short, 24, 4); + assert_eq!((text(&card), card.more), (vec!["one".to_owned(), "two".to_owned()], false)); + } + + #[test] + fn a_suggestion_shows_its_comment_then_the_old_and_the_new_code() { + let code = r#","text":"simpler","originalCode":"\tlet a = b;","suggestedCode":"\tlet a = c;""#; + let suggestion = note("suggestion", "line", "new", (3, 3), code); + let card = Card::of(&suggestion, 40, 2); + assert_eq!(text(&card), ["simpler", "- let a = b;", "+ let a = c;"]); + let red = card.body.get(1).and_then(|line| line.spans.first()).map(|span| span.style.fg); + assert_eq!(red, Some(Some(palette().delete))); + } + + #[test] + fn a_card_is_made_again_when_its_note_or_its_width_changes() { + let mut one = note("comment", "line", "new", (1, 1), r#","text":"a""#); + let card = Card::of(&one, 30, 4); + assert!(card.is_for(&one, 30, 4)); + assert!(!card.is_for(&one, 31, 4)); + one.text = Some("b".into()); + assert!(!card.is_for(&one, 30, 4)); + } +} diff --git a/crates/plannotator-tui/src/review/inline/paint.rs b/crates/plannotator-tui/src/review/inline/paint.rs new file mode 100644 index 00000000..d8baa00a --- /dev/null +++ b/crates/plannotator-tui/src/review/inline/paint.rs @@ -0,0 +1,99 @@ +//! Drawing the boxes the last frame kept rows for. Each is drawn whole off screen and its rows +//! on screen copied in, so a box cut by the pane's top or bottom loses its border there and +//! nothing ever lands outside its rows. The cells keep the diff's background. + +use ratatui::Frame; +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; +use ratatui::style::{Color, Style}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, BorderType, Borders, Paragraph, Widget as _}; + +use super::card::Card; +use super::{Part, part}; +use crate::keys::Action; +use crate::review::Screen; +use crate::theme::palette; + +/// How a box looks: its note sent or not, the cursor on it or not. +#[derive(Debug, Clone, Copy)] +struct Look { + sent: bool, + cursor: bool, +} + +impl Screen { + /// Draw the boxes on screen in the last frame of the diff, and note where for the mouse + /// and the comment box. + pub(in crate::review) fn draw_boxes(&mut self, frame: &mut Frame) { + if self.whole.is_some() || !self.notes_inline() { + return; + } + let tab = self.settings.now.tab_width.get(); + let more = self.keys.labelled(Action::Confirm, "for more").unwrap_or_else(|| "more".to_owned()); + let areas = self.diff.box_areas().to_vec(); + let notes = self.store.annotations(); + for area in areas { + let Some(note) = + self.inline.notes.get(&area.id).and_then(|id| notes.iter().find(|n| n.id == *id)) + else { + continue; + }; + let Some(columns) = self.diff.box_columns(¬e.file_path) else { continue }; + let (part, width) = part(note, columns); + let rect = match part { + Part::Old => area.left, + Part::New => area.right, + Part::Whole => area.area, + }; + let rect = Rect { width: width.min(rect.width), ..rect }; + let look = Look { sent: !self.store.is_pending(note), cursor: area.cursor }; + let card = self.inline.card(area.id, note, width, tab); + paint(frame.buffer_mut(), rect, area.clipped_top, card, look, &more); + self.geometry.boxes.push((rect, area.id)); + } + } +} + +/// The box for `card`, its rows from `clipped_top` on, into `rect` of `buf`. +fn paint(buf: &mut Buffer, rect: Rect, clipped_top: u16, card: &Card, look: Look, more: &str) { + let whole = Rect::new(0, 0, rect.width, card.height()); + let mut scratch = Buffer::empty(whole); + let colour = if look.sent { Color::DarkGray } else { palette().comment }; + let border = if look.cursor { Style::new().fg(palette().accent).bold() } else { Style::new().fg(colour) }; + let mut title = vec![Span::raw(" "), Span::styled(card.label.clone(), Style::new().fg(colour).bold())]; + if let Some(author) = &card.author { + title.push(Span::styled(format!(" \u{b7} {author}"), Style::new().fg(colour))); + } + if look.sent { + title.push(Span::styled(" \u{b7} sent", Style::new().fg(Color::DarkGray))); + } + title.push(Span::raw(" ")); + let mut block = Block::new() + .borders(Borders::ALL) + .border_type(BorderType::Rounded) + .border_style(border) + .title(Line::from(title)); + if card.more { + block = block.title_bottom(Span::styled(format!(" \u{2026} {more} "), Style::new().fg(colour))); + } + let inner = block.inner(whole); + block.render(whole, &mut scratch); + let text = Rect { x: inner.x + 1, width: inner.width.saturating_sub(2), ..inner }; + let style = if look.sent { Style::new().dim() } else { Style::new() }; + Paragraph::new(card.body.clone()).style(style).render(text, &mut scratch); + for dy in 0..rect.height { + let from = clipped_top + dy; + for dx in 0..rect.width { + let (Some(cell), Some(to)) = (scratch.cell((dx, from)), buf.cell_mut((rect.x + dx, rect.y + dy))) + else { + continue; + }; + let bg = to.bg; + *to = cell.clone(); + if cell.bg == Color::Reset { + to.bg = bg; + } + } + } +} diff --git a/crates/plannotator-tui/src/review/input.rs b/crates/plannotator-tui/src/review/input.rs index 5cf6793e..eb588dd2 100644 --- a/crates/plannotator-tui/src/review/input.rs +++ b/crates/plannotator-tui/src/review/input.rs @@ -268,6 +268,9 @@ impl Screen { } fn diff_key(&mut self, key: KeyEvent) -> Result<()> { + if self.box_key(&key)? { + return Ok(()); + } match self.keys.action(&key, keys::DIFF) { Some(action) => self.diff_action(action), None => Ok(()), @@ -536,7 +539,9 @@ impl Screen { } if self.geometry.diff.contains(at) { if click { - return self.press(mouse); + self.press(mouse)?; + self.follow_box(); + return Ok(()); } if let Some(whole) = &mut self.whole { whole.handle_event(Event::Mouse(mouse))?; diff --git a/crates/plannotator-tui/src/review/mod.rs b/crates/plannotator-tui/src/review/mod.rs index d5685138..06dc4460 100644 --- a/crates/plannotator-tui/src/review/mod.rs +++ b/crates/plannotator-tui/src/review/mod.rs @@ -15,7 +15,7 @@ //! and `hc review`, and the pane they open. //! - [`input`]: keys and the mouse; [`mouse`]: clicks and drags in the diff. [`draw`], //! [`header`], [`footer`], [`rail`] and [`overlays`]: the frame; [`compose_at`]: where the -//! comment box opens. [`divider`]: dragging the lines between the panes and between a split +//! comment box opens; [`inline`]: notes drawn in the diff. [`divider`]: dragging the lines between the panes and between a split //! diff's sides. //! - [`settings`]: how the diff is drawn (`[review]`), its menu, and remembering the choices. //! - [`send`]: send, resend, finish and undo. [`pi`]: the Pi link. @@ -37,6 +37,7 @@ mod files; mod footer; mod header; pub(crate) mod herdr; +mod inline; mod input; mod jump; mod mouse; @@ -145,6 +146,8 @@ struct Geometry { /// The buttons of the toolbar beside a mouse selection, and the whole bar. toolbar: Vec<(Rect, crate::keys::Action)>, toolbar_bar: Option, + /// The notes' boxes drawn in the diff last frame, with their ids. + boxes: Vec<(Rect, u64)>, /// The columns the comment box wrapped to last frame; 0 before its first. compose_wrap: usize, /// Where the comment box drew its text, and the first of the text's rows shown there. @@ -188,6 +191,8 @@ pub(crate) struct Screen { notes_rail: NotesRail, /// The changed files on the left, and their filter. files: files::FileList, + /// The notes drawn in the diff, when the Notes setting says so. + inline: inline::Inline, compose: Compose, /// The side of its lines the open comment box took. compose_at: Option, @@ -289,6 +294,7 @@ impl Screen { rail_scroll: 0, notes_rail: NotesRail::default(), files: files::FileList::default(), + inline: inline::Inline::new(settings.now.notes), compose: Compose::default(), compose_at: None, send_state: SendState::Ready, @@ -344,20 +350,33 @@ impl Screen { } /// Whether the rail is shown, width allowing. Hidden, notes keep their gutter marks. + /// With notes inline only, it shows once opened by hand, for the session. fn rail_shown(&self) -> bool { + if self.settings.now.notes == crate::config::review::Notes::Inline { + return self.inline.rail; + } self.notes_rail.shown(!self.store.annotations().is_empty()) } /// `toggle-notes`: close the rail, or open it again, and remember which. The next frame /// gives the diff the rail's columns, or takes them back, and the viewer reflows as on a - /// resize. + /// resize. With notes inline only, it opens or closes for the session. fn toggle_notes(&mut self) { + if self.settings.now.notes == crate::config::review::Notes::Inline { + self.inline.rail = !self.inline.rail; + self.after_rail_change(Ok(())); + return; + } let remembered = self.notes_rail.toggle(!self.store.annotations().is_empty(), &self.data_dir); self.after_rail_change(remembered); } /// Moving the focus to the notes opens a closed rail. fn reveal_notes(&mut self) { + if self.settings.now.notes == crate::config::review::Notes::Inline { + self.inline.rail = true; + return; + } let remembered = self.notes_rail.reveal(!self.store.annotations().is_empty(), &self.data_dir); self.after_rail_change(remembered); } @@ -510,6 +529,7 @@ impl Screen { if let Err(err) = self.diff.set_markers(&marks) { self.status = Some(format!("could not mark notes in the diff: {err:#}")); } + self.sync_boxes(); self.sync_whole_markers(); } diff --git a/crates/plannotator-tui/src/review/overlays.rs b/crates/plannotator-tui/src/review/overlays.rs index 5d85186e..f5a4a78d 100644 --- a/crates/plannotator-tui/src/review/overlays.rs +++ b/crates/plannotator-tui/src/review/overlays.rs @@ -9,7 +9,7 @@ use unicode_width::UnicodeWidthStr as _; use super::Screen; use super::input::{MENU, MenuRow}; -use crate::keys::Action; +use crate::keys::{self, Action}; use crate::theme::palette; use crate::ui::hints; @@ -114,6 +114,18 @@ impl Screen { (key(&[Action::Comment]), "comment on the selection or line"), (key(&[Action::Suggest]), "suggest code for new lines"), (key(&[Action::FileComment]), "comment on the file"), + ( + [self.keys.hint(Action::Confirm), self.keys.hint_besides(Action::Edit, keys::DIFF)] + .into_iter() + .filter(|k| !k.is_empty()) + .collect::>() + .join(" "), + "on a note drawn in the diff (settings: Notes): edit it", + ), + ( + self.keys.hint_besides(Action::Remove, keys::DIFF), + "on a note drawn in the diff: remove it", + ), (key(&[Action::WholeFile]), "the whole file as it is now, at this line"), (key(&[Action::WholeBase]), "the whole file before the change (base)"), (key(&[Action::GoToDefinition]), "go to the definition of a word on the line"), diff --git a/crates/plannotator-tui/src/review/settings.rs b/crates/plannotator-tui/src/review/settings.rs index 4d497d80..22d1770e 100644 --- a/crates/plannotator-tui/src/review/settings.rs +++ b/crates/plannotator-tui/src/review/settings.rs @@ -21,7 +21,7 @@ mod whitespace; use std::path::PathBuf; use crate::config::review::{ - Background, DiffTheme, InlineChanges, Layout, ReviewConfig, SplitShare, TabWidth, Whitespace, + Background, DiffTheme, InlineChanges, Layout, Notes, ReviewConfig, SplitShare, TabWidth, Whitespace, }; use crate::theme::{Theme, theme}; @@ -100,6 +100,8 @@ pub(super) enum Row { Layout, SplitRatio, Wrap, + /// Where the notes show: the panel, boxes in the diff, or both. + Notes, LineNumbers, Whitespace, TabWidth, @@ -111,10 +113,11 @@ pub(super) enum Row { } /// The menu's rows, in display order. -pub(super) const ROWS: [Row; 10] = [ +pub(super) const ROWS: [Row; 11] = [ Row::Layout, Row::SplitRatio, Row::Wrap, + Row::Notes, Row::LineNumbers, Row::Whitespace, Row::TabWidth, @@ -133,6 +136,7 @@ impl Row { Self::Layout => "Layout", Self::SplitRatio => "Split ratio", Self::Wrap => "Wrap", + Self::Notes => "Notes", Self::LineNumbers => "Line numbers", Self::Whitespace => "Whitespace", Self::TabWidth => "Tab width", @@ -214,6 +218,10 @@ impl Screen { if let Err(error) = self.apply_settings() { self.status = Some(format!("{error:#}")); } + if self.inline.view != self.settings.now.notes { + self.inline.view = self.settings.now.notes; + self.notes_view_changed(); + } } /// Remember the keys changed since the state file was last read or written here, once no @@ -261,6 +269,12 @@ impl Screen { Row::SplitRatio if split => now.split_ratio.to_string(), Row::SplitRatio => format!("{} \u{b7} when split", now.split_ratio), Row::Wrap => on_off(now.wrap).to_owned(), + Row::Notes => match now.notes { + Notes::Panel => "panel", + Notes::Inline => "inline, in the diff", + Notes::Both => "both, diff and panel", + } + .to_owned(), Row::LineNumbers => on_off(now.line_numbers).to_owned(), Row::Whitespace => whitespace_label(now.whitespace).to_owned(), Row::TabWidth => format!("{} columns", now.tab_width.get()), @@ -304,6 +318,7 @@ impl Screen { }; } Row::Wrap => now.wrap = !now.wrap, + Row::Notes => now.notes = cycle(&[Notes::Panel, Notes::Inline, Notes::Both], now.notes, back), Row::LineNumbers => now.line_numbers = !now.line_numbers, Row::Whitespace => { let order = [Whitespace::Show, Whitespace::IgnoreAll, Whitespace::IgnoreChange]; diff --git a/crates/plannotator-tui/src/review/settings/state.rs b/crates/plannotator-tui/src/review/settings/state.rs index 1caa0168..8787b0d6 100644 --- a/crates/plannotator-tui/src/review/settings/state.rs +++ b/crates/plannotator-tui/src/review/settings/state.rs @@ -16,7 +16,7 @@ use std::path::{Path, PathBuf}; use anyhow::{Context as _, Result}; use crate::config::review::{ - Background, DiffTheme, InlineChanges, Layout, ReviewConfig, SplitShare, TabWidth, Whitespace, + Background, DiffTheme, InlineChanges, Layout, Notes, ReviewConfig, SplitShare, TabWidth, Whitespace, }; /// The state file in the data folder `data_dir`. @@ -25,7 +25,7 @@ pub(crate) fn path(data_dir: &Path) -> PathBuf { } /// The keys the file holds, as `[review]` names them. -const KEYS: [&str; 9] = [ +const KEYS: [&str; 10] = [ "layout", "wrap", "line_numbers", @@ -35,6 +35,7 @@ const KEYS: [&str; 9] = [ "whitespace", "tab_width", "inline_changes", + "notes", ]; /// `settings` with the file's good keys over it, and what was wrong with the file, if @@ -63,6 +64,7 @@ pub(in crate::review) fn load(path: &Path, settings: ReviewConfig) -> (ReviewCon "whitespace" => value.try_into::().map(|v| out.whitespace = v).is_ok(), "tab_width" => value.try_into::().map(|v| out.tab_width = v).is_ok(), "inline_changes" => value.try_into::().map(|v| out.inline_changes = v).is_ok(), + "notes" => value.try_into::().map(|v| out.notes = v).is_ok(), _ => false, }; if !taken { @@ -103,6 +105,11 @@ pub(super) fn changes(before: ReviewConfig, now: ReviewConfig) -> Vec<(&'static InlineChanges::Char => "char", InlineChanges::None => "none", }; + let notes = |notes| match notes { + Notes::Panel => "panel", + Notes::Inline => "inline", + Notes::Both => "both", + }; let mut out = Vec::new(); if before.layout != now.layout { out.push(("layout", text(layout(now.layout)))); @@ -132,6 +139,9 @@ pub(super) fn changes(before: ReviewConfig, now: ReviewConfig) -> Vec<(&'static if before.inline_changes != now.inline_changes { out.push(("inline_changes", text(inline_changes(now.inline_changes)))); } + if before.notes != now.notes { + out.push(("notes", text(notes(now.notes)))); + } out } @@ -224,6 +234,7 @@ mod tests { whitespace: Whitespace::IgnoreChange, tab_width: TabWidth::new(8), inline_changes: InlineChanges::WordAlt, + notes: Notes::Inline, ..config }; write(&file, &changes(config, now)).expect("written"); @@ -231,6 +242,7 @@ mod tests { assert!(text.contains("split_ratio = 0.62"), "two decimals: {text}"); assert!(text.contains("whitespace = \"ignore-change\""), "{text}"); assert!(text.contains("tab_width = 8") && text.contains("inline_changes = \"word-alt\""), "{text}"); + assert!(text.contains("notes = \"inline\""), "{text}"); assert!(!text.contains("wrap"), "an unchanged key is not written: {text}"); let (read, notice) = load(&file, config); assert_eq!(notice, None); @@ -268,9 +280,14 @@ mod tests { assert!(notice.contains(key), "{notice}"); } assert!(!notice.contains("wrap") && !notice.contains("inline_changes"), "{notice}"); - for text in - ["tab_width = 17\n", "tab_width = \"8\"\n", "whitespace = 1\n", "inline_changes = \"words\"\n"] - { + for text in [ + "tab_width = 17\n", + "tab_width = \"8\"\n", + "whitespace = 1\n", + "inline_changes = \"words\"\n", + "notes = \"rail\"\n", + "notes = 2\n", + ] { std::fs::write(&file, text).expect("write"); let (read, notice) = load(&file, ReviewConfig::DEFAULT); assert_eq!(read, ReviewConfig::DEFAULT, "{text:?}"); diff --git a/crates/plannotator-tui/src/review/tests/inline_flow.rs b/crates/plannotator-tui/src/review/tests/inline_flow.rs new file mode 100644 index 00000000..505fda32 --- /dev/null +++ b/crates/plannotator-tui/src/review/tests/inline_flow.rs @@ -0,0 +1,396 @@ +//! Notes drawn in the diff (`[review] notes = "inline"` or `"both"`): a box under each note's +//! last line, over its side of a split diff, stacked in the order made; the file note under +//! its heading; what the cursor, the keys and the mouse do on a box; and the default, +//! `panel`, drawing exactly as before. On the long four-file fixture at 160×45. + +use plannotator_tui_review::{CodeAnnotation, Side}; +use ratatui::crossterm::event::{KeyCode, MouseButton, MouseEventKind}; +use ratatui::style::Modifier; + +use super::compose_near::{COLS, ROWS, draw, long, report, the_box}; +use super::inline_support::{box_saying, cells, check_boxes, comment, row_of_spot, spot}; +use super::whitespace_flow; +use super::*; +use crate::config::review::Notes; +use crate::review::{Draft, Mode}; +use crate::theme::palette; + +const SIZE: (u16, u16) = (COLS, ROWS); + +/// The long fixture opened with `[review]` as `config` says, the cursor on new line 30 of +/// file0.py, near the bottom: new lines 8 to 30 are on screen. +fn opened(tag: &str, config: &str) -> (Fixture, Screen) { + let fixture = long(tag, false); + fixture.write_config(&format!("[review]\n{config}\n")); + let mut screen = fixture.open_configured(); + draw(&mut screen, SIZE); + screen.diff.reveal("file0.py", Side::New, 30).expect("line 30"); + draw(&mut screen, SIZE); + (fixture, screen) +} + +/// The Notes setting to `notes`, by the settings menu. +pub(super) fn set_notes(screen: &mut Screen, notes: Notes) { + let row = crate::review::settings::ROWS + .iter() + .position(|row| *row == crate::review::settings::Row::Notes) + .expect("a Notes row"); + keys(screen, ","); + for _ in 0..row { + keys(screen, "j"); + } + while screen.settings.now.notes != notes { + press(screen, KeyCode::Right); + } + press(screen, KeyCode::Esc); +} + +/// The diff pane's cells in `buffer`. +fn pane(screen: &Screen, buffer: &ratatui::buffer::Buffer) -> Vec { + let pane = screen.geometry.diff; + (pane.top()..pane.bottom()).map(|y| cells(buffer, pane.x, y, pane.width)).collect() +} + +fn all(buffer: &ratatui::buffer::Buffer) -> String { + (0..buffer.area.height).map(|y| cells(buffer, 0, y, buffer.area.width)).collect::>().join("\n") +} + +#[test] +fn the_panel_setting_keeps_no_rows_for_notes_and_draws_as_before() { + let (_fixture, mut screen) = opened("inline-panel", "layout = \"split\""); + let before = draw(&mut screen, SIZE); + comment(&mut screen, "file0.py", Side::New, (9, 10), "a panel note"); + comment(&mut screen, "file0.py", Side::Old, (12, 12), "an old one"); + let noted = draw(&mut screen, SIZE); + assert!(screen.diff.boxes_set().is_empty(), "no rows kept"); + assert!(screen.geometry.boxes.is_empty()); + assert!(!all(¬ed).contains("comment \u{b7} L"), "no box:\n{}", all(¬ed)); + // Inline and back: the diff is the one panel drew. + set_notes(&mut screen, Notes::Inline); + assert!(!screen.diff.boxes_set().is_empty()); + draw(&mut screen, SIZE); + set_notes(&mut screen, Notes::Panel); + let back = draw(&mut screen, SIZE); + assert!(screen.diff.boxes_set().is_empty()); + assert_eq!(pane(&screen, &back), pane(&screen, ¬ed), "panel again draws what it drew"); + assert_ne!(pane(&screen, &before), pane(&screen, ¬ed), "the notes' marks"); +} + +#[test] +fn boxes_hang_under_their_notes_last_line_on_its_side_in_the_order_made() { + let (_fixture, mut screen) = opened("inline-under", "layout = \"unified\"\nnotes = \"inline\""); + comment(&mut screen, "file0.py", Side::New, (10, 12), "first range"); + comment(&mut screen, "file0.py", Side::New, (12, 12), "second on twelve"); + comment(&mut screen, "file0.py", Side::Old, (12, 12), "old twelve"); + comment(&mut screen, "file1.py", Side::New, (12, 12), "other file twelve"); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "unified"); + let first = box_saying(&screen, "first range").expect("drawn"); + let second = box_saying(&screen, "second on twelve").expect("drawn"); + assert_eq!(second.y, first.bottom(), "stacked under the earlier one"); + assert!(cells(&buffer, first.x, first.y, first.width).contains("comment \u{b7} L10\u{2013}12")); + assert!(box_saying(&screen, "old twelve").is_none(), "the removed lines are further up"); + // Unified, a box starts at the code's first column, as wide as the code or 84. + let area = screen.diff.box_areas().first().map(|a| a.area).expect("an area"); + assert_eq!((first.x, first.width), (area.x, area.width.min(84))); + // The border is the notes' colour, the title bold. + let corner = buffer.cell((first.x, first.y)).expect("corner"); + assert_eq!(corner.fg, palette().comment); + // The old line's box is under the removed line 12, with the old side named. + screen.diff.reveal("file0.py", Side::Old, 12).expect("old line 12"); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "old"); + let old = box_saying(&screen, "old twelve").expect("drawn"); + assert!(cells(&buffer, old.x, old.y, old.width).contains("comment \u{b7} L12 old")); + // The other file's box is under its own line 12. + screen.diff.reveal("file1.py", Side::New, 16).expect("file1 line 16"); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "file1"); + assert!(box_saying(&screen, "other file twelve").is_some()); + assert!(box_saying(&screen, "first range").is_none(), "file0 is off screen"); +} + +#[test] +fn split_a_box_sits_over_its_sides_half_or_across_when_that_half_is_narrow() { + let (_fixture, mut screen) = opened("inline-split", "layout = \"split\"\nnotes = \"inline\""); + comment(&mut screen, "file0.py", Side::Old, (12, 12), "old side note"); + comment(&mut screen, "file0.py", Side::New, (12, 12), "new side note"); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "split 50"); + let line = screen.diff.split_line().expect("split"); + let old = box_saying(&screen, "old side note").expect("old"); + let new = box_saying(&screen, "new side note").expect("new"); + assert!(old.right() <= line, "the old box over the old side: {old:?} {line}"); + assert!(new.x > line, "the new box over the new side: {new:?} {line}"); + assert_eq!(new.y, old.bottom(), "both hang under the row, in the order made"); + // 30:70 leaves the old side under 48 columns: its box runs across. + keys(&mut screen, "(((("); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "split 30"); + let line = screen.diff.split_line().expect("split"); + assert!(line - screen.geometry.diff.x < 48, "narrow old side"); + let old = box_saying(&screen, "old side note").expect("old"); + let area = screen.diff.box_areas().first().map(|a| a.area).expect("an area"); + assert_eq!((old.x, old.width), (area.x, area.width.min(84)), "across from the old code"); + assert!(old.right() > line); + let new = box_saying(&screen, "new side note").expect("new"); + assert!(new.x > line); +} + +#[test] +fn a_file_note_sits_under_its_heading_and_notes_with_no_box_are_counted() { + let (_fixture, mut screen) = opened("inline-file", "layout = \"unified\"\nnotes = \"inline\""); + keys(&mut screen, "C"); + type_and_save(&mut screen, "whole file thoughts"); + keys(&mut screen, "M"); + type_and_save(&mut screen, "about everything"); + screen.diff.show_heading(0).expect("heading"); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "file note"); + let boxed = box_saying(&screen, "whole file thoughts").expect("drawn"); + assert!(cells(&buffer, boxed.x, boxed.y, boxed.width).contains("file comment")); + let footer = all(&buffer); + assert!(footer.contains("1 note not shown inline \u{b7} z"), "{footer}"); + open_notes(&mut screen); + let buffer = draw(&mut screen, SIZE); + assert!(all(&buffer).contains("1 note not shown inline") && !all(&buffer).contains("inline \u{b7} z")); +} + +#[test] +fn inline_starts_without_the_panel_whatever_the_notes_and_both_keeps_its_rule() { + let (fixture, mut screen) = opened("inline-rail", "notes = \"inline\""); + comment(&mut screen, "file0.py", Side::New, (9, 9), "a note"); + let mut again = fixture.open_configured(); + draw(&mut again, SIZE); + assert!(!again.rail_shown(), "inline: no panel at the start, notes or not"); + press(&mut again, KeyCode::Char('z')); + assert!(again.rail_shown(), "z opens it"); + press(&mut again, KeyCode::Char('z')); + assert!(!again.rail_shown()); + press(&mut again, KeyCode::Tab); + assert!(again.rail_shown() && again.focus == crate::review::Focus::Notes, "Tab goes there"); + fixture.write_config("[review]\nnotes = \"both\"\n"); + let both = fixture.open_configured(); + assert!(both.rail_shown(), "both: the panel's rule, shown with notes"); + // Switching to inline puts the panel away; back to both brings it. + let mut screen = both; + draw(&mut screen, SIZE); + set_notes(&mut screen, Notes::Inline); + assert!(!screen.rail_shown()); + set_notes(&mut screen, Notes::Both); + assert!(screen.rail_shown()); +} + +#[test] +fn on_a_box_enter_edits_it_over_the_box_delete_removes_it_and_x_stays_viewed() { + let (_fixture, mut screen) = opened("inline-keys", "layout = \"split\"\nnotes = \"both\""); + open_notes(&mut screen); + comment(&mut screen, "file0.py", Side::New, (9, 9), "fix this"); + comment(&mut screen, "file0.py", Side::New, (20, 20), "other one"); + screen.diff.reveal("file0.py", Side::New, 9).expect("line 9"); + press(&mut screen, KeyCode::Char('j')); + assert!(screen.cursor_note().is_some_and(|n| n.text.as_deref() == Some("fix this")), "on the box"); + let buffer = draw(&mut screen, SIZE); + let boxed = box_saying(&screen, "fix this").expect("drawn"); + let corner = buffer.cell((boxed.x, boxed.y)).expect("corner"); + assert_eq!(corner.fg, palette().accent, "the cursor's box is lit"); + assert!(corner.modifier.contains(Modifier::BOLD)); + let text = all(&buffer); + assert!(text.contains("enter/e edit") && text.contains("delete remove"), "{text}"); + // `x` is still viewed: the note stays. + press(&mut screen, KeyCode::Char('x')); + assert_eq!(screen.store.annotations().len(), 2); + assert!(screen.status.as_deref().is_some_and(|s| s.contains("viewed")), "{:?}", screen.status); + // Enter: the comment box over the note's box, with its text. + press(&mut screen, KeyCode::Enter); + assert!(matches!(&screen.mode, Mode::Compose(Draft::Edit(_)))); + assert_eq!(screen.compose.value(), "fix this"); + let buffer = draw(&mut screen, SIZE); + // (`x` ticked the file in the list, which got wider: the box with it.) + let boxed = box_saying(&screen, "fix this").expect("still drawn"); + let corner = cells(&buffer, boxed.x, boxed.y, 7); + assert_eq!(corner, "\u{256d} edit ", "the comment box over the note's box"); + press(&mut screen, KeyCode::End); + type_and_save(&mut screen, " now, and say why at some length so the box needs a second line of text"); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "edited"); + assert!(screen.cursor_note().is_some(), "the cursor stays on the box"); + // `e` edits too; Esc keeps it. + press(&mut screen, KeyCode::Char('e')); + assert!(matches!(&screen.mode, Mode::Compose(Draft::Edit(_)))); + press(&mut screen, KeyCode::Esc); + assert_eq!(screen.mode, Mode::Browse); + // Delete removes it, and the cursor is back on its line. + press(&mut screen, KeyCode::Delete); + assert_eq!(screen.store.annotations().len(), 1); + assert_eq!(screen.status.as_deref(), Some("note removed")); + assert_eq!(screen.diff.line_on(Side::New).expect("line"), Some(("file0.py", 9))); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "removed"); + assert!(box_saying(&screen, "fix this").is_none()); +} + +#[test] +fn a_click_on_a_box_selects_its_note_and_a_drag_never_starts_or_lands_on_one() { + let (_fixture, mut screen) = opened("inline-mouse", "layout = \"unified\"\nnotes = \"both\""); + open_notes(&mut screen); + comment(&mut screen, "file0.py", Side::New, (12, 12), "first"); + comment(&mut screen, "file0.py", Side::New, (20, 20), "second"); + draw(&mut screen, SIZE); + let boxed = box_saying(&screen, "second").expect("drawn"); + let at = (boxed.x + 4, boxed.y + 1); + report(&mut screen, MouseEventKind::Down(MouseButton::Left), at); + assert!(screen.drag.is_none(), "no selection starts on a box"); + report(&mut screen, MouseEventKind::Up(MouseButton::Left), at); + assert!(screen.cursor_note().is_some_and(|n| n.text.as_deref() == Some("second"))); + assert_eq!(screen.selected_note().and_then(|n| n.text.as_deref()), Some("second"), "the panel follows"); + assert_eq!(screen.diff.selection(), None); + // A drag from line 11 down over line 12's box to 14 selects the lines only. + let first = box_saying(&screen, "first").expect("drawn"); + let x = first.x + 10; + let from = first.y - 2; + report(&mut screen, MouseEventKind::Down(MouseButton::Left), (x, from)); + for y in from + 1..first.bottom() + 3 { + report(&mut screen, MouseEventKind::Drag(MouseButton::Left), (x, y)); + draw(&mut screen, SIZE); + } + report(&mut screen, MouseEventKind::Up(MouseButton::Left), (x, first.bottom() + 2)); + let selected = screen.diff.selection().expect("a selection"); + assert_eq!((selected.side, selected.first), (Side::New, 11), "{selected:?}"); + assert!(selected.last >= 13, "past the box: {selected:?}"); +} + +#[test] +fn a_new_comment_opens_below_the_boxes_under_its_line_and_its_own_box_follows() { + let (_fixture, mut screen) = opened("inline-compose", "layout = \"unified\"\nnotes = \"inline\""); + comment(&mut screen, "file0.py", Side::New, (12, 12), "already here"); + screen.diff.reveal("file0.py", Side::New, 12).expect("line 12"); + let buffer = draw(&mut screen, SIZE); + let existing = box_saying(&screen, "already here").expect("drawn"); + let before = spot(&screen); + let row = row_of_spot(&screen, &before).expect("on screen"); + press(&mut screen, KeyCode::Char('c')); + let buffer_open = draw(&mut screen, SIZE); + let compose = the_box(&buffer_open, "comment on"); + assert_eq!(compose.y, existing.bottom(), "below the box, covering no code"); + drop(buffer); + type_and_save(&mut screen, "one more"); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "saved"); + let added = box_saying(&screen, "one more").expect("its box"); + assert_eq!(added.y, existing.bottom(), "under the earlier box"); + assert_eq!(row_of_spot(&screen, &before), Some(row), "the line kept its row"); +} + +#[test] +fn a_review_opened_with_notes_starts_at_the_top_with_the_first_files_box() { + let (fixture, mut screen) = opened("inline-open", "notes = \"inline\"\nlayout = \"unified\""); + keys(&mut screen, "C"); + type_and_save(&mut screen, "about file zero"); + comment(&mut screen, "file0.py", Side::Old, (1, 1), "on line one"); + let mut again = fixture.open_configured(); + let buffer = draw(&mut again, SIZE); + check_boxes(&again, &buffer, "opened"); + let pane = again.geometry.diff; + let top = again.diff.row_at(pane.right() - 2, pane.y).expect("the top row"); + assert_eq!(top.kind, diffs_rs::engine::DiffRowKind::Header, "the first heading on top"); + let file = box_saying(&again, "about file zero").expect("the file's box shows"); + assert_eq!(file.y, pane.y + 1, "right under it"); + let cursor = again.diff.cursor_row().expect("a cursor"); + assert_eq!((cursor.file, cursor.old_line, cursor.part), (0, Some(1), 0), "on the first line"); + assert!(box_saying(&again, "on line one").is_some()); +} + +#[test] +fn a_note_from_the_agent_gets_its_box_credited_and_suggestions_show_their_code() { + let (fixture, mut screen) = opened("inline-pi", "notes = \"inline\"\nlayout = \"unified\""); + let file = fixture.repo().join("file0.py"); + let (note, _answer) = crate::pi::link::Note::for_test(file, None, Some(9), "check this"); + screen.take_pi_note(¬e); + let key = screen.capture.patch_key.clone(); + let patch = screen.file("file0.py").expect("file"); + let suggestion = CodeAnnotation::suggestion(patch, 11, 11, "f0_line_11 = 11 * 3".into(), None, &key); + screen.add_note(suggestion).expect("saved"); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "agent"); + let credited = box_saying(&screen, "check this").expect("drawn"); + assert!( + cells(&buffer, credited.x, credited.y, credited.width) + .contains("comment \u{b7} L9 \u{b7} pi \u{b7} test") + ); + let text = all(&buffer); + assert!(text.contains("suggestion \u{b7} L11"), "{text}"); + assert!( + text.contains("- f0_line_11 = 11 * 2 # changed") && text.contains("+ f0_line_11 = 11 * 3"), + "{text}" + ); +} + +#[test] +fn a_box_in_a_hunk_hidden_with_whitespace_goes_is_counted_and_comes_back() { + let fixture = whitespace_flow::fixture("inline-ws"); + fixture.write_config("[review]\nnotes = \"inline\"\nlayout = \"unified\"\n"); + let mut screen = fixture.open_configured(); + draw(&mut screen, SIZE); + comment(&mut screen, "ws.go", Side::New, (21, 21), "trailing spaces here"); + comment(&mut screen, "ws.go", Side::New, (6, 6), "doubled"); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "shown"); + assert!(box_saying(&screen, "trailing spaces here").is_some()); + assert!(!all(&buffer).contains("not shown inline")); + keys(&mut screen, "W"); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "whitespace hidden"); + assert!(box_saying(&screen, "trailing spaces here").is_none(), "its hunk is a heading now"); + assert!(box_saying(&screen, "doubled").is_some(), "the other stays"); + assert!(all(&buffer).contains("1 note not shown inline \u{b7} z"), "{}", all(&buffer)); + keys(&mut screen, "W"); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "whitespace shown"); + assert!(box_saying(&screen, "trailing spaces here").is_some(), "back"); + assert!(!all(&buffer).contains("not shown inline")); +} + +#[test] +fn three_hundred_notes_lay_out_once_and_draw_only_what_shows() { + let (_fixture, mut screen) = opened("inline-many", "layout = \"split\"\nnotes = \"inline\""); + for i in 0..300u32 { + let file = format!("file{}.py", i % 4); + let line = 1 + (i / 4) % 89; + let side = if i % 3 == 0 { Side::Old } else { Side::New }; + comment(&mut screen, &file, side, (line, line), &format!("note {i} with a few words to wrap")); + } + draw(&mut screen, SIZE); + assert_eq!(screen.diff.boxes_set().len(), 300); + let started = Instant::now(); + for _ in 0..40 { + press(&mut screen, KeyCode::Char('j')); + let buffer = draw(&mut screen, SIZE); + assert!(screen.geometry.boxes.len() <= usize::from(ROWS), "only the boxes on screen"); + drop(buffer); + } + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "300 notes"); + // Debug build, 41 frames with 300 boxes set: well under a second each. + assert!(started.elapsed() < Duration::from_secs(20), "{:?}", started.elapsed()); + eprintln!("41 frames with 300 notes: {:?}", started.elapsed()); +} + +#[test] +fn the_notes_setting_comes_from_the_config_file_is_remembered_and_reset() { + let (fixture, mut screen) = opened("inline-setting", "notes = \"both\""); + assert_eq!(screen.settings.now.notes, Notes::Both, "the config file's"); + set_notes(&mut screen, Notes::Inline); + let mut next = fixture.open_configured(); + draw(&mut next, SIZE); + assert_eq!(next.settings.now.notes, Notes::Inline, "remembered over the config file"); + keys(&mut next, ","); + for _ in 0..crate::review::settings::ROWS.len() - 1 { + keys(&mut next, "j"); + } + press(&mut next, KeyCode::Enter); + assert_eq!(next.settings.now.notes, Notes::Both, "Reset: the config file's again"); + fixture.write_config("[review]\nnotes = \"sideways\"\n"); + let review = crate::config::Config::load_from(&fixture.config()); + assert!(review.is_err_and(|e| format!("{e:#}").contains("sideways")), "a bad value is named"); +} diff --git a/crates/plannotator-tui/src/review/tests/inline_support.rs b/crates/plannotator-tui/src/review/tests/inline_support.rs new file mode 100644 index 00000000..cb299ece --- /dev/null +++ b/crates/plannotator-tui/src/review/tests/inline_support.rs @@ -0,0 +1,144 @@ +//! What every frame with notes drawn in the diff must hold, read from the frame and the +//! viewer's rows: each box is inside the rows kept for it, over no code, under the line of +//! its own note (by file, side and line), saying that note's words; and where the cursor's +//! line is, to tell it did not move. + +use diffs_rs::engine::DiffRowKind; +use plannotator_tui_review::{CodeAnnotation, NoteScope, Side}; +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; + +use super::*; + +/// The text of `buffer`'s row `y` from `x` for `width` cells. +pub(super) fn cells(buffer: &Buffer, x: u16, y: u16, width: u16) -> String { + (x..x + width).filter_map(|x| buffer.cell((x, y)).map(|c| c.symbol().to_owned())).collect() +} + +/// Every box drawn in the last frame holds: see the module. +pub(super) fn check_boxes(screen: &Screen, buffer: &Buffer, case: &str) { + let pane = screen.geometry.diff; + let areas = screen.diff.box_areas(); + assert_eq!( + areas.iter().map(|a| a.id).collect::>(), + screen.geometry.boxes.iter().map(|(_, id)| *id).collect::>(), + "{case}: every box the viewer kept rows for is drawn" + ); + for (&(rect, id), area) in screen.geometry.boxes.iter().zip(areas) { + let note = screen.note_of_box(id).unwrap_or_else(|| panic!("{case}: box {id} has a note")); + let what = format!("{case}: box {id} ({})", Screen::box_label(note)); + assert!(rect.width > 0 && rect.height > 0, "{what}: drawn"); + assert_eq!(rect.intersection(area.area), rect, "{what}: inside its rows {area:?}"); + assert!( + pane.contains(rect.as_position()) + && rect.right() <= pane.right() + && rect.bottom() <= pane.bottom() + ); + for y in rect.top()..rect.bottom() { + for x in [rect.left(), rect.right() - 1, pane.left(), pane.right() - 1] { + assert_eq!(screen.diff.box_at(x, y), Some(id), "{what}: row {y} is its own, over no code"); + } + } + let left = buffer.cell((rect.x, rect.y)).map(|c| c.symbol().to_owned()).unwrap_or_default(); + let top = cells(buffer, rect.x, rect.y, rect.width); + if area.clipped_top == 0 { + assert_eq!(left, "\u{256d}", "{what}: its top-left corner first: {top:?}"); + assert!(top.contains(&Screen::box_label(note)), "{what}: titled for its note: {top:?}"); + if let Some(word) = note.text.as_deref().and_then(|t| t.split_whitespace().next()) + && rect.height > 1 + { + let body = cells(buffer, rect.x, rect.y + 1, rect.width); + assert!(body.contains(word), "{what}: says its note's words: {body:?}"); + } + anchored(screen, note, rect.y, &what); + } + let bottom_cut = area.height - area.clipped_top - area.area.height; + if bottom_cut == 0 { + let corner = buffer.cell((rect.x, rect.bottom() - 1)).map(|c| c.symbol().to_owned()); + assert_eq!(corner.as_deref(), Some("\u{2570}"), "{what}: its bottom border shows"); + } + } +} + +/// The first row above screen row `y` that is no box shows the note's line, or its file's +/// heading for a file note. +fn anchored(screen: &Screen, note: &CodeAnnotation, y: u16, what: &str) { + let pane = screen.geometry.diff; + let column = pane.right() - 2; + let above = (pane.top()..y).rev().find(|&row| screen.diff.box_at(column, row).is_none()); + let Some(above) = above else { return }; + let row = screen.diff.row_at(column, above).unwrap_or_else(|| panic!("{what}: a row above")); + assert_eq!(row.path, note.file_path, "{what}: under a row of its file"); + // Its line can be the one the sticky heading covers. + if row.kind == DiffRowKind::StickyHeader && note.scope == NoteScope::Line { + return; + } + if note.scope == NoteScope::File { + assert!(matches!(row.kind, DiffRowKind::Header | DiffRowKind::StickyHeader), "{what}: {row:?}"); + return; + } + let line = if note.side == Side::Old { row.old_line } else { row.new_line }; + assert_eq!(row.kind, DiffRowKind::Code, "{what}: under code: {row:?}"); + assert_eq!(line, Some(note.line_end), "{what}: under its last line on its side: {row:?}"); +} + +/// Where the cursor is, by what it shows: file, lines and kind. (Not the wrapped part: a +/// line wrapped again at another width can put the cursor on another of its parts.) +pub(super) type Spot = (String, Option, Option, String); + +pub(super) fn spot(screen: &Screen) -> Spot { + let row = screen.diff.cursor_row().expect("a cursor"); + (row.path.to_string(), row.old_line, row.new_line, format!("{:?}", row.kind)) +} + +/// The screen row of the last frame that shows `spot`, its first part when wrapped. +pub(super) fn row_of_spot(screen: &Screen, spot: &Spot) -> Option { + let pane = screen.geometry.diff; + let column = |side| match screen.diff.split_line() { + Some(line) if side == Side::Old => pane.x + (line - pane.x) / 2, + _ => pane.right() - 2, + }; + let side = screen + .diff + .cursor_row() + .map(|row| if row.side == diffs_rs::engine::Side::Old { Side::Old } else { Side::New }); + let x = column(side.unwrap_or(Side::New)); + (pane.top()..pane.bottom()).find(|&y| { + screen.diff.row_at(x, y).is_some_and(|row| { + (row.path.to_string(), row.old_line, row.new_line, format!("{:?}", row.kind)) == *spot + }) + }) +} + +/// The screen row of the last frame the cursor is on: the part of its line it is on, which +/// the viewer keeps on its row when the line wraps again at another width. +pub(super) fn row_of_cursor(screen: &Screen) -> Option { + let cursor = screen.diff.cursor_row()?; + let spot = spot(screen); + let first = row_of_spot(screen, &spot)?; + Some(first + u16::try_from(cursor.part).ok()?) +} + +/// Rows of the pane the viewer drew nothing on must all be at its bottom, past the diff's end. +pub(super) fn no_holes(screen: &Screen, case: &str) { + let pane = screen.geometry.diff; + let shown: Vec = + (pane.top()..pane.bottom()).map(|y| screen.diff.row_at(pane.right() - 2, y).is_some()).collect(); + let first_empty = shown.iter().position(|s| !s).unwrap_or(shown.len()); + assert!(shown.iter().skip(first_empty).all(|s| !s), "{case}: an empty row inside the diff: {shown:?}"); +} + +/// A note made as `c` makes one, on `first..=last` of `side` of `path`. +pub(super) fn comment(screen: &mut Screen, path: &str, side: Side, (first, last): (u32, u32), text: &str) { + let key = screen.capture.patch_key.clone(); + let file = screen.file(path).expect("the file"); + let note = CodeAnnotation::line_comment(file, side, first, last, text.to_owned(), &key); + screen.add_note(note).expect("saved"); +} + +/// The rectangle the last frame drew the box of the note saying `text` in. +pub(super) fn box_saying(screen: &Screen, text: &str) -> Option { + screen.geometry.boxes.iter().find_map(|&(rect, id)| { + screen.note_of_box(id).filter(|note| note.text.as_deref() == Some(text)).map(|_| rect) + }) +} diff --git a/crates/plannotator-tui/src/review/tests/inline_view.rs b/crates/plannotator-tui/src/review/tests/inline_view.rs new file mode 100644 index 00000000..1ec3a7f0 --- /dev/null +++ b/crates/plannotator-tui/src/review/tests/inline_view.rs @@ -0,0 +1,409 @@ +//! Boxes in the diff never move what the person reads. Unified and split (50:50, 30:70), wrap +//! on and off, the cursor near the top, in the middle and on the last page, with none, one or +//! many notes above and below it: after each thing a person does (a note added, edited, +//! removed, one from the agent, the Notes setting switched, the panel, the file list, a resize, +//! the line between the sides, the layout, wrapping, whitespace, the tab width, a viewed mark, +//! a drag) the cursor's line is on the screen row it was on, every line's code starts at the +//! column it did, no row is left empty, and every box is inside its rows, over no code, under +//! its own note's line, saying that note's words (`inline_support`). +//! +//! The exceptions are the documented ones: at the very start of the diff the line can move +//! up; wrapping turned on or off, reading the diff again, the file filter and jumping to a +//! note from the panel move the view by design (wrapping as it does with no boxes: the +//! cursor's file's heading comes to the top), and there only the boxes and the columns are +//! checked. + +use plannotator_tui_review::Side; +use ratatui::crossterm::event::{Event, KeyCode, MouseButton, MouseEventKind}; + +use super::compose_near::{draw, report}; +use super::inline_flow::set_notes; +use super::inline_support::{Spot, cells, check_boxes, comment, no_holes, row_of_cursor, spot}; +use super::save_keeps_view::{Columns, PATH, SIZE, columns, source}; +use super::*; +use crate::config::review::Notes; +use crate::review::diff::Progress; + +/// Screen.kt changed from line 60 to 140, notes.txt changed, opened as `config` says with the +/// notes inline. +fn kotlin(tag: &str, config: &str) -> (Fixture, Screen) { + let fixture = Fixture::new(tag); + fixture.write(PATH, &source(false)); + fixture.git(&["add", "."]); + fixture.git(&["-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "-qm", "kotlin"]); + fixture.write(PATH, &source(true)); + fixture.write("notes.txt", "changed\n"); + fixture.write_config(&format!("[review]\nnotes = \"inline\"\n{config}\n")); + let mut screen = fixture.open_configured(); + ready(&mut screen); + (fixture, screen) +} + +/// Draw and poll until the viewer has `files` files, coloured. +fn ready_with(screen: &mut Screen, files: usize) { + let started = Instant::now(); + loop { + screen.tick().expect("tick"); + draw(screen, SIZE); + if screen.diff.progress() == Progress::Ready && screen.diff.files_shown() >= files { + screen.tick().expect("tick"); + draw(screen, SIZE); + return; + } + assert!(started.elapsed() < Duration::from_secs(10), "the viewer never got ready"); + std::thread::sleep(Duration::from_millis(10)); + } +} + +/// Draw and poll until the viewer has both files, coloured. +fn ready(screen: &mut Screen) { + ready_with(screen, 2); +} + +/// Where the cursor starts. +#[derive(Debug, Clone, Copy)] +enum At { + /// On the first line of the hunk, at the top of the diff. + Top, + /// In the middle of the pane, on line 100. + Middle, + /// The last line of the diff (`G`). + LastPage, +} + +/// How many notes the review has before the first step. +#[derive(Debug, Clone, Copy)] +enum Many { + None, + One, + Many, +} + +/// What a frame shows: the cursor's line and row, and the code's columns. +struct Look { + cursor: Spot, + row: Option, + columns: Columns, + at_start: bool, + /// The pane's text, to show when a check fails. + text: String, +} + +fn look(screen: &mut Screen, case: &str) -> Look { + let buffer = draw(screen, SIZE); + check_boxes(screen, &buffer, case); + no_holes(screen, case); + let cursor = spot(screen); + let row = row_of_cursor(screen); + let pane = screen.geometry.diff; + let top_row = screen.diff.row_at(pane.right() - 2, pane.y); + let at_start = top_row + .as_ref() + .is_some_and(|row| row.file == 0 && matches!(row.kind, diffs_rs::engine::DiffRowKind::Header)); + let text = (pane.top()..pane.bottom()) + .map(|y| cells(&buffer, pane.x, y, pane.width)) + .collect::>() + .join("\n"); + Look { cursor, row, columns: columns(screen, &buffer), at_start, text } +} + +/// How a step may change the view. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Keeps { + /// The cursor's line on its row (moving up only at the very start of the diff). + Cursor, + /// Neither: the view moves by design. The boxes and the columns still hold. + Nothing, +} + +fn kept(before: &Look, after: &Look, keeps: Keeps, case: &str) { + for (key, column) in &before.columns { + if let Some(now) = after.columns.get(key) { + assert_eq!(column, now, "{case}: line {key:?} scrolled sideways"); + } + } + let common = before.columns.keys().filter(|k| after.columns.contains_key(*k)).count(); + assert!( + after.columns.is_empty() || common > 0 || keeps == Keeps::Nothing, + "{case}: no line of before is on screen" + ); + let side_columns = |look: &Look| { + let mut by_side: std::collections::BTreeMap<&str, u16> = std::collections::BTreeMap::new(); + for ((side, _), column) in &look.columns { + let first = by_side.entry(side).or_insert(*column); + assert_eq!(first, column, "{case}: every line of a side from its start"); + } + }; + side_columns(after); + match keeps { + Keeps::Cursor => { + assert_eq!(after.cursor, before.cursor, "{case}: the cursor stays on its line"); + match (before.row, after.row) { + (Some(was), Some(now)) if now < was && after.at_start => {} + (was, now) => assert_eq!( + now, was, + "{case}: the cursor's line keeps its screen row\nbefore:\n{}\nafter:\n{}", + before.text, after.text + ), + } + } + Keeps::Nothing => {} + } +} + +/// The line of Screen.kt `delta` lines from the cursor's (or from line 120 when the cursor +/// is in the other file), kept inside the hunk. +fn near(screen: &Screen, delta: i64) -> u32 { + let row = screen.diff.cursor_row().expect("cursor"); + let line = if row.path == PATH { row.new_line.or(row.old_line).unwrap_or(100) } else { 130 }; + (i64::from(line) + delta).clamp(58, 142) as u32 +} + +fn notes(screen: &mut Screen, many: Many) { + match many { + Many::None => {} + Many::One => { + let line = near(screen, -2); + comment(screen, PATH, Side::New, (line, line), "one note here"); + } + Many::Many => { + keys(screen, "C"); + type_and_save(screen, "about the whole file"); + for (side, lines, text) in [ + (Side::New, (61, 62), "a range near the top"), + (Side::Old, (64, 64), "the old side of 64"), + (Side::New, (90, 90), "first on ninety"), + (Side::New, (90, 90), "second on ninety"), + (Side::Old, (100, 100), "old hundred"), + (Side::New, (110, 112), "a range in the middle and a longer text that wraps in a box"), + (Side::New, (125, 125), "near the end"), + (Side::New, (138, 138), "last one in the hunk"), + ] { + comment(screen, PATH, side, lines, text); + } + comment(screen, "notes.txt", Side::New, (1, 1), "the other file"); + } + } +} + +fn start(screen: &mut Screen, at: At) { + match at { + At::Top => { + screen.diff.show_heading(0).expect("heading"); + for _ in 0..3 { + press(screen, KeyCode::Char('j')); + } + } + At::Middle => { + screen.diff.reveal(PATH, Side::New, 118).expect("line 118"); + draw(screen, SIZE); + for _ in 0..12 { + press(screen, KeyCode::Char('k')); + } + } + At::LastPage => press(screen, KeyCode::Char('G')), + } +} + +/// One thing a person does, and what it keeps. +type Step = (&'static str, Keeps, fn(&mut Screen, &Fixture)); + +fn steps() -> Vec { + vec![ + ("a note above, saved", Keeps::Cursor, |s, _| { + let line = near(s, -3); + comment(s, PATH, Side::New, (line, line), "added above the cursor"); + }), + ("a note below, saved", Keeps::Cursor, |s, _| { + let line = near(s, 2); + comment(s, PATH, Side::New, (line, line), "added below the cursor"); + }), + ("c on the cursor's line, typed, saved", Keeps::Cursor, |s, _| { + if s.diff.cursor().ok().flatten().is_some() { + press(s, KeyCode::Char('c')); + type_and_save(s, "typed on the cursor line"); + } + }), + ("a note above edited taller", Keeps::Cursor, |s, _| { + if let Some(id) = above(s) { + s.edit_note(&id); + press(s, KeyCode::End); + type_and_save(s, &" and much more text that makes this box taller than before".repeat(3)); + } + }), + ("a note above edited shorter", Keeps::Cursor, |s, _| { + if let Some(id) = above(s) { + s.edit_note(&id); + s.compose = crate::ui::compose::Compose::default(); + type_and_save(s, "short"); + } + }), + ("a note above removed", Keeps::Cursor, |s, _| { + if let Some(id) = above(s) { + s.remove_note(&id).expect("removed"); + } + }), + ("a note from the agent", Keeps::Cursor, |s, fixture| { + let line = near(s, -4); + let file = fixture.repo().join(PATH); + let (note, _answer) = crate::pi::link::Note::for_test(file, None, Some(line as usize), "from pi"); + s.take_pi_note(¬e); + }), + ("Notes: both", Keeps::Cursor, |s, _| set_notes(s, Notes::Both)), + ("a note saved with both", Keeps::Cursor, |s, _| { + let line = near(s, -1); + comment(s, PATH, Side::Old, (line, line), "saved with both"); + }), + ("Notes: panel", Keeps::Cursor, |s, _| set_notes(s, Notes::Panel)), + ("a note saved with the panel", Keeps::Cursor, |s, _| { + let line = near(s, -5); + comment(s, PATH, Side::New, (line, line), "saved with the panel"); + }), + ("Notes: inline", Keeps::Cursor, |s, _| set_notes(s, Notes::Inline)), + ("z opens the panel", Keeps::Cursor, |s, _| keys(s, "z")), + ("z closes it", Keeps::Cursor, |s, _| keys(s, "z")), + ("f twice closes the list", Keeps::Cursor, |s, _| keys(s, "ff")), + ("f opens it", Keeps::Cursor, |s, _| { + keys(s, "f"); + press(s, KeyCode::Esc); + }), + ("narrower and back", Keeps::Cursor, |s, _| { + draw(s, (150, SIZE.1)); + draw(s, SIZE); + }), + ("(", Keeps::Cursor, |s, _| keys(s, "(")), + (")", Keeps::Cursor, |s, _| keys(s, ")")), + ("u twice", Keeps::Cursor, |s, _| { + keys(s, "u"); + draw(s, SIZE); + keys(s, "u"); + }), + ("W twice", Keeps::Cursor, |s, _| { + keys(s, "W"); + draw(s, SIZE); + keys(s, "W"); + }), + ("the tab width", Keeps::Cursor, |s, _| { + let row = crate::review::settings::ROWS + .iter() + .position(|row| *row == crate::review::settings::Row::TabWidth) + .expect("the row"); + keys(s, ","); + for _ in 0..row { + keys(s, "j"); + } + press(s, KeyCode::Right); + press(s, KeyCode::Esc); + }), + ("x marks the file viewed", Keeps::Cursor, |s, _| keys(s, "x")), + ("x again", Keeps::Cursor, |s, _| keys(s, "x")), + ("a drag over lines and a box, let go", Keeps::Nothing, |s, _| drag_over(s)), + ("w", Keeps::Nothing, |s, _| keys(s, "w")), + ("w back", Keeps::Nothing, |s, _| keys(s, "w")), + ("a note picked in the panel", Keeps::Nothing, |s, _| { + keys(s, "z"); + press(s, KeyCode::Tab); + keys(s, "jj"); + press(s, KeyCode::Tab); + keys(s, "z"); + }), + ("the file filter and back", Keeps::Nothing, |s, _| { + keys(s, "/Screen"); + press(s, KeyCode::Enter); + ready_with(s, 1); + keys(s, "/"); + press(s, KeyCode::Esc); + ready(s); + }), + ("r reads the diff again", Keeps::Nothing, |s, _| { + keys(s, "r"); + ready(s); + }), + ] +} + +/// A line note on Screen.kt above the cursor's line, the nearest. +fn above(screen: &Screen) -> Option { + let row = screen.diff.cursor_row()?; + let line = if row.path == PATH { row.new_line.or(row.old_line)? } else { 200 }; + screen + .store + .annotations() + .iter() + .filter(|n| { + n.file_path == PATH && n.scope == plannotator_tui_review::NoteScope::Line && n.line_end < line + }) + .max_by_key(|n| n.line_end) + .map(|n| n.id.clone()) +} + +/// A drag down over three rows of code from the cursor's row, which crosses a box when one +/// hangs there, and the release: the view does not move (0.11.3). +fn drag_over(screen: &mut Screen) { + let buffer = draw(screen, SIZE); + drop(buffer); + let pane = screen.geometry.diff; + let x = pane.right() - 20; + let rows = |screen: &Screen| -> Vec<_> { + (pane.top()..pane.bottom()) + .map(|y| { + screen + .diff + .row_at(pane.right() - 2, y) + .map(|r| (r.path, r.old_line, r.new_line, r.part, r.kind)) + }) + .collect() + }; + let Some(from) = (pane.top() + 3..pane.bottom() - 8) + .find(|&y| screen.diff.row_at(x, y).is_some_and(|r| r.kind == diffs_rs::engine::DiffRowKind::Code)) + else { + return; + }; + let before = rows(screen); + report(screen, MouseEventKind::Down(MouseButton::Left), (x, from)); + for y in from + 1..from + 6 { + report(screen, MouseEventKind::Drag(MouseButton::Left), (x, y)); + draw(screen, SIZE); + } + report(screen, MouseEventKind::Up(MouseButton::Left), (x, from + 5)); + draw(screen, SIZE); + assert_eq!(rows(screen), before, "letting go moved the view"); + screen.handle_event(Event::Key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE))).expect("esc"); +} + +fn every_step(name: &str, layout: &str) { + for wrap in [false, true] { + for at in [At::Top, At::Middle, At::LastPage] { + for many in [Many::None, Many::One, Many::Many] { + let case = format!("{name} wrap {wrap} {at:?} {many:?}"); + let tag = format!("inline-view-{}-{wrap}-{at:?}-{many:?}", name.replace([' ', ':'], "-")); + let (fixture, mut screen) = kotlin(&tag, &format!("{layout}\nwrap = {wrap}")); + notes(&mut screen, many); + start(&mut screen, at); + let mut before = look(&mut screen, &format!("{case}: start")); + for (what, keeps, step) in steps() { + let case = format!("{case}: {what}"); + step(&mut screen, &fixture); + let after = look(&mut screen, &case); + kept(&before, &after, keeps, &case); + before = after; + } + } + } + } +} + +#[test] +fn unified_boxes_never_move_the_view() { + every_step("unified", "layout = \"unified\""); +} + +#[test] +fn split_50_boxes_never_move_the_view() { + every_step("split 50", "layout = \"split\""); +} + +#[test] +fn split_30_boxes_never_move_the_view() { + every_step("split 30", "layout = \"split\"\nsplit_ratio = 0.3"); +} diff --git a/crates/plannotator-tui/src/review/tests/mod.rs b/crates/plannotator-tui/src/review/tests/mod.rs index 4467c1ab..4850e65b 100644 --- a/crates/plannotator-tui/src/review/tests/mod.rs +++ b/crates/plannotator-tui/src/review/tests/mod.rs @@ -18,6 +18,9 @@ mod file_list_mouse; mod file_moves; #[cfg(unix)] mod first_look; +mod inline_flow; +mod inline_support; +mod inline_view; mod jump_flow; mod look; mod mouse_flow; diff --git a/crates/plannotator-tui/src/review/tests/save_keeps_view.rs b/crates/plannotator-tui/src/review/tests/save_keeps_view.rs index 7eb45441..04c54e8d 100644 --- a/crates/plannotator-tui/src/review/tests/save_keeps_view.rs +++ b/crates/plannotator-tui/src/review/tests/save_keeps_view.rs @@ -20,12 +20,12 @@ use super::compose_near::{View, draw, report, view}; use super::*; use crate::review::diff::{Lines, Progress}; -const SIZE: (u16, u16) = (190, 50); -const PATH: &str = "Screen.kt"; +pub(super) const SIZE: (u16, u16) = (190, 50); +pub(super) const PATH: &str = "Screen.kt"; /// Line `i` of `Screen.kt`, before or after the change: every fourth from line 2 a short comment, the /// others longer than any pane, each with its own `rowNNN` to find it by. -fn kotlin_line(i: usize, after: bool) -> String { +pub(super) fn kotlin_line(i: usize, after: bool) -> String { if i % 4 == 2 { return format!(" // section {i}\n"); } @@ -37,7 +37,7 @@ fn kotlin_line(i: usize, after: bool) -> String { ) } -fn source(after: bool) -> String { +pub(super) fn source(after: bool) -> String { (1..=200).map(|i| kotlin_line(i, after)).collect() } @@ -112,9 +112,9 @@ fn drag(screen: &mut Screen, side: Side, (first, last): (u32, u32), up: bool) { /// Where each `rowNNN` is drawn on each side, from that side's left edge: the code's /// columns. Equal maps mean no line scrolled sideways (and none left the screen). -type Columns = BTreeMap<(&'static str, u32), u16>; +pub(super) type Columns = BTreeMap<(&'static str, u32), u16>; -fn columns(screen: &Screen, buffer: &Buffer) -> Columns { +pub(super) fn columns(screen: &Screen, buffer: &Buffer) -> Columns { let pane = screen.geometry.diff; let sides: Vec<(&'static str, u16, u16)> = match screen.diff.split_line() { Some(line) => vec![("old", pane.x, line), ("new", line + 1, pane.right())], diff --git a/crates/plannotator-tui/src/review/tests/settings_flow.rs b/crates/plannotator-tui/src/review/tests/settings_flow.rs index ca93784b..3d8fa0d1 100644 --- a/crates/plannotator-tui/src/review/tests/settings_flow.rs +++ b/crates/plannotator-tui/src/review/tests/settings_flow.rs @@ -10,7 +10,7 @@ use ratatui::crossterm::event::{MouseButton, MouseEvent, MouseEventKind}; use ratatui::layout::Rect; use super::*; -use crate::config::review::{Background, DiffTheme, Layout, ReviewConfig, SplitShare}; +use crate::config::review::{Background, DiffTheme, Layout, Notes, ReviewConfig, SplitShare}; use crate::review::Mode; use crate::review::settings::{Settings, state}; use crate::ui::chips; @@ -135,6 +135,7 @@ fn the_settings_menu_changes_every_setting_live_and_remembers_each_change() { "Layout", "Split ratio", "Wrap", + "Notes", "Line numbers", "Whitespace", "Tab width", @@ -173,10 +174,20 @@ fn the_settings_menu_changes_every_setting_live_and_remembers_each_change() { press(&mut screen, KeyCode::Left); buffer(&mut screen, COLS, ROWS); assert_eq!(remembered(&fixture).split_ratio.permille(), 450); - // Wrap with Space, line numbers with Enter, then colours and the background. + // Wrap with Space, notes inline and then both, line numbers with Enter, then colours and + // the background. keys(&mut screen, "j "); assert!(screen.diff.options().wrap); keys(&mut screen, "j"); + let drawn = buffer(&mut screen, COLS, ROWS); + let shown: String = (0..ROWS).map(|y| text(&drawn, y)).collect::>().join("\n"); + assert!(shown.contains("Notes") && shown.contains("panel"), "{shown}"); + press(&mut screen, KeyCode::Right); + assert_eq!(screen.settings.now.notes, Notes::Inline); + assert_eq!(remembered(&fixture).notes, Notes::Inline); + press(&mut screen, KeyCode::Enter); + assert_eq!(screen.settings.now.notes, Notes::Both); + keys(&mut screen, "j"); press(&mut screen, KeyCode::Enter); buffer(&mut screen, COLS, ROWS); assert!(!screen.diff.options().line_numbers); @@ -196,6 +207,7 @@ fn the_settings_menu_changes_every_setting_live_and_remembers_each_change() { ReviewConfig { layout: Layout::Auto, wrap: true, + notes: Notes::Both, line_numbers: false, theme: DiffTheme::Light, background: Background::Theme, diff --git a/crates/plannotator-tui/src/review/tests/whitespace_flow.rs b/crates/plannotator-tui/src/review/tests/whitespace_flow.rs index 6e68bc60..f1bc8d28 100644 --- a/crates/plannotator-tui/src/review/tests/whitespace_flow.rs +++ b/crates/plannotator-tui/src/review/tests/whitespace_flow.rs @@ -26,7 +26,7 @@ const ROWS: u16 = 45; const GO_BEFORE: &str = "package main\n\nfunc total(items []int) int {\n\tsum := 0\n\tfor _, n := range items {\n\t\tsum += n\n\t}\n\treturn sum\n}\n\n// one\n// two\n// three\n// four\n// five\n// six\n// seven\n// eight\nfunc greet(name string) {\n\tprintln(\"hello\", name)\n\tprintln(\"bye\", name)\n}\n// a\n// b\n// c\n// d\n// e\n// f\n// g\n// h\nfunc main() {\n\tprintln(total([]int{1,2,3}))\n}\n"; const GO_AFTER: &str = "package main\n\nfunc total(items []int) int {\n sum := 0\n for _, n := range items {\n sum += n * 2\n }\n return sum\n}\n\n// one\n// two\n// three\n// four\n// five\n// six\n// seven\n// eight\nfunc greet(name string) {\n\tprintln(\"hello\", name) \n\tprintln(\"bye\", name) \n}\n// a\n// b\n// c\n// d\n// e\n// f\n// g\n// h\nfunc main() {\n\tprintln(total([]int{1, 2, 3}))\n}\n"; -fn fixture(tag: &str) -> Fixture { +pub(super) fn fixture(tag: &str) -> Fixture { let fixture = Fixture::new(tag); fixture.write("ws.go", GO_BEFORE); fixture.git(&["add", "."]); From 376f627e50614650314c00c97749528baa314001 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Tue, 24 Nov 2026 18:13:13 -0500 Subject: [PATCH 02/12] test(review): quiet the 300-notes test --- crates/plannotator-tui/src/review/tests/inline_flow.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/plannotator-tui/src/review/tests/inline_flow.rs b/crates/plannotator-tui/src/review/tests/inline_flow.rs index 505fda32..81853861 100644 --- a/crates/plannotator-tui/src/review/tests/inline_flow.rs +++ b/crates/plannotator-tui/src/review/tests/inline_flow.rs @@ -373,7 +373,6 @@ fn three_hundred_notes_lay_out_once_and_draw_only_what_shows() { check_boxes(&screen, &buffer, "300 notes"); // Debug build, 41 frames with 300 boxes set: well under a second each. assert!(started.elapsed() < Duration::from_secs(20), "{:?}", started.elapsed()); - eprintln!("41 frames with 300 notes: {:?}", started.elapsed()); } #[test] From 4f94f17014cdc9399a62ddc15d362293cfff3a90 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Tue, 24 Nov 2026 18:21:25 -0500 Subject: [PATCH 03/12] fix(review): clippy, the help row, and a wrapped suggestion's sign on its first row only --- crates/plannotator-tui/src/review/diff.rs | 27 ++++++++++----- .../plannotator-tui/src/review/diff/insets.rs | 4 +-- .../plannotator-tui/src/review/diff/place.rs | 6 ++-- crates/plannotator-tui/src/review/draw.rs | 19 +++++------ crates/plannotator-tui/src/review/inline.rs | 34 +++++++++++++++---- .../plannotator-tui/src/review/inline/card.rs | 14 +++++++- crates/plannotator-tui/src/review/overlays.rs | 15 ++------ .../src/review/tests/inline_flow.rs | 6 ++-- .../src/review/tests/inline_support.rs | 4 +-- .../src/review/tests/inline_view.rs | 14 ++++---- 10 files changed, 87 insertions(+), 56 deletions(-) diff --git a/crates/plannotator-tui/src/review/diff.rs b/crates/plannotator-tui/src/review/diff.rs index 7e9b2469..539cc596 100644 --- a/crates/plannotator-tui/src/review/diff.rs +++ b/crates/plannotator-tui/src/review/diff.rs @@ -77,9 +77,16 @@ pub(super) struct Diff { terminal_background: bool, /// The whole-file view: always unified, so no layout or split ratio applies. whole: bool, - /// Nothing moved the cursor or the view since the files were opened: the notes' boxes, - /// laid out for the first time, start from the top (`insets`). - at_start: bool, + /// Whether anything moved the cursor or the view since the files were opened: until + /// then the notes' boxes, laid out for the first time, start from the top (`insets`). + since: Since, +} + +/// What happened to the view since the files were opened. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Since { + Opened, + Moved, } impl std::fmt::Debug for Diff { @@ -128,7 +135,7 @@ impl Diff { notice: None, drawn: false, terminal_background: false, - at_start: true, + since: Since::Opened, } } @@ -162,7 +169,7 @@ impl Diff { self.paths.clear(); self.generation = next_generation(); self.drawn = false; - self.at_start = true; + self.since = Since::Opened; Ok(()) } @@ -252,7 +259,7 @@ impl Diff { } pub(super) fn run(&mut self, command: Command) -> Result<()> { - self.at_start = false; + self.since = Since::Moved; let growing = self.growing(); let effect = self.engine.execute(command)?; let step = match command { @@ -277,7 +284,9 @@ impl Diff { }; let growing = self.growing(); let acted = self.engine.handle_event(event, true)? != InputEffect::Ignored; - self.at_start &= !acted; + if acted { + self.since = Since::Moved; + } if acted { self.keep_in_hunk(growing, step)?; } @@ -360,7 +369,7 @@ impl Diff { first: lines.first, last: lines.last, }; - self.at_start = false; + self.since = Since::Moved; self.engine.select_range(range)?; Ok(()) } @@ -399,7 +408,7 @@ impl Diff { /// Put the cursor on `lines.first`. An error means the diff does not show that line. pub(super) fn reveal(&mut self, path: &str, side: Side, line: u32) -> Result<()> { let file = self.index(path).with_context(|| format!("{path} is not in the diff"))?; - self.at_start = false; + self.since = Since::Moved; self.engine.reveal(file, engine_side(side), line)?; Ok(()) } diff --git a/crates/plannotator-tui/src/review/diff/insets.rs b/crates/plannotator-tui/src/review/diff/insets.rs index b6d92ac8..f92b25b7 100644 --- a/crates/plannotator-tui/src/review/diff/insets.rs +++ b/crates/plannotator-tui/src/review/diff/insets.rs @@ -7,7 +7,7 @@ use anyhow::Result; use diffs_rs::engine::{self, DiffRowKind, Inset, InsetAnchor}; use plannotator_tui_review::Side; -use super::{Diff, engine_side}; +use super::{Diff, Since, engine_side}; pub(in crate::review) use diffs_rs::engine::InsetArea as BoxArea; @@ -61,7 +61,7 @@ impl Diff { // first line, now with the boxes: the viewer keeps the cursor's row when boxes come, // so a box under the first heading would start above the top. let in_first = self.engine.cursor_row().is_some_and(|row| row.file == 0); - if first && self.at_start && in_first && !insets.is_empty() { + if first && self.since == Since::Opened && in_first && !insets.is_empty() { self.show_heading(0)?; self.engine.execute(engine::Command::FirstSource)?; } diff --git a/crates/plannotator-tui/src/review/diff/place.rs b/crates/plannotator-tui/src/review/diff/place.rs index 05a6ca8b..a10f7c4d 100644 --- a/crates/plannotator-tui/src/review/diff/place.rs +++ b/crates/plannotator-tui/src/review/diff/place.rs @@ -7,7 +7,7 @@ use diffs_rs::engine::{Command, DiffRow, DiffRowKind, InputEffect, Side}; use diffs_rs::reading::SourceRange; use ratatui::crossterm::event::{Event, KeyModifiers, MouseButton, MouseEvent, MouseEventKind}; -use super::{Diff, Lines}; +use super::{Diff, Lines, Since}; impl Diff { /// The viewer's index of the file the cursor is in. `None` before any file arrived. @@ -85,7 +85,7 @@ impl Diff { let kind = MouseEventKind::Down(MouseButton::Left); Event::Mouse(MouseEvent { kind, column, row, modifiers: KeyModifiers::NONE }) }; - self.at_start = false; + self.since = Since::Moved; self.engine.execute(Command::ClearSelection)?; self.engine.handle_event(click(from), true)?; self.engine.execute(Command::SelectLines)?; @@ -129,7 +129,7 @@ impl Diff { if index >= self.paths.len() { return Ok(()); } - self.at_start = false; + self.since = Since::Moved; for _ in 0..=self.paths.len() { let Some(row) = self.cursor_row() else { return Ok(()) }; let command = match row.file.cmp(&index) { diff --git a/crates/plannotator-tui/src/review/draw.rs b/crates/plannotator-tui/src/review/draw.rs index 10462b14..27b55750 100644 --- a/crates/plannotator-tui/src/review/draw.rs +++ b/crates/plannotator-tui/src/review/draw.rs @@ -86,17 +86,16 @@ impl Screen { self.decide_auto(area.width, diff.width)?; self.draw_header(frame, header); let cursor_selected = self.cursor_selected(); - match &mut self.whole { - Some(whole) => whole.draw(frame, diff)?, - None => { - // The notes' boxes as the last frame's columns size them, then again for this - // frame's when those changed (a resize, a pane opened or closed, the line - // between the sides moved), drawn again before anything shows. - self.sync_boxes(); + if let Some(whole) = &mut self.whole { + whole.draw(frame, diff)?; + } else { + // The notes' boxes as the last frame's columns size them, then again for this + // frame's when those changed (a resize, a pane opened or closed, the line between + // the sides moved), drawn again before anything shows. + self.sync_boxes(); + self.diff.draw(frame, diff)?; + if self.sync_boxes() { self.diff.draw(frame, diff)?; - if self.sync_boxes() { - self.diff.draw(frame, diff)?; - } } } let (middle, code) = match self.active_diff_mut() { diff --git a/crates/plannotator-tui/src/review/inline.rs b/crates/plannotator-tui/src/review/inline.rs index 3b84bb80..b61e8760 100644 --- a/crates/plannotator-tui/src/review/inline.rs +++ b/crates/plannotator-tui/src/review/inline.rs @@ -89,12 +89,21 @@ enum Part { Whole, } -/// Where `note`'s box goes: under its last line on its side, or under its file's heading -/// (`Some(None)`). `None` for a note with no box. -fn place(note: &CodeAnnotation) -> Option> { +/// Where a box goes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Place { + /// Under this line of this side. + Line(Side, u32), + /// Under the file's heading. + Heading, +} + +/// Where `note`'s box goes: under its last line on its side, or under its file's heading. +/// `None` for a note with no box. +fn place(note: &CodeAnnotation) -> Option { match note.scope { - NoteScope::Line if notes::in_diff(note) => Some(Some((note.side, note.line_end))), - NoteScope::File if !notes::is_outdated(note) => Some(None), + NoteScope::Line if notes::in_diff(note) => Some(Place::Line(note.side, note.line_end)), + NoteScope::File if !notes::is_outdated(note) => Some(Place::Heading), _ => None, } } @@ -136,7 +145,7 @@ impl Screen { for note in order.into_iter().filter_map(|i| notes.get(i)) { let path = note.file_path.as_str(); let shown = columns.entry(path).or_insert_with(|| self.diff.box_columns(path)); - let (Some(line), Some(columns)) = (place(note), *shown) else { + let (Some(place), Some(columns)) = (place(note), *shown) else { skipped += 1; continue; }; @@ -147,6 +156,10 @@ impl Screen { } let id = self.inline.id(¬e.id); let height = self.inline.card(id, note, width, tab).height(); + let line = match place { + Place::Line(side, line) => Some((side, line)), + Place::Heading => None, + }; slots.push(Slot { id, path, line, height }); } } @@ -194,6 +207,15 @@ impl Screen { Ok(true) } + /// The key help's row for the keys on a box: edit / remove. + pub(super) fn box_help(&self) -> (String, &'static str) { + let edit = [self.keys.hint(Action::Confirm), self.keys.hint_besides(Action::Edit, keys::DIFF)]; + let edit = edit.into_iter().filter(|k| !k.is_empty()).collect::>().join(" "); + let remove = self.keys.hint_besides(Action::Remove, keys::DIFF); + let keys = [edit, remove].into_iter().filter(|k| !k.is_empty()).collect::>().join(" / "); + (keys, "on a note drawn in the diff: edit / remove it") + } + /// Where note `id`'s box was drawn in the last frame, when it was. pub(super) fn drawn_box(&self, id: &str) -> Option { let id = self.inline.ids.get(id)?; diff --git a/crates/plannotator-tui/src/review/inline/card.rs b/crates/plannotator-tui/src/review/inline/card.rs index e4eba521..ac6b78e4 100644 --- a/crates/plannotator-tui/src/review/inline/card.rs +++ b/crates/plannotator-tui/src/review/inline/card.rs @@ -48,9 +48,17 @@ impl Card { if note.kind == NoteType::Suggestion { let mut rows = Vec::new(); let mut code = |code: Option<&str>, sign: &'static str, style: Style| { + // The sign on a line's first row only, as a diff marks a wrapped line. for line in code.into_iter().flat_map(|code| code.split('\n')) { let line = Line::from(Span::styled(plain(line.trim_end_matches('\r')), style)); - split_line(&mut rows, &Span::styled(sign, style), &line, &[], text_width); + let start = rows.len(); + split_line(&mut rows, &Span::styled(" ", style), &line, &[], text_width); + if let Some(first) = rows.get_mut(start) { + let text: String = + first.line.spans.iter().map(|span| span.content.as_ref()).collect(); + let rest = text.get(2..).unwrap_or_default(); + first.line = Line::from(Span::styled(format!("{sign}{rest}"), style)); + } } }; code(note.original_code.as_deref(), "- ", Style::new().fg(palette().delete)); @@ -154,6 +162,10 @@ mod tests { assert_eq!(text(&card), ["simpler", "- let a = b;", "+ let a = c;"]); let red = card.body.get(1).and_then(|line| line.spans.first()).map(|span| span.style.fg); assert_eq!(red, Some(Some(palette().delete))); + // A long line wraps with its sign on the first row only. + let code = r#","originalCode":"abcdefghijklmnop","suggestedCode":"x""#; + let card = Card::of(¬e("suggestion", "line", "new", (3, 3), code), 14, 2); + assert_eq!(text(&card), ["- abcdefgh", " ijklmnop", "+ x"]); } #[test] diff --git a/crates/plannotator-tui/src/review/overlays.rs b/crates/plannotator-tui/src/review/overlays.rs index a7349c2b..50f45e36 100644 --- a/crates/plannotator-tui/src/review/overlays.rs +++ b/crates/plannotator-tui/src/review/overlays.rs @@ -9,7 +9,7 @@ use unicode_width::UnicodeWidthStr as _; use super::Screen; use super::input::{MENU, MenuRow}; -use crate::keys::{self, Action}; +use crate::keys::Action; use crate::theme::palette; use crate::ui::hints; @@ -118,18 +118,7 @@ impl Screen { (key(&[Action::Comment]), "comment on the selection or line"), (key(&[Action::Suggest]), "suggest code for new lines"), (key(&[Action::FileComment]), "comment on the file"), - ( - [self.keys.hint(Action::Confirm), self.keys.hint_besides(Action::Edit, keys::DIFF)] - .into_iter() - .filter(|k| !k.is_empty()) - .collect::>() - .join(" "), - "on a note drawn in the diff (settings: Notes): edit it", - ), - ( - self.keys.hint_besides(Action::Remove, keys::DIFF), - "on a note drawn in the diff: remove it", - ), + self.box_help(), (key(&[Action::WholeFile]), "the whole file as it is now, at this line"), (key(&[Action::WholeBase]), "the whole file before the change (base)"), (key(&[Action::GoToDefinition]), "go to the definition of a word on the line"), diff --git a/crates/plannotator-tui/src/review/tests/inline_flow.rs b/crates/plannotator-tui/src/review/tests/inline_flow.rs index 81853861..f6fc23b8 100644 --- a/crates/plannotator-tui/src/review/tests/inline_flow.rs +++ b/crates/plannotator-tui/src/review/tests/inline_flow.rs @@ -63,15 +63,15 @@ fn the_panel_setting_keeps_no_rows_for_notes_and_draws_as_before() { comment(&mut screen, "file0.py", Side::Old, (12, 12), "an old one"); let noted = draw(&mut screen, SIZE); assert!(screen.diff.boxes_set().is_empty(), "no rows kept"); - assert!(screen.geometry.boxes.is_empty()); + assert!(screen.geometry.boxes.is_empty(), "none drawn"); assert!(!all(¬ed).contains("comment \u{b7} L"), "no box:\n{}", all(¬ed)); // Inline and back: the diff is the one panel drew. set_notes(&mut screen, Notes::Inline); - assert!(!screen.diff.boxes_set().is_empty()); + assert!(!screen.diff.boxes_set().is_empty(), "inline keeps rows"); draw(&mut screen, SIZE); set_notes(&mut screen, Notes::Panel); let back = draw(&mut screen, SIZE); - assert!(screen.diff.boxes_set().is_empty()); + assert!(screen.diff.boxes_set().is_empty(), "panel again keeps none"); assert_eq!(pane(&screen, &back), pane(&screen, ¬ed), "panel again draws what it drew"); assert_ne!(pane(&screen, &before), pane(&screen, ¬ed), "the notes' marks"); } diff --git a/crates/plannotator-tui/src/review/tests/inline_support.rs b/crates/plannotator-tui/src/review/tests/inline_support.rs index cb299ece..f91d7835 100644 --- a/crates/plannotator-tui/src/review/tests/inline_support.rs +++ b/crates/plannotator-tui/src/review/tests/inline_support.rs @@ -88,7 +88,7 @@ pub(super) type Spot = (String, Option, Option, String); pub(super) fn spot(screen: &Screen) -> Spot { let row = screen.diff.cursor_row().expect("a cursor"); - (row.path.to_string(), row.old_line, row.new_line, format!("{:?}", row.kind)) + (row.path.clone(), row.old_line, row.new_line, format!("{:?}", row.kind)) } /// The screen row of the last frame that shows `spot`, its first part when wrapped. @@ -105,7 +105,7 @@ pub(super) fn row_of_spot(screen: &Screen, spot: &Spot) -> Option { let x = column(side.unwrap_or(Side::New)); (pane.top()..pane.bottom()).find(|&y| { screen.diff.row_at(x, y).is_some_and(|row| { - (row.path.to_string(), row.old_line, row.new_line, format!("{:?}", row.kind)) == *spot + (row.path.clone(), row.old_line, row.new_line, format!("{:?}", row.kind)) == *spot }) }) } diff --git a/crates/plannotator-tui/src/review/tests/inline_view.rs b/crates/plannotator-tui/src/review/tests/inline_view.rs index 1ec3a7f0..9e607535 100644 --- a/crates/plannotator-tui/src/review/tests/inline_view.rs +++ b/crates/plannotator-tui/src/review/tests/inline_view.rs @@ -73,10 +73,10 @@ enum At { /// How many notes the review has before the first step. #[derive(Debug, Clone, Copy)] -enum Many { +enum Count { None, One, - Many, + Several, } /// What a frame shows: the cursor's line and row, and the code's columns. @@ -159,14 +159,14 @@ fn near(screen: &Screen, delta: i64) -> u32 { (i64::from(line) + delta).clamp(58, 142) as u32 } -fn notes(screen: &mut Screen, many: Many) { +fn notes(screen: &mut Screen, many: Count) { match many { - Many::None => {} - Many::One => { + Count::None => {} + Count::One => { let line = near(screen, -2); comment(screen, PATH, Side::New, (line, line), "one note here"); } - Many::Many => { + Count::Several => { keys(screen, "C"); type_and_save(screen, "about the whole file"); for (side, lines, text) in [ @@ -374,7 +374,7 @@ fn drag_over(screen: &mut Screen) { fn every_step(name: &str, layout: &str) { for wrap in [false, true] { for at in [At::Top, At::Middle, At::LastPage] { - for many in [Many::None, Many::One, Many::Many] { + for many in [Count::None, Count::One, Count::Several] { let case = format!("{name} wrap {wrap} {at:?} {many:?}"); let tag = format!("inline-view-{}-{wrap}-{at:?}-{many:?}", name.replace([' ', ':'], "-")); let (fixture, mut screen) = kotlin(&tag, &format!("{layout}\nwrap = {wrap}")); From c0052757baf8b914a5ddbdfaad8e3794fc5b5ed7 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Tue, 24 Nov 2026 18:25:40 -0500 Subject: [PATCH 04/12] fix(review): hint_besides is the code review's, which Windows does not build --- crates/plannotator-tui/src/keys.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/plannotator-tui/src/keys.rs b/crates/plannotator-tui/src/keys.rs index 3feeaf3b..97eb40d2 100644 --- a/crates/plannotator-tui/src/keys.rs +++ b/crates/plannotator-tui/src/keys.rs @@ -648,6 +648,7 @@ impl Keymap { /// The action's first key that no action of `context` takes, as the hints spell it; /// empty when there is none. + #[cfg_attr(not(unix), allow(dead_code, reason = "only the code review, Unix-only, asks"))] pub(crate) fn hint_besides(&self, action: Action, context: &[Action]) -> String { let taken = |key: &Key| context.iter().any(|&other| other != action && self.keys(other).contains(key)); From a9a181d44cae2bd18549090432aa05a024b9d186 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Wed, 25 Nov 2026 11:09:36 -0500 Subject: [PATCH 05/12] feat(review): side-by-side boxes in a split diff, on diffs-rs's inset spans Boxes over one side sit side by side under their row; a narrow side or a file's note spans both. Widths come from the viewer before drawing, so the hand-built split geometry and the opening workaround go. Suggested code loses its shared indentation and breaks after punctuation; a new comment lines up with the boxes; on a box, h/l move to the box beside. --- Cargo.lock | 8 +- .../plannotator-tui/src/review/compose_at.rs | 8 +- crates/plannotator-tui/src/review/diff.rs | 28 ++--- .../plannotator-tui/src/review/diff/insets.rs | 61 ++++------ .../plannotator-tui/src/review/diff/place.rs | 4 +- crates/plannotator-tui/src/review/inline.rs | 78 +++++++----- .../plannotator-tui/src/review/inline/card.rs | 29 ++--- .../src/review/inline/card/code.rs | 111 ++++++++++++++++++ .../src/review/inline/paint.rs | 12 +- .../src/review/tests/inline_flow.rs | 105 +++++++++++++++-- .../src/review/tests/inline_support.rs | 10 +- .../src/review/tests/inline_view.rs | 8 +- 12 files changed, 317 insertions(+), 145 deletions(-) create mode 100644 crates/plannotator-tui/src/review/inline/card/code.rs diff --git a/Cargo.lock b/Cargo.lock index caf72620..93d6a4b3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -524,7 +524,7 @@ checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" [[package]] name = "diffs-fancy-regex" version = "0.1.0" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#8eac7f92607632e293500ca1fdcd08a6c27b70ba" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#50c794cf6a4ac5e2dc639dab64c4bf170e9f0737" dependencies = [ "bit-set 0.8.0", "regex-automata", @@ -534,7 +534,7 @@ dependencies = [ [[package]] name = "diffs-rs" version = "0.2.5" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#8eac7f92607632e293500ca1fdcd08a6c27b70ba" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#50c794cf6a4ac5e2dc639dab64c4bf170e9f0737" dependencies = [ "anyhow", "clap", @@ -560,7 +560,7 @@ dependencies = [ [[package]] name = "diffs-syntect" version = "0.1.0" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#8eac7f92607632e293500ca1fdcd08a6c27b70ba" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#50c794cf6a4ac5e2dc639dab64c4bf170e9f0737" dependencies = [ "bincode", "diffs-fancy-regex", @@ -580,7 +580,7 @@ dependencies = [ [[package]] name = "diffs-two-face" version = "0.1.0" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#8eac7f92607632e293500ca1fdcd08a6c27b70ba" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#50c794cf6a4ac5e2dc639dab64c4bf170e9f0737" dependencies = [ "diffs-syntect", "serde", diff --git a/crates/plannotator-tui/src/review/compose_at.rs b/crates/plannotator-tui/src/review/compose_at.rs index 2c98f515..35df22ab 100644 --- a/crates/plannotator-tui/src/review/compose_at.rs +++ b/crates/plannotator-tui/src/review/compose_at.rs @@ -65,7 +65,14 @@ impl Screen { let anchor = self.anchor(draft); // Where the viewer drew the line between a split diff's sides, wherever it was dragged. let middle = self.active_diff().filter(|diff| diff.split()).and_then(super::diff::Diff::split_line); + let boxes = self.notes_inline() && self.whole.is_none(); let (x, width) = match &anchor { + // Where the notes' boxes are drawn, the box lines up with them. + Anchor::Lines(lines) + if let Some(columns) = boxes.then(|| self.box_columns(pane, lines)).flatten() => + { + columns + } Anchor::Lines(lines) => columns(pane, middle, lines.side), Anchor::File(_) | Anchor::Centre => (pane.x, pane.width.min(MAX_WIDTH)), Anchor::Over(rect) => (rect.x, rect.width), @@ -78,7 +85,6 @@ impl Screen { return Rect { x, y, width, height: wanted.min(pane.bottom() - y) }; } let diff = self.active_diff(); - let boxes = self.notes_inline() && self.whole.is_none(); let rows = match &anchor { Anchor::Lines(lines) => diff.and_then(|diff| diff.rows_showing(lines)).map(|(first, last)| { let at_first = diff.and_then(|diff| diff.line_on(lines.side).ok().flatten()); diff --git a/crates/plannotator-tui/src/review/diff.rs b/crates/plannotator-tui/src/review/diff.rs index 539cc596..540a8d1a 100644 --- a/crates/plannotator-tui/src/review/diff.rs +++ b/crates/plannotator-tui/src/review/diff.rs @@ -26,7 +26,7 @@ mod sections; mod settings; mod whitespace; -pub(super) use insets::{Columns, Slot}; +pub(super) use insets::Slot; use sections::Sections; use settings::{layout, options}; @@ -77,16 +77,6 @@ pub(super) struct Diff { terminal_background: bool, /// The whole-file view: always unified, so no layout or split ratio applies. whole: bool, - /// Whether anything moved the cursor or the view since the files were opened: until - /// then the notes' boxes, laid out for the first time, start from the top (`insets`). - since: Since, -} - -/// What happened to the view since the files were opened. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Since { - Opened, - Moved, } impl std::fmt::Debug for Diff { @@ -135,7 +125,6 @@ impl Diff { notice: None, drawn: false, terminal_background: false, - since: Since::Opened, } } @@ -169,7 +158,6 @@ impl Diff { self.paths.clear(); self.generation = next_generation(); self.drawn = false; - self.since = Since::Opened; Ok(()) } @@ -259,7 +247,6 @@ impl Diff { } pub(super) fn run(&mut self, command: Command) -> Result<()> { - self.since = Since::Moved; let growing = self.growing(); let effect = self.engine.execute(command)?; let step = match command { @@ -284,9 +271,6 @@ impl Diff { }; let growing = self.growing(); let acted = self.engine.handle_event(event, true)? != InputEffect::Ignored; - if acted { - self.since = Since::Moved; - } if acted { self.keep_in_hunk(growing, step)?; } @@ -335,7 +319,13 @@ impl Diff { /// The side the cursor is on. pub(super) fn cursor_side(&self) -> Result> { - Ok(self.engine.selected_source()?.map(|at| side_of(at.side))) + if let Some(at) = self.engine.selected_source()? { + return Ok(Some(side_of(at.side))); + } + // On a note's box: the side it is over. + let on_box = + self.engine.cursor_row().filter(|row| matches!(row.kind, engine::DiffRowKind::Inset { .. })); + Ok(on_box.map(|row| side_of(row.side))) } /// The cursor's line on `side`, with its file: `None` on a header, a gap, or a row that @@ -369,7 +359,6 @@ impl Diff { first: lines.first, last: lines.last, }; - self.since = Since::Moved; self.engine.select_range(range)?; Ok(()) } @@ -408,7 +397,6 @@ impl Diff { /// Put the cursor on `lines.first`. An error means the diff does not show that line. pub(super) fn reveal(&mut self, path: &str, side: Side, line: u32) -> Result<()> { let file = self.index(path).with_context(|| format!("{path} is not in the diff"))?; - self.since = Since::Moved; self.engine.reveal(file, engine_side(side), line)?; Ok(()) } diff --git a/crates/plannotator-tui/src/review/diff/insets.rs b/crates/plannotator-tui/src/review/diff/insets.rs index f92b25b7..683a6010 100644 --- a/crates/plannotator-tui/src/review/diff/insets.rs +++ b/crates/plannotator-tui/src/review/diff/insets.rs @@ -4,38 +4,30 @@ //! is safe at any time. use anyhow::Result; -use diffs_rs::engine::{self, DiffRowKind, Inset, InsetAnchor}; +use diffs_rs::engine::{DiffRowKind, Inset, InsetAnchor, InsetSpan}; use plannotator_tui_review::Side; +use ratatui::layout::Rect; -use super::{Diff, Since, engine_side}; +use super::{Diff, engine_side}; pub(in crate::review) use diffs_rs::engine::InsetArea as BoxArea; -/// Rows kept for one box: under `line` of `side`, or under the file's heading (`None`). +/// Rows kept for one box: under `line` of `side`, or under the file's heading (`None`); in +/// a split diff over the column of `over`'s side, or across both sides (`None`). #[derive(Debug, Clone, PartialEq, Eq)] pub(in crate::review) struct Slot<'a> { pub(in crate::review) id: u64, pub(in crate::review) path: &'a str, pub(in crate::review) line: Option<(Side, u32)>, + pub(in crate::review) over: Option, pub(in crate::review) height: u16, } -/// The columns a box in one file can draw in, as the last frame laid them out. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(in crate::review) struct Columns { - /// The code column of each side; unified, the one code column twice. - pub(in crate::review) old: u16, - pub(in crate::review) new: u16, - /// From the old side's code to the diff's right edge; unified, the code column. - pub(in crate::review) whole: u16, - /// Split, each side's pane, its gutter included; `None` unified. - pub(in crate::review) panes: Option<(u16, u16)>, -} - impl Diff { - /// Keep rows for `slots`, in their order where several share a row. Slots in files the - /// viewer does not have (not arrived, filtered out) keep none until the next call. True - /// when the set changed; the same set again changes nothing. + /// Keep rows for `slots`, in their order where several share a row: in a split diff, + /// side-by-side when they are over one side each. Slots in files the viewer does not have + /// (not arrived, filtered out) keep none until the next call. True when the set changed; + /// the same set again changes nothing. pub(in crate::review) fn set_boxes(&mut self, slots: &[Slot<'_>]) -> Result { let review = self.engine.review_id(); let index: std::collections::HashMap<&str, usize> = @@ -49,22 +41,13 @@ impl Diff { Some(_) => return None, None => InsetAnchor::FileHeading, }; - Some(Inset { review, id: slot.id, file, anchor, height: slot.height }) + Some(Inset { review, id: slot.id, file, anchor, span: span(slot.over), height: slot.height }) }) .collect(); if self.engine.insets() == insets.as_slice() { return Ok(false); } - let first = self.engine.insets().is_empty(); self.engine.set_insets(&insets)?; - // The view as the diff opened, its first heading at the top and the cursor on its - // first line, now with the boxes: the viewer keeps the cursor's row when boxes come, - // so a box under the first heading would start above the top. - let in_first = self.engine.cursor_row().is_some_and(|row| row.file == 0); - if first && self.since == Since::Opened && in_first && !insets.is_empty() { - self.show_heading(0)?; - self.engine.execute(engine::Command::FirstSource)?; - } Ok(true) } @@ -79,19 +62,11 @@ impl Diff { self.engine.hidden_insets() } - /// The columns a box in the file at `path` has, as the last frame laid them out. `None` - /// before the first frame and for a file the viewer does not have. - pub(in crate::review) fn box_columns(&self, path: &str) -> Option { - let file = self.index(path)?; - let old = self.engine.inset_width(file, engine::Side::Old)?; - let new = self.engine.inset_width(file, engine::Side::New)?; - // Split, the viewer's box runs from the old side's code over the line between the - // sides to the right edge: the old code column, then all of the new side's pane. - let Some(line) = self.split_line() else { - return Some(Columns { old, new, whole: new, panes: None }); - }; - let (left, right) = (line.saturating_sub(self.area.x), self.area.right().saturating_sub(line + 1)); - Some(Columns { old, new, whole: old + 1 + right, panes: Some((left, right)) }) + /// The width a box in the file at `path` has over `over`'s side (across the diff for + /// `None`), in a frame drawn into `area` with the settings as they are now. `None` for a + /// file the viewer does not have and an area too small for the diff. + pub(in crate::review) fn box_width(&self, area: Rect, path: &str, over: Option) -> Option { + self.engine.inset_width_in(area, self.index(path)?, span(over)) } /// The box the cursor is on, by id. @@ -122,6 +97,10 @@ impl Diff { } } +fn span(over: Option) -> InsetSpan { + over.map_or(InsetSpan::Full, |side| InsetSpan::Side(engine_side(side))) +} + #[cfg(test)] impl Diff { /// The viewer's boxes as set, for tests. diff --git a/crates/plannotator-tui/src/review/diff/place.rs b/crates/plannotator-tui/src/review/diff/place.rs index a10f7c4d..357dc7a6 100644 --- a/crates/plannotator-tui/src/review/diff/place.rs +++ b/crates/plannotator-tui/src/review/diff/place.rs @@ -7,7 +7,7 @@ use diffs_rs::engine::{Command, DiffRow, DiffRowKind, InputEffect, Side}; use diffs_rs::reading::SourceRange; use ratatui::crossterm::event::{Event, KeyModifiers, MouseButton, MouseEvent, MouseEventKind}; -use super::{Diff, Lines, Since}; +use super::{Diff, Lines}; impl Diff { /// The viewer's index of the file the cursor is in. `None` before any file arrived. @@ -85,7 +85,6 @@ impl Diff { let kind = MouseEventKind::Down(MouseButton::Left); Event::Mouse(MouseEvent { kind, column, row, modifiers: KeyModifiers::NONE }) }; - self.since = Since::Moved; self.engine.execute(Command::ClearSelection)?; self.engine.handle_event(click(from), true)?; self.engine.execute(Command::SelectLines)?; @@ -129,7 +128,6 @@ impl Diff { if index >= self.paths.len() { return Ok(()); } - self.since = Since::Moved; for _ in 0..=self.paths.len() { let Some(row) = self.cursor_row() else { return Ok(()) }; let command = match row.file.cmp(&index) { diff --git a/crates/plannotator-tui/src/review/inline.rs b/crates/plannotator-tui/src/review/inline.rs index b61e8760..c42b0a5a 100644 --- a/crates/plannotator-tui/src/review/inline.rs +++ b/crates/plannotator-tui/src/review/inline.rs @@ -30,7 +30,7 @@ use plannotator_tui_review::{CodeAnnotation, NoteScope, Side}; use ratatui::crossterm::event::KeyEvent; use super::compose_at::{MAX_WIDTH, MIN_SIDE_WIDTH}; -use super::diff::{Columns, Slot}; +use super::diff::{Lines, Slot}; use super::{Screen, notes}; use crate::config::review::Notes; use crate::keys::{self, Action}; @@ -80,15 +80,6 @@ impl Inline { } } -/// Which of a box's columns it draws in. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Part { - Old, - New, - /// Across the diff: a file's note, or a side too narrow for the box. - Whole, -} - /// Where a box goes. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Place { @@ -108,20 +99,27 @@ fn place(note: &CodeAnnotation) -> Option { } } -/// The columns `note`'s box draws in, and its width there. -fn part(note: &CodeAnnotation, columns: Columns) -> (Part, u16) { - let part = match (note.scope, columns.panes) { - (NoteScope::Line, None) => Part::New, - (NoteScope::Line, Some((old, _))) if note.side == Side::Old && old >= MIN_SIDE_WIDTH => Part::Old, - (NoteScope::Line, Some((_, new))) if note.side == Side::New && new >= MIN_SIDE_WIDTH => Part::New, - _ => Part::Whole, - }; - let width = match part { - Part::Old => columns.old, - Part::New => columns.new, - Part::Whole => columns.whole, - }; - (part, width.min(MAX_WIDTH)) +/// The widths a box in one file can have: over the old side, over the new side, across. +type Widths = [Option; 3]; + +/// The width of a box over `over`'s side, or across for `None`. +fn width(widths: Widths, over: Option) -> Option { + let [old, new, across] = widths; + match over { + Some(Side::Old) => old, + Some(Side::New) => new, + None => across, + } +} + +/// Which side a box at `place` sits over in a split diff, `None` across both: its own side +/// when that side's column is wide enough for the comment box (`compose_at`'s rule), and +/// across for a file's note. Unified, every box is across. +fn over(place: Place, split: bool, widths: Widths) -> Option { + let Place::Line(side, _) = place else { return None }; + let [old, new, _] = widths; + let width = if side == Side::Old { old } else { new }; + (split && width.is_some_and(|w| w >= MIN_SIDE_WIDTH)).then_some(side) } impl Screen { @@ -139,17 +137,22 @@ impl Screen { let mut skipped = 0; if self.settings.now.notes != Notes::Panel { let tab = self.settings.now.tab_width.get(); - let mut columns: HashMap<&str, Option> = HashMap::new(); + let area = self.geometry.diff; + let split = self.diff.split(); + let mut widths: HashMap<&str, Widths> = HashMap::new(); let mut order: Vec = (0..notes.len()).collect(); order.sort_by_key(|&i| (notes.get(i).map_or(0, |note| note.created_at), i)); for note in order.into_iter().filter_map(|i| notes.get(i)) { let path = note.file_path.as_str(); - let shown = columns.entry(path).or_insert_with(|| self.diff.box_columns(path)); - let (Some(place), Some(columns)) = (place(note), *shown) else { + let widths = *widths.entry(path).or_insert_with(|| { + [Some(Side::Old), Some(Side::New), None].map(|over| self.diff.box_width(area, path, over)) + }); + let Some(place) = place(note) else { skipped += 1; continue; }; - let (_, width) = part(note, columns); + let over = over(place, split, widths); + let width = width(widths, over).unwrap_or(0).min(MAX_WIDTH); if width < MIN_WIDTH { skipped += 1; continue; @@ -160,7 +163,7 @@ impl Screen { Place::Line(side, line) => Some((side, line)), Place::Heading => None, }; - slots.push(Slot { id, path, line, height }); + slots.push(Slot { id, path, line, over, height }); } } self.inline.skipped = skipped; @@ -173,6 +176,23 @@ impl Screen { } } + /// The first column and width the box of a note on `lines` would have in `pane`, for the + /// comment box to line up with the boxes. `None` when it would get none. + pub(super) fn box_columns(&self, pane: ratatui::layout::Rect, lines: &Lines) -> Option<(u16, u16)> { + let split = self.diff.split(); + let widths = + [Some(Side::Old), Some(Side::New), None].map(|over| self.diff.box_width(pane, &lines.path, over)); + let over = over(Place::Line(lines.side, lines.last), split, widths); + let full = width(widths, over)?; + // Every box ends at the pane's right edge but one over the old side, which ends at + // the line between the sides. + let right = match over { + Some(Side::Old) => self.diff.split_line()?, + _ => pane.right(), + }; + Some((right.checked_sub(full)?, full.min(MAX_WIDTH))).filter(|&(_, width)| width >= MIN_WIDTH) + } + /// How many notes have no box in the diff now, for the footer. pub(super) fn notes_not_inline(&self) -> usize { if !self.notes_inline() { diff --git a/crates/plannotator-tui/src/review/inline/card.rs b/crates/plannotator-tui/src/review/inline/card.rs index ac6b78e4..5fa64dc4 100644 --- a/crates/plannotator-tui/src/review/inline/card.rs +++ b/crates/plannotator-tui/src/review/inline/card.rs @@ -3,14 +3,16 @@ //! the lines it replaces and the code it suggests as `-` and `+` lines. At most //! [`BODY_LINES`] lines show; the box says when there is more, which opening the note shows. +mod code; + use std::hash::{Hash as _, Hasher as _}; use plannotator_tui_review::{CodeAnnotation, NoteScope, NoteType, Side}; use ratatui::style::Style; -use ratatui::text::{Line, Span}; +use ratatui::text::Line; use crate::theme::palette; -use crate::wrap::{split_line, wrap_line}; +use crate::wrap::wrap_line; /// The most lines of text a box shows. pub(super) const BODY_LINES: usize = 6; @@ -46,24 +48,9 @@ impl Card { } } if note.kind == NoteType::Suggestion { - let mut rows = Vec::new(); - let mut code = |code: Option<&str>, sign: &'static str, style: Style| { - // The sign on a line's first row only, as a diff marks a wrapped line. - for line in code.into_iter().flat_map(|code| code.split('\n')) { - let line = Line::from(Span::styled(plain(line.trim_end_matches('\r')), style)); - let start = rows.len(); - split_line(&mut rows, &Span::styled(" ", style), &line, &[], text_width); - if let Some(first) = rows.get_mut(start) { - let text: String = - first.line.spans.iter().map(|span| span.content.as_ref()).collect(); - let rest = text.get(2..).unwrap_or_default(); - first.line = Line::from(Span::styled(format!("{sign}{rest}"), style)); - } - } - }; - code(note.original_code.as_deref(), "- ", Style::new().fg(palette().delete)); - code(note.suggested_code.as_deref(), "+ ", Style::new().fg(palette().looks_good)); - body.extend(rows.into_iter().map(|row| row.line)); + let styles = (Style::new().fg(palette().delete), Style::new().fg(palette().looks_good)); + let (old, new) = (note.original_code.as_deref(), note.suggested_code.as_deref()); + body.extend(code::rows(old, new, text_width, usize::from(tab), styles)); } let more = body.len() > BODY_LINES; body.truncate(BODY_LINES); @@ -159,7 +146,7 @@ mod tests { let code = r#","text":"simpler","originalCode":"\tlet a = b;","suggestedCode":"\tlet a = c;""#; let suggestion = note("suggestion", "line", "new", (3, 3), code); let card = Card::of(&suggestion, 40, 2); - assert_eq!(text(&card), ["simpler", "- let a = b;", "+ let a = c;"]); + assert_eq!(text(&card), ["simpler", "- let a = b;", "+ let a = c;"]); let red = card.body.get(1).and_then(|line| line.spans.first()).map(|span| span.style.fg); assert_eq!(red, Some(Some(palette().delete))); // A long line wraps with its sign on the first row only. diff --git a/crates/plannotator-tui/src/review/inline/card/code.rs b/crates/plannotator-tui/src/review/inline/card/code.rs new file mode 100644 index 00000000..742827bd --- /dev/null +++ b/crates/plannotator-tui/src/review/inline/card/code.rs @@ -0,0 +1,111 @@ +//! A suggestion's code in a note's box: the lines it replaces as `-` lines, then the code it +//! suggests as `+` lines, with the indentation they all share taken off so the code gets the +//! width. A line too long for the box breaks after a space or punctuation near the end of +//! the row when there is one, else where the row is full; its sign is on its first row only. + +use ratatui::style::Style; +use ratatui::text::{Line, Span}; +use unicode_width::UnicodeWidthChar as _; + +/// How far back from a full row a break after a space or punctuation is looked for. +const LOOK_BACK: usize = 12; + +/// The `-` and `+` rows for `original` and `suggested`, `width` columns wide, tabs `tab` +/// columns. +pub(super) fn rows( + original: Option<&str>, + suggested: Option<&str>, + width: usize, + tab: usize, + (old, new): (Style, Style), +) -> Vec> { + let tabs = " ".repeat(tab); + let lines = |code: Option<&str>, sign: &'static str, style: Style| { + code.into_iter() + .flat_map(|code| code.split('\n')) + .map(|line| (sign, style, line.trim_end_matches('\r').replace('\t', &tabs))) + .collect::>() + }; + let mut all = lines(original, "- ", old); + all.extend(lines(suggested, "+ ", new)); + let indent = all + .iter() + .filter(|(_, _, line)| !line.trim().is_empty()) + .map(|(_, _, line)| line.len() - line.trim_start_matches(' ').len()) + .min() + .unwrap_or(0); + let room = width.saturating_sub(2).max(1); + let mut rows = Vec::new(); + for (sign, style, line) in all { + let line = line.get(indent..).unwrap_or_default(); + for (index, piece) in pieces(line, room).into_iter().enumerate() { + let lead = if index == 0 { sign } else { " " }; + rows.push(Line::from(Span::styled(format!("{lead}{piece}"), style))); + } + } + rows +} + +/// `line` in rows of at most `room` columns, every character kept. +fn pieces(line: &str, room: usize) -> Vec { + let mut rows = Vec::new(); + let mut rest: Vec = line.chars().collect(); + loop { + let mut used = 0; + let mut fits = 0; + for &ch in &rest { + let wide = ch.width().unwrap_or(0); + if used + wide > room && fits > 0 { + break; + } + used += wide; + fits += 1; + } + if fits >= rest.len() { + rows.push(rest.into_iter().collect()); + return rows; + } + let soft = (fits.saturating_sub(LOOK_BACK).max(1)..fits).rev().find(|&cut| { + rest.get(cut - 1).is_some_and(|&ch| ch == ' ' || (ch.is_ascii_punctuation() && ch != '_')) + }); + let cut = soft.unwrap_or(fits); + let tail = rest.split_off(cut); + rows.push(rest.into_iter().collect()); + rest = tail; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn text(rows: &[Line<'_>]) -> Vec { + rows.iter().map(|row| row.spans.iter().map(|span| span.content.as_ref()).collect()).collect() + } + + #[test] + fn the_shared_indentation_goes_and_long_lines_break_after_punctuation() { + let styles = (Style::new(), Style::new()); + let old = " if ready {\n send(Error::from(e));\n }"; + let new = " if ready { send(Error::Route(e)) }"; + let rows = rows(Some(old), Some(new), 22, 4, styles); + assert_eq!( + text(&rows), + [ + "- if ready {", + "- send(Error::", + " from(e));", + "- }", + "+ if ready { send(", + " Error::Route(e)) }" + ] + ); + } + + #[test] + fn a_line_with_no_break_near_the_end_breaks_where_the_row_is_full() { + assert_eq!(pieces("abcdefghijklmnopqrstuvwxyz", 10), ["abcdefghij", "klmnopqrst", "uvwxyz"]); + assert_eq!(pieces("", 10), [""]); + assert_eq!(pieces("a b", 1), ["a", " ", "b"]); + } +} diff --git a/crates/plannotator-tui/src/review/inline/paint.rs b/crates/plannotator-tui/src/review/inline/paint.rs index d8baa00a..936a4a9d 100644 --- a/crates/plannotator-tui/src/review/inline/paint.rs +++ b/crates/plannotator-tui/src/review/inline/paint.rs @@ -9,8 +9,8 @@ use ratatui::style::{Color, Style}; use ratatui::text::{Line, Span}; use ratatui::widgets::{Block, BorderType, Borders, Paragraph, Widget as _}; +use super::super::compose_at::MAX_WIDTH; use super::card::Card; -use super::{Part, part}; use crate::keys::Action; use crate::review::Screen; use crate::theme::palette; @@ -39,14 +39,8 @@ impl Screen { else { continue; }; - let Some(columns) = self.diff.box_columns(¬e.file_path) else { continue }; - let (part, width) = part(note, columns); - let rect = match part { - Part::Old => area.left, - Part::New => area.right, - Part::Whole => area.area, - }; - let rect = Rect { width: width.min(rect.width), ..rect }; + let width = area.area.width.min(MAX_WIDTH); + let rect = Rect { width, ..area.area }; let look = Look { sent: !self.store.is_pending(note), cursor: area.cursor }; let card = self.inline.card(area.id, note, width, tab); paint(frame.buffer_mut(), rect, area.clipped_top, card, look, &more); diff --git a/crates/plannotator-tui/src/review/tests/inline_flow.rs b/crates/plannotator-tui/src/review/tests/inline_flow.rs index f6fc23b8..26563e5a 100644 --- a/crates/plannotator-tui/src/review/tests/inline_flow.rs +++ b/crates/plannotator-tui/src/review/tests/inline_flow.rs @@ -111,30 +111,116 @@ fn boxes_hang_under_their_notes_last_line_on_its_side_in_the_order_made() { } #[test] -fn split_a_box_sits_over_its_sides_half_or_across_when_that_half_is_narrow() { +fn split_boxes_sit_side_by_side_over_their_sides_or_across_when_a_side_is_narrow() { let (_fixture, mut screen) = opened("inline-split", "layout = \"split\"\nnotes = \"inline\""); comment(&mut screen, "file0.py", Side::Old, (12, 12), "old side note"); comment(&mut screen, "file0.py", Side::New, (12, 12), "new side note"); + comment(&mut screen, "file0.py", Side::Old, (12, 12), "second old note"); let buffer = draw(&mut screen, SIZE); check_boxes(&screen, &buffer, "split 50"); let line = screen.diff.split_line().expect("split"); let old = box_saying(&screen, "old side note").expect("old"); let new = box_saying(&screen, "new side note").expect("new"); + let second = box_saying(&screen, "second old note").expect("second"); assert!(old.right() <= line, "the old box over the old side: {old:?} {line}"); assert!(new.x > line, "the new box over the new side: {new:?} {line}"); - assert_eq!(new.y, old.bottom(), "both hang under the row, in the order made"); - // 30:70 leaves the old side under 48 columns: its box runs across. + assert_eq!(new.y, old.y, "side by side, from the same row"); + assert_eq!((second.x, second.y), (old.x, old.bottom()), "the next old one under it"); + let pane = screen.geometry.diff; + let under = (pane.top()..pane.bottom()) + .find(|&y| screen.diff.row_at(pane.right() - 2, y).is_some_and(|row| row.new_line == Some(13))) + .expect("line 13"); + assert_eq!(under, second.bottom(), "no rows besides the block's"); + // 30:70 leaves the old side under 48 columns: its boxes run across, each its own block. keys(&mut screen, "(((("); let buffer = draw(&mut screen, SIZE); check_boxes(&screen, &buffer, "split 30"); let line = screen.diff.split_line().expect("split"); - assert!(line - screen.geometry.diff.x < 48, "narrow old side"); let old = box_saying(&screen, "old side note").expect("old"); - let area = screen.diff.box_areas().first().map(|a| a.area).expect("an area"); - assert_eq!((old.x, old.width), (area.x, area.width.min(84)), "across from the old code"); - assert!(old.right() > line); let new = box_saying(&screen, "new side note").expect("new"); - assert!(new.x > line); + let second = box_saying(&screen, "second old note").expect("second"); + assert!(old.x < line && old.right() > line, "across from the old code: {old:?} {line}"); + assert!(new.x > line && new.y == old.bottom(), "the new one over its side, below: {new:?}"); + assert_eq!(second.y, new.bottom(), "in the order made"); +} + +#[test] +fn the_cursor_stops_on_side_boxes_left_column_first_and_takes_their_side() { + let (_fixture, mut screen) = opened("inline-stops", "layout = \"split\"\nnotes = \"inline\""); + comment(&mut screen, "file0.py", Side::Old, (12, 12), "first old"); + comment(&mut screen, "file0.py", Side::New, (12, 12), "the new one"); + comment(&mut screen, "file0.py", Side::Old, (12, 12), "second old"); + screen.diff.reveal("file0.py", Side::New, 12).expect("line 12"); + draw(&mut screen, SIZE); + let side = |screen: &Screen| screen.diff.cursor_row().map(|row| row.side); + let on = |screen: &Screen| screen.cursor_note().and_then(|n| n.text.clone()); + let mut stops = Vec::new(); + for _ in 0..4 { + press(&mut screen, KeyCode::Char('j')); + draw(&mut screen, SIZE); + stops.push((on(&screen), side(&screen))); + } + let old = Some(diffs_rs::engine::Side::Old); + let new = Some(diffs_rs::engine::Side::New); + assert_eq!( + stops, + [ + (Some("first old".to_owned()), old), + (Some("second old".to_owned()), old), + (Some("the new one".to_owned()), new), + (None, new), + ], + "left column top to bottom, then the right; leaving it on the new side" + ); + assert_eq!(screen.diff.cursor_row().and_then(|row| row.new_line), Some(13)); + // Back up onto the block, then across to the box beside. + keys(&mut screen, "kkk"); + assert_eq!(on(&screen).as_deref(), Some("first old")); + press(&mut screen, KeyCode::Char('l')); + assert_eq!((on(&screen).as_deref(), side(&screen)), (Some("the new one"), new), "the box beside"); +} + +#[test] +fn a_click_on_either_of_two_boxes_side_by_side_picks_its_own_note() { + let (_fixture, mut screen) = opened("inline-click-sides", "layout = \"split\"\nnotes = \"both\""); + open_notes(&mut screen); + comment(&mut screen, "file0.py", Side::Old, (12, 12), "left note"); + comment(&mut screen, "file0.py", Side::New, (12, 12), "right note"); + draw(&mut screen, SIZE); + for text in ["right note", "left note", "right note"] { + let boxed = box_saying(&screen, text).expect("drawn"); + let at = (boxed.x + 3, boxed.y + 1); + report(&mut screen, MouseEventKind::Down(MouseButton::Left), at); + report(&mut screen, MouseEventKind::Up(MouseButton::Left), at); + draw(&mut screen, SIZE); + assert_eq!(screen.cursor_note().and_then(|n| n.text.as_deref()), Some(text)); + assert_eq!(screen.selected_note().and_then(|n| n.text.as_deref()), Some(text), "the panel"); + assert_eq!(screen.diff.selection(), None); + } +} + +#[test] +fn a_new_comment_lines_up_with_the_boxes() { + for layout in ["unified", "split"] { + let (_fixture, mut screen) = + opened("inline-compose-x", &format!("layout = \"{layout}\"\nnotes = \"inline\"")); + comment(&mut screen, "file0.py", Side::New, (12, 12), "a new-side box"); + comment(&mut screen, "file0.py", Side::Old, (14, 14), "an old-side box"); + draw(&mut screen, SIZE); + // Two lines under each box's line, on its side. + for (side, line, text) in [(Side::New, 12, "a new-side box"), (Side::Old, 14, "an old-side box")] { + screen.diff.reveal("file0.py", side, line).expect("the line"); + keys(&mut screen, "jjj"); + draw(&mut screen, SIZE); + let boxed = box_saying(&screen, text).expect("drawn"); + press(&mut screen, KeyCode::Char('c')); + let buffer = draw(&mut screen, SIZE); + let compose = the_box(&buffer, "comment on"); + assert_eq!((compose.x, compose.width), (boxed.x, boxed.width), "{layout} {side:?}"); + press(&mut screen, KeyCode::Esc); + draw(&mut screen, SIZE); + } + } } #[test] @@ -296,8 +382,9 @@ fn a_review_opened_with_notes_starts_at_the_top_with_the_first_files_box() { assert_eq!(top.kind, diffs_rs::engine::DiffRowKind::Header, "the first heading on top"); let file = box_saying(&again, "about file zero").expect("the file's box shows"); assert_eq!(file.y, pane.y + 1, "right under it"); + // The cursor where a review opens without boxes: on the first heading. let cursor = again.diff.cursor_row().expect("a cursor"); - assert_eq!((cursor.file, cursor.old_line, cursor.part), (0, Some(1), 0), "on the first line"); + assert_eq!((cursor.file, cursor.kind), (0, diffs_rs::engine::DiffRowKind::Header)); assert!(box_saying(&again, "on line one").is_some()); } diff --git a/crates/plannotator-tui/src/review/tests/inline_support.rs b/crates/plannotator-tui/src/review/tests/inline_support.rs index f91d7835..ba3bdf99 100644 --- a/crates/plannotator-tui/src/review/tests/inline_support.rs +++ b/crates/plannotator-tui/src/review/tests/inline_support.rs @@ -35,7 +35,7 @@ pub(super) fn check_boxes(screen: &Screen, buffer: &Buffer, case: &str) { && rect.bottom() <= pane.bottom() ); for y in rect.top()..rect.bottom() { - for x in [rect.left(), rect.right() - 1, pane.left(), pane.right() - 1] { + for x in [rect.left(), rect.left() + rect.width / 2, rect.right() - 1] { assert_eq!(screen.diff.box_at(x, y), Some(id), "{what}: row {y} is its own, over no code"); } } @@ -50,7 +50,7 @@ pub(super) fn check_boxes(screen: &Screen, buffer: &Buffer, case: &str) { let body = cells(buffer, rect.x, rect.y + 1, rect.width); assert!(body.contains(word), "{what}: says its note's words: {body:?}"); } - anchored(screen, note, rect.y, &what); + anchored(screen, note, rect, &what); } let bottom_cut = area.height - area.clipped_top - area.area.height; if bottom_cut == 0 { @@ -62,10 +62,10 @@ pub(super) fn check_boxes(screen: &Screen, buffer: &Buffer, case: &str) { /// The first row above screen row `y` that is no box shows the note's line, or its file's /// heading for a file note. -fn anchored(screen: &Screen, note: &CodeAnnotation, y: u16, what: &str) { +fn anchored(screen: &Screen, note: &CodeAnnotation, rect: Rect, what: &str) { let pane = screen.geometry.diff; - let column = pane.right() - 2; - let above = (pane.top()..y).rev().find(|&row| screen.diff.box_at(column, row).is_none()); + let column = rect.x + 1; + let above = (pane.top()..rect.y).rev().find(|&row| screen.diff.box_at(column, row).is_none()); let Some(above) = above else { return }; let row = screen.diff.row_at(column, above).unwrap_or_else(|| panic!("{what}: a row above")); assert_eq!(row.path, note.file_path, "{what}: under a row of its file"); diff --git a/crates/plannotator-tui/src/review/tests/inline_view.rs b/crates/plannotator-tui/src/review/tests/inline_view.rs index 9e607535..1c66108a 100644 --- a/crates/plannotator-tui/src/review/tests/inline_view.rs +++ b/crates/plannotator-tui/src/review/tests/inline_view.rs @@ -7,8 +7,8 @@ //! column it did, no row is left empty, and every box is inside its rows, over no code, under //! its own note's line, saying that note's words (`inline_support`). //! -//! The exceptions are the documented ones: at the very start of the diff the line can move -//! up; wrapping turned on or off, reading the diff again, the file filter and jumping to a +//! The exceptions are the documented ones: at the very top of the diff the top stays and the +//! cursor's line moves as boxes above it come and go; wrapping turned on or off, reading the diff again, the file filter and jumping to a //! note from the panel move the view by design (wrapping as it does with no boxes: the //! cursor's file's heading comes to the top), and there only the boxes and the columns are //! checked. @@ -139,7 +139,9 @@ fn kept(before: &Look, after: &Look, keeps: Keeps, case: &str) { Keeps::Cursor => { assert_eq!(after.cursor, before.cursor, "{case}: the cursor stays on its line"); match (before.row, after.row) { - (Some(was), Some(now)) if now < was && after.at_start => {} + // At the very top of the diff the top stays the top: boxes coming or going + // above the cursor move its line instead. + (Some(_), Some(_)) if before.at_start && after.at_start => {} (was, now) => assert_eq!( now, was, "{case}: the cursor's line keeps its screen row\nbefore:\n{}\nafter:\n{}", From 9c5258abda6173ee37ea8c6a5f849027cf52da69 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Wed, 25 Nov 2026 11:55:21 -0500 Subject: [PATCH 06/12] fix(review): undo a removed note, box keys in help only with boxes, footer and edit fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - U takes back the last note removed (from its box or the panel) as well as the last finish: the note goes back where it was, as sent as it was; the footer says "note removed · U undo" and the review menu's row "Undo remove". - The key help lists the box keys only while notes show in the diff, as two rows whose keys fit the key column. - The footer counts no notes in the whole file; a pane under 10 rows shows no boxes and says "pane too small for inline notes". - A note being edited leaves its box's rows blank under the comment box. - Tabs in a box take the comment box's four columns. - c or s on a box comments on the lines it hangs under, on its side. - A note saved on the pane's last row says "note saved · below, ↓ shows it". --- crates/plannotator-tui-review/src/store.rs | 26 ++ .../plannotator-tui-review/src/store/tests.rs | 25 ++ .../plannotator-tui/src/review/diff/insets.rs | 5 + crates/plannotator-tui/src/review/drafts.rs | 40 ++- crates/plannotator-tui/src/review/draw.rs | 1 + crates/plannotator-tui/src/review/footer.rs | 4 +- crates/plannotator-tui/src/review/inline.rs | 67 ++++- .../plannotator-tui/src/review/inline/card.rs | 42 +-- .../src/review/inline/paint.rs | 30 ++- crates/plannotator-tui/src/review/mod.rs | 4 +- crates/plannotator-tui/src/review/overlays.rs | 11 +- crates/plannotator-tui/src/review/send.rs | 46 +++- .../src/review/tests/inline_fixes.rs | 242 ++++++++++++++++++ .../src/review/tests/inline_flow.rs | 8 +- .../plannotator-tui/src/review/tests/mod.rs | 1 + crates/plannotator-tui/src/ui/compose.rs | 4 +- 16 files changed, 493 insertions(+), 63 deletions(-) create mode 100644 crates/plannotator-tui/src/review/tests/inline_fixes.rs diff --git a/crates/plannotator-tui-review/src/store.rs b/crates/plannotator-tui-review/src/store.rs index ab5a7224..f6d01ae1 100644 --- a/crates/plannotator-tui-review/src/store.rs +++ b/crates/plannotator-tui-review/src/store.rs @@ -164,6 +164,32 @@ impl ReviewStore { Ok(removed) } + /// Remove a note and hand it back with where it was, for [`Self::put_back`] to undo. + /// Its send history stays, so a note put back is as sent as it was. + pub fn take(&mut self, id: &str) -> Result> { + let Some(index) = self.record.annotations.iter().position(|n| n.id == id) else { return Ok(None) }; + let mut taken = None; + self.commit(|record| { + taken = (index < record.annotations.len()).then(|| record.annotations.remove(index)); + taken.is_some() + })?; + Ok(taken.map(|note| (index, note))) + } + + /// Put a note [`Self::take`] removed back where it was, or last when fewer notes are left. + /// A note whose id is there again stays out. Returns whether it went back. + pub fn put_back(&mut self, index: usize, note: CodeAnnotation) -> Result { + if self.find(¬e.id).is_some() { + return Ok(false); + } + self.commit(|record| { + let index = index.min(record.annotations.len()); + record.annotations.insert(index, note); + true + })?; + Ok(true) + } + /// Apply resolutions (parallel to [`Self::annotations`], as /// [`crate::Capture::resolve_all`] returns them) and save when a note moved or changed /// state. Returns whether anything changed. diff --git a/crates/plannotator-tui-review/src/store/tests.rs b/crates/plannotator-tui-review/src/store/tests.rs index 065d63f0..9fabe84e 100644 --- a/crates/plannotator-tui-review/src/store/tests.rs +++ b/crates/plannotator-tui-review/src/store/tests.rs @@ -131,6 +131,31 @@ fn a_send_is_never_dated_before_the_edits_it_covers() { assert_eq!(parse_millis(&store.deliveries()[0].at), store.annotations()[0].plannotator_tui.updated_at); } +#[test] +fn a_taken_note_goes_back_where_it_was_as_sent_as_it_was() { + let f = Fixture::new("take"); + let mut store = f.load(); + let ids = [add(&mut store, "a"), add(&mut store, "b"), add(&mut store, "c")]; + let [a, b, c] = ids.clone(); + store.record_delivery("agent", std::slice::from_ref(&b)).expect("records"); + let (index, taken) = store.take(&b).expect("saves").expect("there"); + assert_eq!((index, taken.id.as_str()), (1, b.as_str())); + assert!(store.take(&b).expect("saves").is_none(), "gone"); + let mut store = f.load(); + assert_eq!(store.annotations().len(), 2, "the removal was saved"); + assert!(store.put_back(index, taken.clone()).expect("saves")); + let ids_now: Vec<&str> = store.annotations().iter().map(|n| n.id.as_str()).collect(); + assert_eq!(ids_now, [a.as_str(), b.as_str(), c.as_str()]); + assert!(!store.is_pending(&store.annotations()[1]), "still sent"); + assert!(!store.put_back(index, taken).expect("no-op"), "never twice"); + assert_eq!(f.load().annotations().len(), 3, "and saved"); + // Fewer notes left than its place: it goes last. + let (index, last) = store.take(&c).expect("saves").expect("there"); + store.take(&a).expect("saves"); + assert!(store.put_back(index, last).expect("saves")); + assert_eq!(store.annotations().last().map(|n| n.id.clone()), Some(c)); +} + #[test] fn finishing_archives_sent_notes_and_restoring_brings_them_back() { let f = Fixture::new("archive"); diff --git a/crates/plannotator-tui/src/review/diff/insets.rs b/crates/plannotator-tui/src/review/diff/insets.rs index 683a6010..62806099 100644 --- a/crates/plannotator-tui/src/review/diff/insets.rs +++ b/crates/plannotator-tui/src/review/diff/insets.rs @@ -62,6 +62,11 @@ impl Diff { self.engine.hidden_insets() } + /// Whether box `id` keeps rows in the diff now: set, and its line shown. + pub(in crate::review) fn keeps_box(&self, id: u64) -> bool { + self.engine.insets().iter().any(|inset| inset.id == id) && !self.engine.hidden_insets().contains(&id) + } + /// The width a box in the file at `path` has over `over`'s side (across the diff for /// `None`), in a frame drawn into `area` with the settings as they are now. `None` for a /// file the viewer does not have and an area too small for the diff. diff --git a/crates/plannotator-tui/src/review/drafts.rs b/crates/plannotator-tui/src/review/drafts.rs index 1993a117..7927d30e 100644 --- a/crates/plannotator-tui/src/review/drafts.rs +++ b/crates/plannotator-tui/src/review/drafts.rs @@ -2,23 +2,39 @@ //! Enter and Delete on a note's box in the diff), and saving what the comment box holds. use anyhow::Result; -use plannotator_tui_review::{CodeAnnotation, NoteType, Side}; +use plannotator_tui_review::{CodeAnnotation, NoteScope, NoteType, Side}; use super::diff::Lines; use super::{Draft, Focus, Mode, Screen}; use crate::ui::compose::Compose; impl Screen { - /// The lines a note made now would cover: the selection, else the cursor's line. + /// The lines a note made now would cover: the selection, else the cursor's line, else + /// with the cursor on a note's box the lines it hangs under, so the new note's box + /// stacks under it. fn target_lines(&self) -> Result> { - match self.diff.selection() { - Some(lines) => Ok(Some(lines)), - None => self.diff.cursor(), + if let Some(lines) = self.diff.selection() { + return Ok(Some(lines)); } + if let Some(lines) = self.diff.cursor()? { + return Ok(Some(lines)); + } + Ok(self.cursor_note().filter(|note| note.scope == NoteScope::Line).map(|note| Lines { + path: note.file_path.clone(), + side: note.side, + first: note.line_start, + last: note.line_end, + })) } - /// `c`: comment on the selection or the cursor line. + /// `c`: comment on the selection or the cursor line; on a file note's box, on the file. pub(super) fn start_comment(&mut self) -> Result<()> { + if self.diff.selection().is_none() + && self.cursor_note().is_some_and(|note| note.scope == NoteScope::File) + { + self.start_file_comment(); + return Ok(()); + } let Some(lines) = self.target_lines()? else { self.status = Some("move the cursor onto a line of code first".into()); return Ok(()); @@ -134,8 +150,10 @@ impl Screen { self.status = Some("that file is no longer in the diff".into()); return Ok(()); }; + let id = note.id.clone(); self.add_note(note)?; self.status = Some("note saved".into()); + self.inline.saved = Some(id); Ok(()) } @@ -157,10 +175,14 @@ impl Screen { } } - /// Remove note `id`, at once, as the rail's `x` does. + /// Remove note `id`, at once, as the rail's `x` does; `undo-finish` brings it back. pub(super) fn remove_note(&mut self, id: &str) -> Result<()> { - if self.store.remove(id)? { - self.status = Some("note removed".into()); + if let Some((index, note)) = self.store.take(id)? { + self.undo.push(super::send::Undo::Removed(index, Box::new(note))); + self.status = Some(match self.keys.hint(crate::keys::Action::UndoFinish) { + key if key.is_empty() => "note removed".to_owned(), + key => format!("note removed \u{b7} {key} undo"), + }); } self.after_note_change(); if self.store.annotations().is_empty() { diff --git a/crates/plannotator-tui/src/review/draw.rs b/crates/plannotator-tui/src/review/draw.rs index 27b55750..ffafe8e3 100644 --- a/crates/plannotator-tui/src/review/draw.rs +++ b/crates/plannotator-tui/src/review/draw.rs @@ -108,6 +108,7 @@ impl Screen { let code = |y: u16| code.get(usize::from(y - diff.y)).copied().unwrap_or(true); let selected = super::mouse::tint_selection(frame.buffer_mut(), diff, middle, cursor_selected, code); self.draw_boxes(frame); + self.tell_saved_below(); if files.width > 0 { let listing = self.listing(); self.draw_files(frame, files, &listing); diff --git a/crates/plannotator-tui/src/review/footer.rs b/crates/plannotator-tui/src/review/footer.rs index 9ff821d5..ecb6bd6f 100644 --- a/crates/plannotator-tui/src/review/footer.rs +++ b/crates/plannotator-tui/src/review/footer.rs @@ -170,7 +170,9 @@ impl Screen { } // Notes drawn in the diff: the ones that are not, and where they are. let away = self.notes_not_inline(); - if away > 0 { + if self.too_small_for_boxes() { + parts.push("pane too small for inline notes".to_owned()); + } else if away > 0 { let what = if away == 1 { "1 note not shown inline".to_owned() } else { diff --git a/crates/plannotator-tui/src/review/inline.rs b/crates/plannotator-tui/src/review/inline.rs index c42b0a5a..0e6a4c50 100644 --- a/crates/plannotator-tui/src/review/inline.rs +++ b/crates/plannotator-tui/src/review/inline.rs @@ -38,6 +38,10 @@ use crate::keys::{self, Action}; /// Narrower than this a box would show next to nothing: the note gets none. const MIN_WIDTH: u16 = 12; +/// A diff pane shorter than this shows no boxes, which would leave next to no code beside +/// them (a box of one line of text takes three rows): the footer says so instead. +pub(super) const MIN_PANE_ROWS: u16 = 10; + /// The boxes' state for one review. #[derive(Debug, Default)] pub(super) struct Inline { @@ -49,6 +53,10 @@ pub(super) struct Inline { /// Notes that got no box at the last count: on the whole change, not in the diff, or /// with no room. skipped: usize, + /// The pane was too short for boxes at the last count ([`MIN_PANE_ROWS`]). + small: bool, + /// The note saved last, until the frame after: the footer says when its box is below. + pub(super) saved: Option, /// While notes show inline only, whether the panel was opened by hand. pub(super) rail: bool, /// The Notes setting the screen last followed. @@ -71,10 +79,10 @@ impl Inline { } /// The card for `note` at `width`, laid out again only when either changed. - fn card(&mut self, id: u64, note: &CodeAnnotation, width: u16, tab: u8) -> &card::Card { - let card = self.cards.entry(id).or_insert_with(|| card::Card::of(note, width, tab)); - if !card.is_for(note, width, tab) { - *card = card::Card::of(note, width, tab); + fn card(&mut self, id: u64, note: &CodeAnnotation, width: u16) -> &card::Card { + let card = self.cards.entry(id).or_insert_with(|| card::Card::of(note, width)); + if !card.is_for(note, width) { + *card = card::Card::of(note, width); } card } @@ -135,8 +143,8 @@ impl Screen { let notes = self.store.annotations(); let mut slots = Vec::new(); let mut skipped = 0; - if self.settings.now.notes != Notes::Panel { - let tab = self.settings.now.tab_width.get(); + let small = self.geometry.diff.height < MIN_PANE_ROWS; + if self.settings.now.notes != Notes::Panel && !small { let area = self.geometry.diff; let split = self.diff.split(); let mut widths: HashMap<&str, Widths> = HashMap::new(); @@ -158,7 +166,7 @@ impl Screen { continue; } let id = self.inline.id(¬e.id); - let height = self.inline.card(id, note, width, tab).height(); + let height = self.inline.card(id, note, width).height(); let line = match place { Place::Line(side, line) => Some((side, line)), Place::Heading => None, @@ -167,6 +175,7 @@ impl Screen { } } self.inline.skipped = skipped; + self.inline.small = small; match self.diff.set_boxes(&slots) { Ok(changed) => changed, Err(error) => { @@ -193,14 +202,43 @@ impl Screen { Some((right.checked_sub(full)?, full.min(MAX_WIDTH))).filter(|&(_, width)| width >= MIN_WIDTH) } - /// How many notes have no box in the diff now, for the footer. + /// How many notes have no box in the diff now, for the footer: none in the whole file, + /// which draws no boxes, nor while the pane is too short for any. pub(super) fn notes_not_inline(&self) -> usize { - if !self.notes_inline() { + if !self.notes_inline() || self.whole.is_some() || self.inline.small { return 0; } self.inline.skipped + self.diff.hidden_boxes().len() } + /// Whether the diff is too short for the notes' boxes, while there are notes to draw. + pub(super) fn too_small_for_boxes(&self) -> bool { + self.notes_inline() + && self.whole.is_none() + && self.inline.small + && !self.store.annotations().is_empty() + } + + /// After a frame: a note just saved whose box is wholly below the pane (saved on its last + /// row, say) is not scrolled to, as nothing moves the view; the footer says where it is. + pub(super) fn tell_saved_below(&mut self) { + let Some(note) = self.inline.saved.take() else { return }; + if self.whole.is_some() || !self.notes_inline() || self.status.as_deref() != Some("note saved") { + return; + } + let Some(&id) = self.inline.ids.get(¬e) else { return }; + if self.drawn_box(¬e).is_some() || !self.diff.keeps_box(id) { + return; + } + let down = KeyEvent::from(ratatui::crossterm::event::KeyCode::Down); + let key = if self.keys.is(Action::Down, &down) { + "\u{2193}".to_owned() + } else { + self.keys.hint(Action::Down) + }; + self.status = Some(format!("note saved \u{b7} below, {key} shows it")); + } + /// The note whose box the cursor is on, in the diff (not the whole file). pub(super) fn cursor_note(&self) -> Option<&CodeAnnotation> { if self.whole.is_some() || !self.notes_inline() { @@ -227,13 +265,16 @@ impl Screen { Ok(true) } - /// The key help's row for the keys on a box: edit / remove. - pub(super) fn box_help(&self) -> (String, &'static str) { + /// The key help's rows for the keys on a box, edit and remove, while notes show in the + /// diff; none in the panel's mode, whose help is as it was. + pub(super) fn box_help(&self) -> Vec<(String, &'static str)> { + if !self.notes_inline() { + return Vec::new(); + } let edit = [self.keys.hint(Action::Confirm), self.keys.hint_besides(Action::Edit, keys::DIFF)]; let edit = edit.into_iter().filter(|k| !k.is_empty()).collect::>().join(" "); let remove = self.keys.hint_besides(Action::Remove, keys::DIFF); - let keys = [edit, remove].into_iter().filter(|k| !k.is_empty()).collect::>().join(" / "); - (keys, "on a note drawn in the diff: edit / remove it") + vec![(edit, "on a note's box in the diff: edit it"), (remove, "on a note's box: remove it")] } /// Where note `id`'s box was drawn in the last frame, when it was. diff --git a/crates/plannotator-tui/src/review/inline/card.rs b/crates/plannotator-tui/src/review/inline/card.rs index 5fa64dc4..3423dc66 100644 --- a/crates/plannotator-tui/src/review/inline/card.rs +++ b/crates/plannotator-tui/src/review/inline/card.rs @@ -12,6 +12,7 @@ use ratatui::style::Style; use ratatui::text::Line; use crate::theme::palette; +use crate::ui::compose::TAB_WIDTH; use crate::wrap::wrap_line; /// The most lines of text a box shows. @@ -35,10 +36,11 @@ pub(super) struct Card { } impl Card { - /// `note` in a box `width` columns wide, its tabs `tab` columns. - pub(super) fn of(note: &CodeAnnotation, width: u16, tab: u8) -> Self { + /// `note` in a box `width` columns wide, its tabs as wide as the comment box draws them, + /// whatever the diff's tab width, so a note reads the same in both. + pub(super) fn of(note: &CodeAnnotation, width: u16) -> Self { let text_width = usize::from(width.saturating_sub(CHROME)).max(1); - let tabs = " ".repeat(usize::from(tab)); + let tabs = " ".repeat(TAB_WIDTH); let plain = |text: &str| text.replace('\t', &tabs); let mut body: Vec> = Vec::new(); if let Some(text) = note.text.as_deref().map(str::trim_end).filter(|t| !t.is_empty()) { @@ -50,7 +52,7 @@ impl Card { if note.kind == NoteType::Suggestion { let styles = (Style::new().fg(palette().delete), Style::new().fg(palette().looks_good)); let (old, new) = (note.original_code.as_deref(), note.suggested_code.as_deref()); - body.extend(code::rows(old, new, text_width, usize::from(tab), styles)); + body.extend(code::rows(old, new, text_width, TAB_WIDTH, styles)); } let more = body.len() > BODY_LINES; body.truncate(BODY_LINES); @@ -58,12 +60,12 @@ impl Card { body.push(Line::default()); } let author = note.author_name.as_deref().filter(|name| !name.is_empty()).map(str::to_owned); - Self { made_for: (revision(note, tab), width), label: label(note), author, body, more } + Self { made_for: (revision(note), width), label: label(note), author, body, more } } /// Whether this is `note`'s card at `width`, as [`Self::of`] would make it now. - pub(super) fn is_for(&self, note: &CodeAnnotation, width: u16, tab: u8) -> bool { - self.made_for == (revision(note, tab), width) + pub(super) fn is_for(&self, note: &CodeAnnotation, width: u16) -> bool { + self.made_for == (revision(note), width) } /// The rows the box takes: its text and two borders. @@ -92,12 +94,12 @@ pub(super) fn label(note: &CodeAnnotation) -> String { } /// A number that changes whenever what the box shows of `note` does. -fn revision(note: &CodeAnnotation, tab: u8) -> u64 { +fn revision(note: &CodeAnnotation) -> u64 { let mut hasher = std::collections::hash_map::DefaultHasher::new(); (¬e.text, ¬e.suggested_code, ¬e.original_code, ¬e.author_name).hash(&mut hasher); (note.kind == NoteType::Suggestion, note.scope == NoteScope::Line, note.side == Side::Old) .hash(&mut hasher); - (note.line_start, note.line_end, tab).hash(&mut hasher); + (note.line_start, note.line_end).hash(&mut hasher); hasher.finish() } @@ -131,13 +133,13 @@ mod tests { fn text_wraps_to_the_box_and_stops_after_six_lines() { let words = "word ".repeat(40); let long = note("comment", "line", "new", (1, 1), &format!(r#","text":"{words}""#)); - let card = Card::of(&long, 24, 4); + let card = Card::of(&long, 24); assert_eq!(card.body.len(), BODY_LINES); assert!(card.more); assert!(text(&card).iter().all(|line| line.chars().count() <= 20), "{:?}", text(&card)); assert_eq!(card.height(), 8); let short = note("comment", "line", "new", (1, 1), r#","text":"one\ntwo""#); - let card = Card::of(&short, 24, 4); + let card = Card::of(&short, 24); assert_eq!((text(&card), card.more), (vec!["one".to_owned(), "two".to_owned()], false)); } @@ -145,23 +147,29 @@ mod tests { fn a_suggestion_shows_its_comment_then_the_old_and_the_new_code() { let code = r#","text":"simpler","originalCode":"\tlet a = b;","suggestedCode":"\tlet a = c;""#; let suggestion = note("suggestion", "line", "new", (3, 3), code); - let card = Card::of(&suggestion, 40, 2); + let card = Card::of(&suggestion, 40); assert_eq!(text(&card), ["simpler", "- let a = b;", "+ let a = c;"]); let red = card.body.get(1).and_then(|line| line.spans.first()).map(|span| span.style.fg); assert_eq!(red, Some(Some(palette().delete))); // A long line wraps with its sign on the first row only. let code = r#","originalCode":"abcdefghijklmnop","suggestedCode":"x""#; - let card = Card::of(¬e("suggestion", "line", "new", (3, 3), code), 14, 2); + let card = Card::of(¬e("suggestion", "line", "new", (3, 3), code), 14); assert_eq!(text(&card), ["- abcdefgh", " ijklmnop", "+ x"]); } + #[test] + fn tabs_take_the_comment_boxs_four_columns() { + let tabbed = note("comment", "line", "new", (1, 1), r#","text":"a\tb""#); + assert_eq!(text(&Card::of(&tabbed, 30)), ["a b"]); + } + #[test] fn a_card_is_made_again_when_its_note_or_its_width_changes() { let mut one = note("comment", "line", "new", (1, 1), r#","text":"a""#); - let card = Card::of(&one, 30, 4); - assert!(card.is_for(&one, 30, 4)); - assert!(!card.is_for(&one, 31, 4)); + let card = Card::of(&one, 30); + assert!(card.is_for(&one, 30)); + assert!(!card.is_for(&one, 31)); one.text = Some("b".into()); - assert!(!card.is_for(&one, 30, 4)); + assert!(!card.is_for(&one, 30)); } } diff --git a/crates/plannotator-tui/src/review/inline/paint.rs b/crates/plannotator-tui/src/review/inline/paint.rs index 936a4a9d..f61cd7b7 100644 --- a/crates/plannotator-tui/src/review/inline/paint.rs +++ b/crates/plannotator-tui/src/review/inline/paint.rs @@ -29,10 +29,15 @@ impl Screen { if self.whole.is_some() || !self.notes_inline() { return; } - let tab = self.settings.now.tab_width.get(); let more = self.keys.labelled(Action::Confirm, "for more").unwrap_or_else(|| "more".to_owned()); let areas = self.diff.box_areas().to_vec(); let notes = self.store.annotations(); + // The note in the comment box: its box keeps its rows, blank, under the comment box, + // which can be shorter than the box was. + let editing = match &self.mode { + crate::review::Mode::Compose(crate::review::Draft::Edit(id)) => Some(id.as_str()), + _ => None, + }; for area in areas { let Some(note) = self.inline.notes.get(&area.id).and_then(|id| notes.iter().find(|n| n.id == *id)) @@ -41,14 +46,31 @@ impl Screen { }; let width = area.area.width.min(MAX_WIDTH); let rect = Rect { width, ..area.area }; - let look = Look { sent: !self.store.is_pending(note), cursor: area.cursor }; - let card = self.inline.card(area.id, note, width, tab); - paint(frame.buffer_mut(), rect, area.clipped_top, card, look, &more); + if editing == Some(note.id.as_str()) { + blank(frame.buffer_mut(), rect); + } else { + let look = Look { sent: !self.store.is_pending(note), cursor: area.cursor }; + let card = self.inline.card(area.id, note, width); + paint(frame.buffer_mut(), rect, area.clipped_top, card, look, &more); + } self.geometry.boxes.push((rect, area.id)); } } } +/// `rect` of `buf` empty, on the diff's background. +fn blank(buf: &mut Buffer, rect: Rect) { + for y in rect.top()..rect.bottom() { + for x in rect.left()..rect.right() { + if let Some(cell) = buf.cell_mut((x, y)) { + let bg = cell.bg; + cell.reset(); + cell.bg = bg; + } + } + } +} + /// The box for `card`, its rows from `clipped_top` on, into `rect` of `buf`. fn paint(buf: &mut Buffer, rect: Rect, clipped_top: u16, card: &Card, look: Look, more: &str) { let whole = Rect::new(0, 0, rect.width, card.height()); diff --git a/crates/plannotator-tui/src/review/mod.rs b/crates/plannotator-tui/src/review/mod.rs index abb3228a..976032dd 100644 --- a/crates/plannotator-tui/src/review/mod.rs +++ b/crates/plannotator-tui/src/review/mod.rs @@ -206,8 +206,8 @@ pub(crate) struct Screen { compose_at: Option, send_state: SendState, last_send: crate::ui::send_button::LastSend, - /// Notes the last finish archived, for undo. - undo: Vec, + /// What `undo-finish` takes back, the last first: a finish, or a removed note. + undo: Vec, status: Option, geometry: Geometry, /// A drag with the left button in the diff, until the release. diff --git a/crates/plannotator-tui/src/review/overlays.rs b/crates/plannotator-tui/src/review/overlays.rs index 50f45e36..26b979fc 100644 --- a/crates/plannotator-tui/src/review/overlays.rs +++ b/crates/plannotator-tui/src/review/overlays.rs @@ -26,7 +26,7 @@ impl Screen { format!("Resend all \u{b7} {} notes", self.store.annotations().len()) } MenuRow::Finish => format!("Finish review \u{b7} archive {sent} sent"), - MenuRow::Undo => "Undo finish".to_owned(), + MenuRow::Undo => self.undo_label().to_owned(), }; format!(" {} {label} ", self.keys.hint(row.binding())) }) @@ -88,6 +88,7 @@ impl Screen { "review menu: whole-change comment, resend all, finish, undo", ), (key(&[Action::PickTarget]), "choose the agent Send goes to"), + (key(&[Action::UndoFinish]), "undo the last note removed, or the last finish"), ( key(&[Action::PickChanges]), "pick what to review: uncommitted, unstaged, staged, a commit", @@ -118,7 +119,10 @@ impl Screen { (key(&[Action::Comment]), "comment on the selection or line"), (key(&[Action::Suggest]), "suggest code for new lines"), (key(&[Action::FileComment]), "comment on the file"), - self.box_help(), + ] + .into_iter() + .chain(self.box_help()) + .chain([ (key(&[Action::WholeFile]), "the whole file as it is now, at this line"), (key(&[Action::WholeBase]), "the whole file before the change (base)"), (key(&[Action::GoToDefinition]), "go to the definition of a word on the line"), @@ -141,7 +145,8 @@ impl Screen { ), (key(&[Action::HideViewed]), "hide viewed files, or show them again"), (key(&[Action::NarrowFiles, Action::WidenFiles]), "narrow / widen the file list"), - ], + ]) + .collect(), ), ( "file list", diff --git a/crates/plannotator-tui/src/review/send.rs b/crates/plannotator-tui/src/review/send.rs index fce2a0cf..ed728e44 100644 --- a/crates/plannotator-tui/src/review/send.rs +++ b/crates/plannotator-tui/src/review/send.rs @@ -24,6 +24,15 @@ pub(crate) struct PickThen { close: bool, } +/// One thing `undo-finish` can take back. +#[derive(Debug)] +pub(super) enum Undo { + /// The notes a finish archived. + Finish(Vec), + /// A removed note and where it was among the notes. + Removed(usize, Box), +} + impl Screen { /// The feedback text for `notes`, as the agent receives it. pub(super) fn feedback(&self, notes: &[&CodeAnnotation]) -> String { @@ -195,23 +204,44 @@ impl Screen { format!("archived {} note(s)", ids.len()) }); if !ids.is_empty() { - self.undo = ids; + self.undo.push(Undo::Finish(ids)); } self.after_note_change(); } + /// `undo-finish`: take back the last finish or removal of this session. A note comes back + /// where it was, as sent as it was, its box where it was. pub(super) fn undo_finish(&mut self) -> Result<()> { - if self.undo.is_empty() { - self.status = Some("nothing to undo".into()); - return Ok(()); + match self.undo.pop() { + None => self.status = Some("nothing to undo".into()), + Some(Undo::Finish(ids)) => { + let restored = self.store.restore_archived(&ids)?; + self.place_notes()?; + self.status = Some(format!("restored {restored} note(s)")); + self.after_note_change(); + } + Some(Undo::Removed(index, note)) => { + let id = note.id.clone(); + self.status = Some(if self.store.put_back(index, *note)? { + "note restored".to_owned() + } else { + "that note is back already".to_owned() + }); + self.after_note_change(); + self.select_note(&id); + } } - let restored = self.store.restore_archived(&std::mem::take(&mut self.undo))?; - self.place_notes()?; - self.status = Some(format!("restored {restored} note(s)")); - self.after_note_change(); Ok(()) } + /// The review menu's undo row: what it would take back. + pub(super) fn undo_label(&self) -> &'static str { + match self.undo.last() { + Some(Undo::Removed(..)) => "Undo remove", + _ => "Undo finish", + } + } + /// The Send button's words. pub(super) fn send_label(&self) -> String { let count = self.store.pending().len(); diff --git a/crates/plannotator-tui/src/review/tests/inline_fixes.rs b/crates/plannotator-tui/src/review/tests/inline_fixes.rs new file mode 100644 index 00000000..fc09e64a --- /dev/null +++ b/crates/plannotator-tui/src/review/tests/inline_fixes.rs @@ -0,0 +1,242 @@ +//! Notes drawn in the diff, after a review in the real program: a removed note comes back +//! with `U`; the key help names the box keys only while boxes show, in line with the rest; +//! the footer counts nothing in the whole file and says when the pane is too short for +//! boxes; a note being edited leaves no rows of its old box under the comment box; `c` on a +//! box comments on its lines; a note saved on the pane's last row says where its box is. + +use plannotator_tui_review::Side; +use ratatui::crossterm::event::KeyCode; + +use super::compose_near::draw; +use super::inline_flow::{SIZE, all, opened, set_notes}; +use super::inline_support::{box_saying, cells, check_boxes, comment, row_of_cursor, row_of_spot, spot}; +use super::*; +use crate::config::review::Notes; +use crate::review::{Draft, Mode}; +use crate::ui::compose::Compose; + +/// The screen row of new line `line` of file0.py in the last frame. +fn row_of_new(screen: &Screen, line: u32) -> Option { + let spot = ("file0.py".to_owned(), None, Some(line), "Code".to_owned()); + row_of_spot(screen, &spot) +} + +#[test] +fn a_removed_note_comes_back_with_u_where_it_was_as_sent_as_it_was_and_nothing_moves() { + let (_fixture, mut screen) = opened("fix-undo", "layout = \"unified\"\nnotes = \"inline\""); + comment(&mut screen, "file0.py", Side::New, (20, 20), "keep me"); + comment(&mut screen, "file0.py", Side::New, (24, 24), "after it"); + let id = screen.store.annotations().first().map(|n| n.id.clone()).expect("a note"); + screen.store.record_delivery("agent", std::slice::from_ref(&id)).expect("sent"); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "before"); + // Onto its box, and Delete. + screen.diff.reveal("file0.py", Side::New, 20).expect("line 20"); + draw(&mut screen, SIZE); + let line = row_of_new(&screen, 20).expect("line 20 on screen"); + let next = row_of_new(&screen, 21).expect("line 21 on screen"); + press(&mut screen, KeyCode::Char('j')); + assert_eq!(screen.cursor_note().map(|n| n.id.as_str()), Some(id.as_str()), "on its box"); + press(&mut screen, KeyCode::Delete); + assert_eq!(screen.status.as_deref(), Some("note removed \u{b7} U undo")); + assert_eq!(screen.store.annotations().len(), 1); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "removed"); + assert_eq!(row_of_new(&screen, 20), Some(line), "its line stays where it was"); + assert!(box_saying(&screen, "keep me").is_none()); + // The review menu's undo row says what it takes back. + keys(&mut screen, "m"); + assert!(all(&draw(&mut screen, SIZE)).contains("Undo remove")); + press(&mut screen, KeyCode::Esc); + keys(&mut screen, "U"); + assert_eq!(screen.status.as_deref(), Some("note restored")); + let notes = screen.store.annotations(); + assert_eq!(notes.first().map(|n| n.id.as_str()), Some(id.as_str()), "first again, as it was"); + assert!(notes.first().is_some_and(|n| !screen.store.is_pending(n)), "still sent"); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "restored"); + assert!(box_saying(&screen, "keep me").is_some(), "its box is back"); + assert_eq!(row_of_new(&screen, 20), Some(line), "its line did not move"); + assert!(row_of_new(&screen, 21).is_some_and(|row| row == next), "nor the line under the box"); + keys(&mut screen, "U"); + assert_eq!(screen.status.as_deref(), Some("nothing to undo")); + // From the panel too. + open_notes(&mut screen); + press(&mut screen, KeyCode::Tab); + assert_eq!(screen.focus, crate::review::Focus::Notes); + keys(&mut screen, "x"); + assert_eq!(screen.store.annotations().len(), 1); + keys(&mut screen, "U"); + assert_eq!(screen.store.annotations().len(), 2, "{:?}", screen.status); +} + +#[test] +fn the_key_help_names_the_box_keys_only_while_boxes_show_in_line_with_the_rest() { + let help = |screen: &mut Screen| { + keys(screen, "?"); + let text = all(&draw(screen, SIZE)); + press(screen, KeyCode::Esc); + text + }; + let (_fixture, mut screen) = opened("fix-help", "layout = \"unified\""); + let panel = help(&mut screen); + assert!(panel.contains("comment on the file") && !panel.contains("note's box"), "{panel}"); + set_notes(&mut screen, Notes::Inline); + let inline = help(&mut screen); + let column = |what: &str| { + inline.lines().find_map(|row| { + let at = row.find(what)?; + Some(row.get(..at)?.chars().count()) + }) + }; + let edit = column("on a note's box in the diff: edit it").expect("the edit row"); + let remove = column("on a note's box: remove it").expect("the remove row"); + let file = column("comment on the file").expect("a row beside"); + assert_eq!((edit, remove), (file, file), "lined up with the rows around:\n{inline}"); +} + +#[test] +fn the_footer_counts_nothing_in_the_whole_file_and_says_when_the_pane_is_too_short() { + let (_fixture, mut screen) = opened("fix-small", "layout = \"unified\"\nnotes = \"inline\""); + comment(&mut screen, "file0.py", Side::New, (20, 20), "a box"); + keys(&mut screen, "M"); + type_and_save(&mut screen, "on everything"); + let text = all(&draw(&mut screen, SIZE)); + assert!(text.contains("1 note not shown inline"), "{text}"); + keys(&mut screen, "o"); + assert!(screen.whole.is_some(), "the whole file"); + let text = all(&draw(&mut screen, SIZE)); + assert!(!text.contains("not shown inline"), "{text}"); + keys(&mut screen, "o"); + draw(&mut screen, SIZE); + // The cursor on line 20, its box under it. + screen.diff.reveal("file0.py", Side::New, 20).expect("line 20"); + draw(&mut screen, SIZE); + let line = row_of_new(&screen, 20).expect("on screen"); + let cursor = row_of_cursor(&screen); + // Too short: no boxes, and one phrase for it. + for rows in [11, 6] { + let small = (SIZE.0, rows); + let text = all(&draw(&mut screen, small)); + assert!(screen.geometry.diff.height < crate::review::inline::MIN_PANE_ROWS, "{rows}"); + assert!(screen.diff.boxes_set().is_empty() && screen.geometry.boxes.is_empty(), "{rows}"); + assert!(text.contains("pane too small for inline notes"), "{rows}: {text}"); + assert!(!text.contains("not shown inline"), "{rows}: {text}"); + } + // Tall enough again: the boxes, and the cursor's line where it was. + let buffer = draw(&mut screen, (SIZE.0, 12)); + assert!(screen.geometry.diff.height >= crate::review::inline::MIN_PANE_ROWS); + assert!(!screen.diff.boxes_set().is_empty(), "boxes at the least height"); + check_boxes(&screen, &buffer, "least height"); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "grown"); + assert!(box_saying(&screen, "a box").is_some()); + assert_eq!(row_of_new(&screen, 20), Some(line), "its line's row again"); + assert_eq!(row_of_cursor(&screen), cursor); + assert!(!all(&buffer).contains("pane too small")); +} + +#[test] +fn a_note_being_edited_leaves_no_rows_of_its_old_box_under_the_comment_box() { + let (_fixture, mut screen) = opened("fix-edit", "layout = \"unified\"\nnotes = \"inline\""); + let long = "a long note that takes a few rows of its box: ".repeat(6); + comment(&mut screen, "file0.py", Side::New, (20, 20), &long); + screen.diff.reveal("file0.py", Side::New, 20).expect("line 20"); + draw(&mut screen, SIZE); + press(&mut screen, KeyCode::Char('j')); + assert!(screen.cursor_note().is_some(), "on its box"); + draw(&mut screen, SIZE); + let old = box_saying(&screen, &long).expect("drawn"); + assert!(old.height >= 6, "{old:?}"); + press(&mut screen, KeyCode::Enter); + let Mode::Compose(draft) = screen.mode.clone() else { panic!("editing") }; + assert!(matches!(draft, Draft::Edit(_))); + screen.compose = Compose::with_text("short"); + let buffer = draw(&mut screen, SIZE); + let pane = screen.geometry.diff; + let compose = screen.compose_rect(pane, &draft); + for y in old.top()..old.bottom() { + for x in old.left()..old.right() { + if compose.contains((x, y).into()) { + continue; + } + let cell = cells(&buffer, x, y, 1); + assert_eq!(cell, " ", "({x}, {y}) of the old box, outside the comment box {compose:?}"); + } + } + press(&mut screen, KeyCode::Enter); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "saved short"); + assert!(box_saying(&screen, "short").is_some_and(|b| b.height == 3)); +} + +#[test] +fn c_on_a_box_comments_on_its_lines_and_the_new_box_stacks_under_it() { + let (_fixture, mut screen) = opened("fix-c", "layout = \"split\"\nnotes = \"inline\""); + comment(&mut screen, "file0.py", Side::New, (19, 20), "first"); + comment(&mut screen, "file0.py", Side::Old, (22, 22), "an old one"); + draw(&mut screen, SIZE); + screen.diff.reveal("file0.py", Side::New, 20).expect("line 20"); + press(&mut screen, KeyCode::Char('j')); + assert!(screen.cursor_note().is_some_and(|n| n.text.as_deref() == Some("first"))); + keys(&mut screen, "c"); + let Mode::Compose(Draft::Comment(lines)) = screen.mode.clone() else { + panic!("a comment: {:?}", screen.status) + }; + assert_eq!((lines.side, lines.first, lines.last), (Side::New, 19, 20)); + type_and_save(&mut screen, "second"); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "stacked"); + let (first, second) = (box_saying(&screen, "first"), box_saying(&screen, "second")); + let (first, second) = (first.expect("first drawn"), second.expect("second drawn")); + assert_eq!((second.x, second.y), (first.x, first.bottom()), "under the first"); + // An old line's box: a comment on the old side; a suggestion is for new lines. + screen.diff.reveal("file0.py", Side::Old, 22).expect("old 22"); + press(&mut screen, KeyCode::Char('h')); + press(&mut screen, KeyCode::Char('j')); + assert!( + screen.cursor_note().is_some_and(|n| n.text.as_deref() == Some("an old one")), + "{:?}", + spot(&screen) + ); + keys(&mut screen, "s"); + assert_eq!(screen.mode, Mode::Browse); + assert!(screen.status.as_deref().is_some_and(|s| s.contains("new lines")), "{:?}", screen.status); + keys(&mut screen, "c"); + let Mode::Compose(Draft::Comment(lines)) = screen.mode.clone() else { panic!("a comment") }; + assert_eq!((lines.side, lines.first, lines.last), (Side::Old, 22, 22)); + press(&mut screen, KeyCode::Esc); +} + +#[test] +fn a_note_saved_on_the_panes_last_row_says_its_box_is_below_and_nothing_moves() { + let (_fixture, mut screen) = opened("fix-below", "layout = \"unified\"\nnotes = \"inline\""); + draw(&mut screen, SIZE); + let bottom = screen.geometry.diff.bottom() - 1; + for _ in 0..60 { + if row_of_cursor(&screen) == Some(bottom) { + break; + } + press(&mut screen, KeyCode::Char('j')); + draw(&mut screen, SIZE); + } + assert_eq!(row_of_cursor(&screen), Some(bottom), "the cursor on the last row"); + let at = spot(&screen); + keys(&mut screen, "c"); + type_and_save(&mut screen, "down here"); + draw(&mut screen, SIZE); + assert_eq!(screen.status.as_deref(), Some("note saved \u{b7} below, \u{2193} shows it")); + assert_eq!((spot(&screen), row_of_cursor(&screen)), (at, Some(bottom)), "nothing moved"); + assert!(box_saying(&screen, "down here").is_none()); + press(&mut screen, KeyCode::Down); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "shown"); + assert!(box_saying(&screen, "down here").is_some(), "Down shows it"); + // A note whose box shows says only that it was saved. + screen.diff.reveal("file0.py", Side::New, 20).expect("line 20"); + draw(&mut screen, SIZE); + keys(&mut screen, "c"); + type_and_save(&mut screen, "in view"); + draw(&mut screen, SIZE); + assert_eq!(screen.status.as_deref(), Some("note saved")); +} diff --git a/crates/plannotator-tui/src/review/tests/inline_flow.rs b/crates/plannotator-tui/src/review/tests/inline_flow.rs index 26563e5a..4c21cd6f 100644 --- a/crates/plannotator-tui/src/review/tests/inline_flow.rs +++ b/crates/plannotator-tui/src/review/tests/inline_flow.rs @@ -15,11 +15,11 @@ use crate::config::review::Notes; use crate::review::{Draft, Mode}; use crate::theme::palette; -const SIZE: (u16, u16) = (COLS, ROWS); +pub(super) const SIZE: (u16, u16) = (COLS, ROWS); /// The long fixture opened with `[review]` as `config` says, the cursor on new line 30 of /// file0.py, near the bottom: new lines 8 to 30 are on screen. -fn opened(tag: &str, config: &str) -> (Fixture, Screen) { +pub(super) fn opened(tag: &str, config: &str) -> (Fixture, Screen) { let fixture = long(tag, false); fixture.write_config(&format!("[review]\n{config}\n")); let mut screen = fixture.open_configured(); @@ -51,7 +51,7 @@ fn pane(screen: &Screen, buffer: &ratatui::buffer::Buffer) -> Vec { (pane.top()..pane.bottom()).map(|y| cells(buffer, pane.x, y, pane.width)).collect() } -fn all(buffer: &ratatui::buffer::Buffer) -> String { +pub(super) fn all(buffer: &ratatui::buffer::Buffer) -> String { (0..buffer.area.height).map(|y| cells(buffer, 0, y, buffer.area.width)).collect::>().join("\n") } @@ -309,7 +309,7 @@ fn on_a_box_enter_edits_it_over_the_box_delete_removes_it_and_x_stays_viewed() { // Delete removes it, and the cursor is back on its line. press(&mut screen, KeyCode::Delete); assert_eq!(screen.store.annotations().len(), 1); - assert_eq!(screen.status.as_deref(), Some("note removed")); + assert_eq!(screen.status.as_deref(), Some("note removed \u{b7} U undo")); assert_eq!(screen.diff.line_on(Side::New).expect("line"), Some(("file0.py", 9))); let buffer = draw(&mut screen, SIZE); check_boxes(&screen, &buffer, "removed"); diff --git a/crates/plannotator-tui/src/review/tests/mod.rs b/crates/plannotator-tui/src/review/tests/mod.rs index 4850e65b..faffb128 100644 --- a/crates/plannotator-tui/src/review/tests/mod.rs +++ b/crates/plannotator-tui/src/review/tests/mod.rs @@ -18,6 +18,7 @@ mod file_list_mouse; mod file_moves; #[cfg(unix)] mod first_look; +mod inline_fixes; mod inline_flow; mod inline_support; mod inline_view; diff --git a/crates/plannotator-tui/src/ui/compose.rs b/crates/plannotator-tui/src/ui/compose.rs index 086c579d..392b9fc2 100644 --- a/crates/plannotator-tui/src/ui/compose.rs +++ b/crates/plannotator-tui/src/ui/compose.rs @@ -41,8 +41,8 @@ pub(crate) struct Compose { scroll: Cell, } -/// The columns a tab takes in the box, as in the diff. -const TAB_WIDTH: usize = 4; +/// The columns a tab takes in the box, and in a note's box in the diff. +pub(crate) const TAB_WIDTH: usize = 4; /// The columns `c` takes in the box: a tab four, a control character (a code line's `\r`) /// none. From 73b0f32f0190f3954c6327b89147f04570d8a5e6 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Wed, 25 Nov 2026 11:55:34 -0500 Subject: [PATCH 07/12] docs(review): U brings back a removed note; c on a box; the small-pane and saved-below footers --- README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 2eea7668..ff7967df 100644 --- a/README.md +++ b/README.md @@ -264,7 +264,7 @@ document review. to. Sends go to the same place a document review's do (Herdr pane, Rex, Pi or the clipboard, or the agent you choose when nothing named one; see [Choosing the agent](#choosing-the-agent)), and are kept in the feedback archive. `q` asks first when notes are unsent. `m` opens the Review menu: `M` comment on the whole change, `R` resend all, `F` finish -review, `U` undo. +review, `U` undo. `U` also brings back the last note removed in this session, where it was. `o` shows the whole file under the cursor as it is now, scrolled to the same line; `O` shows it as it was before the change (the base), at the matching old line. The header says @@ -320,8 +320,11 @@ order they were made, and a note on the whole file sits under the file's heading shows the note's kind and lines, its author when it is not you, `sent` once sent, and up to six lines of its text (a suggestion's code as `-`/`+` lines); `… enter for more` says there is more. The cursor stops once on each box: `enter` or `e` opens the note in the comment box -over it, `delete` removes it, and a click on a box picks its note (in the panel too). A drag -selects code only, and boxes never move the line you are on. Notes on the whole change, and +over it, `delete` removes it (`U` brings it back), `c` or `s` there writes another note on +the same lines, under it, and a click on a box picks its note (in the panel too). A drag +selects code only, and boxes never move the line you are on: a note saved on the pane's last +row says `note saved · below, ↓ shows it`. A pane under 10 rows shows no boxes (`pane too +small for inline notes`). Notes on the whole change, and notes whose lines the diff does not show now (outdated, in a hunk hidden with `W`, in a filtered-out file), get no box: the footer counts them (`2 notes not shown inline · z`) and the panel lists them. With `inline` the panel starts away whatever notes there are; `z` From a9421d1b8fa89ed8b9ff22edb60e59f295c8f6eb Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Wed, 25 Nov 2026 12:06:46 -0500 Subject: [PATCH 08/12] build(review): diffs-rs feat/insets 094634d; insets built with Inset::new --- Cargo.lock | 8 ++++---- crates/plannotator-tui/src/review/diff/insets.rs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 93d6a4b3..2d3ba2fb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -524,7 +524,7 @@ checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" [[package]] name = "diffs-fancy-regex" version = "0.1.0" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#50c794cf6a4ac5e2dc639dab64c4bf170e9f0737" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#094634d2abbda6f1ac29c8db6532d748152e3daf" dependencies = [ "bit-set 0.8.0", "regex-automata", @@ -534,7 +534,7 @@ dependencies = [ [[package]] name = "diffs-rs" version = "0.2.5" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#50c794cf6a4ac5e2dc639dab64c4bf170e9f0737" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#094634d2abbda6f1ac29c8db6532d748152e3daf" dependencies = [ "anyhow", "clap", @@ -560,7 +560,7 @@ dependencies = [ [[package]] name = "diffs-syntect" version = "0.1.0" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#50c794cf6a4ac5e2dc639dab64c4bf170e9f0737" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#094634d2abbda6f1ac29c8db6532d748152e3daf" dependencies = [ "bincode", "diffs-fancy-regex", @@ -580,7 +580,7 @@ dependencies = [ [[package]] name = "diffs-two-face" version = "0.1.0" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#50c794cf6a4ac5e2dc639dab64c4bf170e9f0737" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#094634d2abbda6f1ac29c8db6532d748152e3daf" dependencies = [ "diffs-syntect", "serde", diff --git a/crates/plannotator-tui/src/review/diff/insets.rs b/crates/plannotator-tui/src/review/diff/insets.rs index 62806099..23494a53 100644 --- a/crates/plannotator-tui/src/review/diff/insets.rs +++ b/crates/plannotator-tui/src/review/diff/insets.rs @@ -41,7 +41,7 @@ impl Diff { Some(_) => return None, None => InsetAnchor::FileHeading, }; - Some(Inset { review, id: slot.id, file, anchor, span: span(slot.over), height: slot.height }) + Some(Inset::new(review, slot.id, file, anchor, slot.height).with_span(span(slot.over))) }) .collect(); if self.engine.insets() == insets.as_slice() { From 026225446ba649ce276f18596ddabc18fa346473 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Wed, 25 Nov 2026 12:41:10 -0500 Subject: [PATCH 09/12] test(review): the viewer keeps a box's line still through edits, clicks and resizes, and the cursor's side past a box On diffs-rs feat/insets dc407e5. --- Cargo.lock | 8 +- .../src/review/tests/inline_engine.rs | 169 ++++++++++++++++++ .../plannotator-tui/src/review/tests/mod.rs | 1 + 3 files changed, 174 insertions(+), 4 deletions(-) create mode 100644 crates/plannotator-tui/src/review/tests/inline_engine.rs diff --git a/Cargo.lock b/Cargo.lock index 2d3ba2fb..f12dfe50 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -524,7 +524,7 @@ checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" [[package]] name = "diffs-fancy-regex" version = "0.1.0" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#094634d2abbda6f1ac29c8db6532d748152e3daf" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#dc407e5edc988f9549aadf1ca4041a138d0780b3" dependencies = [ "bit-set 0.8.0", "regex-automata", @@ -534,7 +534,7 @@ dependencies = [ [[package]] name = "diffs-rs" version = "0.2.5" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#094634d2abbda6f1ac29c8db6532d748152e3daf" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#dc407e5edc988f9549aadf1ca4041a138d0780b3" dependencies = [ "anyhow", "clap", @@ -560,7 +560,7 @@ dependencies = [ [[package]] name = "diffs-syntect" version = "0.1.0" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#094634d2abbda6f1ac29c8db6532d748152e3daf" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#dc407e5edc988f9549aadf1ca4041a138d0780b3" dependencies = [ "bincode", "diffs-fancy-regex", @@ -580,7 +580,7 @@ dependencies = [ [[package]] name = "diffs-two-face" version = "0.1.0" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#094634d2abbda6f1ac29c8db6532d748152e3daf" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#dc407e5edc988f9549aadf1ca4041a138d0780b3" dependencies = [ "diffs-syntect", "serde", diff --git a/crates/plannotator-tui/src/review/tests/inline_engine.rs b/crates/plannotator-tui/src/review/tests/inline_engine.rs new file mode 100644 index 00000000..b4aeb135 --- /dev/null +++ b/crates/plannotator-tui/src/review/tests/inline_engine.rs @@ -0,0 +1,169 @@ +//! What the viewer keeps still around the notes' boxes, as a reviewer met it in the real +//! program: a box edited shorter, after the cursor came up onto it or a click on its bottom +//! border, keeps its line's row; so does a resize with the cursor on a wrapped box's last +//! row. The cursor keeps its side past a box of the other side, and switching the Notes +//! setting round near the top of the diff ends where it started. + +use plannotator_tui_review::Side; +use ratatui::crossterm::event::{KeyCode, MouseButton, MouseEventKind}; + +use super::compose_near::{draw, report, view}; +use super::inline_flow::{SIZE, opened, set_notes}; +use super::inline_support::{box_saying, check_boxes, comment, row_of_spot}; +use super::*; +use crate::config::review::Notes; +use crate::review::{Draft, Mode}; + +/// The screen row of new line `line` of file0.py (a changed line) in the last frame. +fn row_of_new(screen: &Screen, line: u32) -> Option { + let spot = ("file0.py".to_owned(), None, Some(line), "Code".to_owned()); + row_of_spot(screen, &spot) +} + +const LONG: &str = "a note long enough to take several rows of its box, so that saving it shorter \ + gives back rows under its line, which must come back without moving the line"; + +/// In the comment box: delete everything typed but `keep` characters, by keys, and save. +fn shorten_and_save(screen: &mut Screen, keep: usize) { + press(screen, KeyCode::End); + let len = screen.compose.value().chars().count(); + for _ in keep..len { + press(screen, KeyCode::Backspace); + } + press(screen, KeyCode::Enter); + assert_eq!(screen.mode, Mode::Browse, "saved"); +} + +#[test] +fn a_box_edited_shorter_after_coming_up_onto_it_keeps_its_line_still() { + let (_fixture, mut screen) = opened("engine-up", "layout = \"unified\"\nnotes = \"inline\""); + comment(&mut screen, "file0.py", Side::New, (20, 20), LONG); + draw(&mut screen, SIZE); + screen.diff.reveal("file0.py", Side::New, 21).expect("line 21"); + draw(&mut screen, SIZE); + press(&mut screen, KeyCode::Char('k')); + assert!(screen.cursor_note().is_some(), "up onto the box"); + draw(&mut screen, SIZE); + let line = row_of_new(&screen, 20).expect("its line on screen"); + press(&mut screen, KeyCode::Enter); + shorten_and_save(&mut screen, 6); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "shorter"); + assert_eq!(row_of_new(&screen, 20), Some(line), "its line did not move"); +} + +#[test] +fn a_box_edited_shorter_after_a_click_on_its_bottom_border_keeps_its_line_still() { + let (_fixture, mut screen) = opened("engine-click", "layout = \"unified\"\nnotes = \"inline\""); + comment(&mut screen, "file0.py", Side::New, (20, 20), LONG); + screen.diff.reveal("file0.py", Side::New, 20).expect("line 20"); + draw(&mut screen, SIZE); + let boxed = box_saying(&screen, LONG).expect("drawn"); + let at = (boxed.x + 3, boxed.bottom() - 1); + report(&mut screen, MouseEventKind::Down(MouseButton::Left), at); + report(&mut screen, MouseEventKind::Up(MouseButton::Left), at); + assert!(screen.cursor_note().is_some(), "on the box"); + draw(&mut screen, SIZE); + let line = row_of_new(&screen, 20).expect("its line on screen"); + press(&mut screen, KeyCode::Enter); + shorten_and_save(&mut screen, 6); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "shorter"); + assert_eq!(row_of_new(&screen, 20), Some(line), "its line did not move"); +} + +#[test] +fn a_resize_with_the_cursor_on_a_wrapped_boxs_last_row_keeps_its_line_still() { + let (_fixture, mut screen) = opened("engine-resize", "layout = \"unified\"\nnotes = \"inline\""); + comment(&mut screen, "file0.py", Side::New, (20, 20), LONG); + let narrow = (80, SIZE.1); + draw(&mut screen, narrow); + screen.diff.reveal("file0.py", Side::New, 20).expect("line 20"); + draw(&mut screen, narrow); + let boxed = box_saying(&screen, LONG).expect("drawn"); + assert!(boxed.height > 3, "wrapped: {boxed:?}"); + let at = (boxed.x + 3, boxed.bottom() - 1); + report(&mut screen, MouseEventKind::Down(MouseButton::Left), at); + report(&mut screen, MouseEventKind::Up(MouseButton::Left), at); + assert!(screen.cursor_note().is_some(), "on the box's last row"); + draw(&mut screen, narrow); + let line = row_of_new(&screen, 20).expect("its line on screen"); + let buffer = draw(&mut screen, SIZE); + check_boxes(&screen, &buffer, "wide"); + assert_eq!(row_of_new(&screen, 20), Some(line), "its line did not move"); +} + +#[test] +fn a_resize_after_a_box_on_the_cursor_shrank_keeps_its_line_still() { + let (_fixture, mut screen) = opened("engine-shrunk", "layout = \"unified\"\nnotes = \"inline\""); + comment(&mut screen, "file0.py", Side::New, (20, 20), LONG); + let narrow = (80, SIZE.1); + draw(&mut screen, narrow); + screen.diff.reveal("file0.py", Side::New, 20).expect("line 20"); + draw(&mut screen, narrow); + let boxed = box_saying(&screen, LONG).expect("drawn"); + let at = (boxed.x + 3, boxed.bottom() - 1); + report(&mut screen, MouseEventKind::Down(MouseButton::Left), at); + report(&mut screen, MouseEventKind::Up(MouseButton::Left), at); + assert!(screen.cursor_note().is_some(), "on the box's last row"); + draw(&mut screen, narrow); + let line = row_of_new(&screen, 20).expect("its line on screen"); + // One row shorter, at the same width: the line stays. + let id = screen.store.annotations().first().map(|n| n.id.clone()).expect("the note"); + let shorter = LONG.split_once(", which").map(|(head, _)| head.to_owned()).expect("a comma"); + screen + .store + .edit(&id, |note| { + note.text = Some(shorter); + true + }) + .expect("edited"); + draw(&mut screen, narrow); + assert_eq!(row_of_new(&screen, 20), Some(line), "the shorter box kept its line"); + // Two columns wider, the box as tall: nothing to move for. + let buffer = draw(&mut screen, (82, SIZE.1)); + check_boxes(&screen, &buffer, "82"); + assert_eq!(row_of_new(&screen, 20), Some(line), "its line did not move"); +} + +#[test] +fn the_cursor_keeps_its_side_past_a_box_of_the_other_side() { + let (_fixture, mut screen) = opened("engine-side", "layout = \"split\"\nnotes = \"inline\""); + comment(&mut screen, "file0.py", Side::Old, (32, 32), "only on the old side"); + screen.diff.reveal("file0.py", Side::New, 32).expect("new 32"); + draw(&mut screen, SIZE); + assert_eq!(screen.diff.line_on(Side::New).expect("line"), Some(("file0.py", 32))); + press(&mut screen, KeyCode::Down); + press(&mut screen, KeyCode::Down); + draw(&mut screen, SIZE); + keys(&mut screen, "c"); + let Mode::Compose(Draft::Comment(lines)) = screen.mode.clone() else { + panic!("a comment: {:?}", screen.status) + }; + assert_eq!((lines.side, lines.first), (Side::New, 33), "the new side of 33"); + press(&mut screen, KeyCode::Esc); + press(&mut screen, KeyCode::Up); + press(&mut screen, KeyCode::Up); + draw(&mut screen, SIZE); + keys(&mut screen, "c"); + let Mode::Compose(Draft::Comment(lines)) = screen.mode.clone() else { panic!("a comment") }; + assert_eq!((lines.side, lines.first), (Side::New, 32), "back on new 32"); + press(&mut screen, KeyCode::Esc); +} + +#[test] +fn the_notes_setting_round_and_back_near_the_top_ends_where_it_started() { + let (_fixture, mut screen) = opened("engine-round", "layout = \"unified\"\nnotes = \"inline\""); + comment(&mut screen, "file0.py", Side::New, (2, 2), "near the top"); + comment(&mut screen, "file0.py", Side::New, (5, 6), "a little lower"); + screen.diff.reveal("file0.py", Side::New, 4).expect("line 4"); + let mut seen = vec![(Notes::Inline, view(&mut screen, SIZE))]; + for notes in [Notes::Panel, Notes::Inline, Notes::Both, Notes::Panel] { + set_notes(&mut screen, notes); + let now = view(&mut screen, SIZE); + if let Some((_, before)) = seen.iter().find(|(seen, _)| *seen == notes) { + assert_eq!(&now, before, "{notes:?} again: where it was"); + } + seen.push((notes, now)); + } +} diff --git a/crates/plannotator-tui/src/review/tests/mod.rs b/crates/plannotator-tui/src/review/tests/mod.rs index faffb128..7a13fc0e 100644 --- a/crates/plannotator-tui/src/review/tests/mod.rs +++ b/crates/plannotator-tui/src/review/tests/mod.rs @@ -18,6 +18,7 @@ mod file_list_mouse; mod file_moves; #[cfg(unix)] mod first_look; +mod inline_engine; mod inline_fixes; mod inline_flow; mod inline_support; From ac5fa8ce81bf76de16301648bee3cd054ef4e6d5 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Wed, 25 Nov 2026 13:48:26 -0500 Subject: [PATCH 10/12] build(review): diffs-rs feat/insets 7d287cc --- Cargo.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index add53ab0..427834f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -524,7 +524,7 @@ checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" [[package]] name = "diffs-fancy-regex" version = "0.1.0" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#dc407e5edc988f9549aadf1ca4041a138d0780b3" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#7d287cc212ab290a40052f86fe7171e0c8483980" dependencies = [ "bit-set 0.8.0", "regex-automata", @@ -534,7 +534,7 @@ dependencies = [ [[package]] name = "diffs-rs" version = "0.2.5" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#dc407e5edc988f9549aadf1ca4041a138d0780b3" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#7d287cc212ab290a40052f86fe7171e0c8483980" dependencies = [ "anyhow", "clap", @@ -560,7 +560,7 @@ dependencies = [ [[package]] name = "diffs-syntect" version = "0.1.0" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#dc407e5edc988f9549aadf1ca4041a138d0780b3" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#7d287cc212ab290a40052f86fe7171e0c8483980" dependencies = [ "bincode", "diffs-fancy-regex", @@ -580,7 +580,7 @@ dependencies = [ [[package]] name = "diffs-two-face" version = "0.1.0" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#dc407e5edc988f9549aadf1ca4041a138d0780b3" +source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#7d287cc212ab290a40052f86fe7171e0c8483980" dependencies = [ "diffs-syntect", "serde", From 92c36dbb8998f076270761e8612696b527b5ba4d Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Wed, 25 Nov 2026 14:24:33 -0500 Subject: [PATCH 11/12] fix(review): a file note's comment box under the heading's boxes; s on a file box; undo kept per review; help fits 40 rows - c on a file note's box opens the new file note under the heading's boxes, lined up with them, as a line's comment box opens under its boxes. - s there says a suggestion needs lines of code and c adds a file comment. - Each review's undo history is kept for the session: back on a review after picking another, U still takes back what was done there. - The key help's U row joins the review menu's (m U), so the help fits 40 rows again with the notes panel's keys on screen. --- .../plannotator-tui/src/review/compose_at.rs | 10 +++- crates/plannotator-tui/src/review/drafts.rs | 9 ++++ crates/plannotator-tui/src/review/inline.rs | 13 ++++- crates/plannotator-tui/src/review/mod.rs | 4 ++ crates/plannotator-tui/src/review/overlays.rs | 5 +- .../plannotator-tui/src/review/pick/shown.rs | 5 ++ .../plannotator-tui/src/review/pick/tests.rs | 36 ++++++++++++++ .../src/review/tests/inline_fixes.rs | 48 +++++++++++++++++++ 8 files changed, 124 insertions(+), 6 deletions(-) diff --git a/crates/plannotator-tui/src/review/compose_at.rs b/crates/plannotator-tui/src/review/compose_at.rs index 35df22ab..2271ecf4 100644 --- a/crates/plannotator-tui/src/review/compose_at.rs +++ b/crates/plannotator-tui/src/review/compose_at.rs @@ -5,7 +5,8 @@ //! shows them, else above the first, so the box covers none of them; in a split diff over //! that side's pane, wherever the line between the sides was dragged. Lines taller than //! the room keep the box at the end the person last moved to, the cursor's end. -//! - A file (`C`, editing a file note): under the file's heading, else at the top of the pane. +//! - A file (`C`, editing a file note): under the file's heading (and the file notes' boxes +//! there, lined up with them), else at the top of the pane. //! - The whole change (`M`, editing its note), or lines no longer on screen: centred. //! - Editing a note whose box the diff shows (`inline`): over the box, as wide as it. Notes' //! boxes under the lines of a new one count as theirs: the box opens below them. @@ -74,6 +75,11 @@ impl Screen { columns } Anchor::Lines(lines) => columns(pane, middle, lines.side), + Anchor::File(path) + if let Some(columns) = boxes.then(|| self.heading_box_columns(pane, path)).flatten() => + { + columns + } Anchor::File(_) | Anchor::Centre => (pane.x, pane.width.min(MAX_WIDTH)), Anchor::Over(rect) => (rect.x, rect.width), }; @@ -95,6 +101,8 @@ impl Screen { (first, last, top) }), Anchor::File(path) => match diff.and_then(|diff| diff.heading_row(path)) { + // Below the file notes' boxes under the heading, never over them. + Some(row) if boxes => Some((row, diff.map_or(row, |diff| diff.under_boxes(row)), false)), Some(row) => Some((row, row, false)), // No heading on screen: at the top of the pane. None => return Rect { x, y: pane.y, width, height: wanted }, diff --git a/crates/plannotator-tui/src/review/drafts.rs b/crates/plannotator-tui/src/review/drafts.rs index 7927d30e..f6b926ca 100644 --- a/crates/plannotator-tui/src/review/drafts.rs +++ b/crates/plannotator-tui/src/review/drafts.rs @@ -47,6 +47,15 @@ impl Screen { /// `s`: the comment box filled with the selected new-side lines; what the person makes /// of them is the suggested code. pub(super) fn start_suggestion(&mut self) -> Result<()> { + if self.diff.selection().is_none() + && self.cursor_note().is_some_and(|note| note.scope == NoteScope::File) + { + self.status = Some(match self.keys.hint(crate::keys::Action::Comment) { + key if key.is_empty() => "a suggestion needs lines of code".to_owned(), + key => format!("a suggestion needs lines of code; {key} adds a file comment"), + }); + return Ok(()); + } let Some(lines) = self.target_lines()? else { self.status = Some("move the cursor onto a line of code first".into()); return Ok(()); diff --git a/crates/plannotator-tui/src/review/inline.rs b/crates/plannotator-tui/src/review/inline.rs index 0e6a4c50..964569ed 100644 --- a/crates/plannotator-tui/src/review/inline.rs +++ b/crates/plannotator-tui/src/review/inline.rs @@ -188,10 +188,19 @@ impl Screen { /// The first column and width the box of a note on `lines` would have in `pane`, for the /// comment box to line up with the boxes. `None` when it would get none. pub(super) fn box_columns(&self, pane: ratatui::layout::Rect, lines: &Lines) -> Option<(u16, u16)> { + self.columns_at(pane, &lines.path, Place::Line(lines.side, lines.last)) + } + + /// [`Self::box_columns`] for a note on the file at `path`, under its heading. + pub(super) fn heading_box_columns(&self, pane: ratatui::layout::Rect, path: &str) -> Option<(u16, u16)> { + self.columns_at(pane, path, Place::Heading) + } + + fn columns_at(&self, pane: ratatui::layout::Rect, path: &str, place: Place) -> Option<(u16, u16)> { let split = self.diff.split(); let widths = - [Some(Side::Old), Some(Side::New), None].map(|over| self.diff.box_width(pane, &lines.path, over)); - let over = over(Place::Line(lines.side, lines.last), split, widths); + [Some(Side::Old), Some(Side::New), None].map(|over| self.diff.box_width(pane, path, over)); + let over = over(place, split, widths); let full = width(widths, over)?; // Every box ends at the pane's right edge but one over the old side, which ends at // the line between the sides. diff --git a/crates/plannotator-tui/src/review/mod.rs b/crates/plannotator-tui/src/review/mod.rs index 976032dd..b61d8a19 100644 --- a/crates/plannotator-tui/src/review/mod.rs +++ b/crates/plannotator-tui/src/review/mod.rs @@ -208,6 +208,9 @@ pub(crate) struct Screen { last_send: crate::ui::send_button::LastSend, /// What `undo-finish` takes back, the last first: a finish, or a removed note. undo: Vec, + /// The undo histories of the reviews switched away from in this session, by their + /// record's path, for when they are back. + undos: std::collections::HashMap>, status: Option, geometry: Geometry, /// A drag with the left button in the diff, until the release. @@ -312,6 +315,7 @@ impl Screen { send_state: SendState::Ready, last_send: crate::ui::send_button::LastSend::None, undo: Vec::new(), + undos: std::collections::HashMap::new(), status: None, geometry: Geometry::default(), drag: None, diff --git a/crates/plannotator-tui/src/review/overlays.rs b/crates/plannotator-tui/src/review/overlays.rs index 26b979fc..2b8bb276 100644 --- a/crates/plannotator-tui/src/review/overlays.rs +++ b/crates/plannotator-tui/src/review/overlays.rs @@ -84,11 +84,10 @@ impl Screen { (key(&[Action::SendAndClose]), "send and close"), (key(&[Action::ChangeComment]), "comment on the whole change"), ( - key(&[Action::ReviewMenu]), - "review menu: whole-change comment, resend all, finish, undo", + key(&[Action::ReviewMenu, Action::UndoFinish]), + "review menu: comment, resend, finish / undo a finish or a removal", ), (key(&[Action::PickTarget]), "choose the agent Send goes to"), - (key(&[Action::UndoFinish]), "undo the last note removed, or the last finish"), ( key(&[Action::PickChanges]), "pick what to review: uncommitted, unstaged, staged, a commit", diff --git a/crates/plannotator-tui/src/review/pick/shown.rs b/crates/plannotator-tui/src/review/pick/shown.rs index 95855fc4..98bacee9 100644 --- a/crates/plannotator-tui/src/review/pick/shown.rs +++ b/crates/plannotator-tui/src/review/pick/shown.rs @@ -394,6 +394,11 @@ impl Screen { next.notes_rail.settle(!next.store.annotations().is_empty()); next.reach = std::mem::take(&mut self.reach); next.pi_link = self.pi_link.take(); + // Each review's undo history, for the session: back on one, `U` still takes back + // what was done there. + next.undos = std::mem::take(&mut self.undos); + next.undos.insert(self.store.path().to_path_buf(), std::mem::take(&mut self.undo)); + next.undo = next.undos.remove(next.store.path()).unwrap_or_default(); // The reviews left so far and this one, less the one opening. let here = self.left(); let opening = next.left(); diff --git a/crates/plannotator-tui/src/review/pick/tests.rs b/crates/plannotator-tui/src/review/pick/tests.rs index 70dbe727..3e938d74 100644 --- a/crates/plannotator-tui/src/review/pick/tests.rs +++ b/crates/plannotator-tui/src/review/pick/tests.rs @@ -835,3 +835,39 @@ fn a_repository_with_no_commits_says_there_is_nothing() { assert!(rows.iter().any(|r| r.contains("Nothing to review in fresh")), "{}", rows.join("\n")); assert!(!rows.iter().any(|r| r.contains("pick a commit")), "{}", rows.join("\n")); } + +#[test] +fn u_still_takes_back_a_removal_after_another_target_and_back() { + let fixture = Fixture::new("pick-undo"); + commit(&fixture, "second"); + fixture.write("app.py", crate::review::tests::AFTER.replace("import sys", "import os").as_str()); + let mut shown = reviewing(&fixture); + { + let screen = shown.screen_mut().expect("review"); + at(screen, 1); + crate::review::tests::keys(screen, "c"); + type_and_save(screen, "why os?"); + let id = screen.store.annotations().first().map(|n| n.id.clone()).expect("the note"); + screen.remove_note(&id).expect("removed"); + assert_eq!(screen.status.as_deref(), Some("note removed \u{b7} U undo")); + } + keys(&mut shown, "p"); + settle(&mut shown, 120, 30); + keys(&mut shown, "jjj"); // the commit `second` + press(&mut shown, KeyCode::Enter); + until_open(&mut shown); + keys(&mut shown, "U"); + let screen = shown.screen().expect("the commit's review"); + assert_eq!(screen.status.as_deref(), Some("nothing to undo"), "its own history: none"); + + keys(&mut shown, "p"); + settle(&mut shown, 120, 30); + keys(&mut shown, "g"); + press(&mut shown, KeyCode::Enter); + until_open(&mut shown); + keys(&mut shown, "U"); + let screen = shown.screen().expect("back on uncommitted"); + assert_eq!(screen.capture.scope, Scope::Uncommitted); + assert_eq!(screen.status.as_deref(), Some("note restored")); + assert_eq!(screen.store.annotations().len(), 1, "the note is back"); +} diff --git a/crates/plannotator-tui/src/review/tests/inline_fixes.rs b/crates/plannotator-tui/src/review/tests/inline_fixes.rs index fc09e64a..5d9a8972 100644 --- a/crates/plannotator-tui/src/review/tests/inline_fixes.rs +++ b/crates/plannotator-tui/src/review/tests/inline_fixes.rs @@ -240,3 +240,51 @@ fn a_note_saved_on_the_panes_last_row_says_its_box_is_below_and_nothing_moves() draw(&mut screen, SIZE); assert_eq!(screen.status.as_deref(), Some("note saved")); } + +#[test] +fn c_on_a_file_notes_box_opens_under_the_headings_boxes_lined_up_and_s_says_why_not() { + for layout in ["unified", "split"] { + let (_fixture, mut screen) = + opened(&format!("fix-file-{layout}"), &format!("layout = \"{layout}\"\nnotes = \"inline\"")); + keys(&mut screen, "C"); + type_and_save(&mut screen, "about the whole file"); + screen.diff.show_heading(0).expect("heading"); + draw(&mut screen, SIZE); + press(&mut screen, KeyCode::Char('j')); + assert!( + screen.cursor_note().is_some_and(|n| n.scope == plannotator_tui_review::NoteScope::File), + "{layout}: on the file note's box" + ); + draw(&mut screen, SIZE); + let boxed = box_saying(&screen, "about the whole file").expect("drawn"); + keys(&mut screen, "s"); + assert_eq!(screen.mode, Mode::Browse, "{layout}"); + assert_eq!( + screen.status.as_deref(), + Some("a suggestion needs lines of code; c adds a file comment"), + "{layout}" + ); + keys(&mut screen, "c"); + let Mode::Compose(draft) = screen.mode.clone() else { panic!("{layout}: a file comment") }; + assert!(matches!(&draft, Draft::File(path) if path == "file0.py"), "{layout}: {draft:?}"); + let buffer = draw(&mut screen, SIZE); + let compose = screen.compose_rect(screen.geometry.diff, &draft); + assert_eq!((compose.x, compose.width), (boxed.x, boxed.width), "{layout}: lined up with the box"); + assert_eq!(compose.y, boxed.bottom(), "{layout}: right under the box, over none of it"); + assert_eq!(cells(&buffer, boxed.x, boxed.y, 1), "\u{256d}", "{layout}: the box still shows"); + press(&mut screen, KeyCode::Esc); + } +} + +#[test] +fn the_key_help_fits_forty_rows_in_both_modes() { + for notes in [Notes::Panel, Notes::Inline] { + let (_fixture, mut screen) = opened(&format!("fix-help-{notes:?}"), "layout = \"unified\""); + set_notes(&mut screen, notes); + keys(&mut screen, "?"); + let text = all(&draw(&mut screen, (SIZE.0, 40))); + assert_eq!(screen.help_room.get(), 0, "{notes:?}: nothing below the fold:\n{text}"); + assert!(text.contains("remove") && text.contains("undo a finish or a removal"), "{notes:?}:\n{text}"); + press(&mut screen, KeyCode::Esc); + } +} From 05df69ddb2531a8abfaff357c68a1fd4179b24bd Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Wed, 25 Nov 2026 14:38:27 -0500 Subject: [PATCH 12/12] build: diffs-rs 0.2.6 from crates.io, no longer patched from its branch --- Cargo.lock | 14 +++++++++----- Cargo.toml | 7 ------- crates/plannotator-tui/Cargo.toml | 2 +- 3 files changed, 10 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 427834f4..850f81a2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -524,7 +524,8 @@ checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" [[package]] name = "diffs-fancy-regex" version = "0.1.0" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#7d287cc212ab290a40052f86fe7171e0c8483980" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c8bafb03bb9ed9eeb28ac231849ae6be395c8bf483f6a6f46db0616828e8fbc" dependencies = [ "bit-set 0.8.0", "regex-automata", @@ -533,8 +534,9 @@ dependencies = [ [[package]] name = "diffs-rs" -version = "0.2.5" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#7d287cc212ab290a40052f86fe7171e0c8483980" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea974d078fbc82f526482cf85943953370c3c5e96b2bc9176648e35ee60bbbbf" dependencies = [ "anyhow", "clap", @@ -560,7 +562,8 @@ dependencies = [ [[package]] name = "diffs-syntect" version = "0.1.0" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#7d287cc212ab290a40052f86fe7171e0c8483980" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf57443c937ba79afc5d9c7ca4b63d411dad8fb25fa72f0a5f063c71234e0e4d" dependencies = [ "bincode", "diffs-fancy-regex", @@ -580,7 +583,8 @@ dependencies = [ [[package]] name = "diffs-two-face" version = "0.1.0" -source = "git+https://github.com/plannotator/diffs-rs?branch=feat%2Finsets#7d287cc212ab290a40052f86fe7171e0c8483980" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fc53b9992dd1e96ffd1daf26d10ee81cfa0bbbe356b8eaf39a971d8819cd67e" dependencies = [ "diffs-syntect", "serde", diff --git a/Cargo.toml b/Cargo.toml index 46b49e83..726fb7f4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,13 +52,6 @@ cast_sign_loss = "allow" cast_possible_wrap = "allow" cast_precision_loss = "allow" -# diffs-rs: rows between the diff's rows for the notes drawn inline (plannotator/diffs-rs#23), -# until it is published. Its two forks come from the same checkout, so one copy of each is built. -[patch.crates-io] -diffs-rs = { git = "https://github.com/plannotator/diffs-rs", branch = "feat/insets" } -diffs-syntect = { git = "https://github.com/plannotator/diffs-rs", branch = "feat/insets" } -diffs-two-face = { git = "https://github.com/plannotator/diffs-rs", branch = "feat/insets" } - [profile.release] lto = "thin" # Shipped binaries carry no debug info; profile locally with `--profile profiling`. diff --git a/crates/plannotator-tui/Cargo.toml b/crates/plannotator-tui/Cargo.toml index cb3bd141..e43b4a94 100644 --- a/crates/plannotator-tui/Cargo.toml +++ b/crates/plannotator-tui/Cargo.toml @@ -50,7 +50,7 @@ signal-hook = "0.3" # Default features off: `dev-tty` would switch crossterm, for this whole build, to reading # /dev/tty, and `clipboard` is its own macOS clipboard; this app owns its input and copies. # 0.2.4: the version the unpublished branch patched in at the workspace root carries. -diffs-rs = { version = "0.2.5", default-features = false } +diffs-rs = { version = "0.2.6", default-features = false } [dev-dependencies] rusqlite = { version = "0.31.0", features = ["bundled"] }