Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ All notable changes to `diffs-rs` are recorded here. The forked crates in
## 0.1.1 - unreleased

- docs: new README, docs moved under docs/.
- `Options.chrome`: set it to `false` and the engine draws no label row, footer or help
overlay, so the host owns those rows. Adding this field breaks hosts that build `Options`
without `..Options::default()`.
- `Engine::set_markers` draws host markers in the gutter for ranges of source lines.
- `Engine::reveal` moves the cursor to a source line, and `Engine::select_range` selects a
range of source lines as the user would.

## 0.1.0 - 2026-10-27

Expand Down
52 changes: 52 additions & 0 deletions docs/embedding.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,20 @@ The draw rectangle is intersected with the frame. Engine drawing does not change
The supplied rectangle controls reflow. Terminal resize events request a redraw but do not replace the pane dimensions with the full terminal dimensions.
Supply the current rectangle on every draw, including when a pane moves without changing size.

### Without chrome

By default the engine draws a label row at the top of its rectangle, a footer with status and key hints at the bottom, and a help overlay on `?`.
Set `Options { chrome: false, .. }` when the host owns those rows:

- The diff, its file headers and the Files sidebar fill the whole rectangle. The rectangle needs at least 40 columns × 8 rows instead of 40 × 10.
- `Command::Help` and the `?` key are ignored, so the help overlay never opens.
- `draw_with_controls` ignores its `ReadingControls`; the host shows its own hints and notices.
- The loading, failure and too-small placeholders name no keys.

Read the state the footer would have shown from `status()`: `loading`, `coloring`, `preparing_source`, `source_failed` and `error`, and `files` for the count.
The review label, layout and theme are the host's own inputs and `options()`.
`chrome` is fixed for the engine's lifetime, and `replace()` keeps it.

## Commands and selection

`handle_event(event, focused)` applies the viewer's default bindings.
Expand Down Expand Up @@ -92,6 +106,42 @@ The default mouse route supports Shift-click within the same file and side. The
The standalone maps `V` and Escape to these commands. `handle_event` alone does not add those keyboard bindings.
Headers and padding never become endpoints. Ranges can span unavailable patch-only gaps; `source_read` rejects those gaps during streaming.

### Host-driven position and selection

`reveal(file, side, line)` scrolls an original source line into view and puts the cursor on it, on that side.
`select_range(range)` makes a fixed selection over `range.first..=range.last`, as if the user had selected it and finished.
The cursor ends on `range.last`; `selection()`, `selected_source()` and `source_read()` then report it as they would a user selection, and `selection_extending()` is false.
Both give the diff keyboard focus and close the help overlay.

Both return an error, and change nothing, when the line is not displayed: the file is not in the review, the line is outside the file or on the other side only, or it sits in a gap that the patch does not supply and nobody has revealed.
Checked context counts once it is revealed. For `select_range` only the two endpoints must be displayed. As with a user selection, the lines between them can cross a gap, and `source_read` then rejects the range.
`select_range` also rejects a range from another review or with `first` of 0 or greater than `last`.
Moving the cursor to another file or side clears the selection, as it does for a user selection.

### Gutter markers

`set_markers(&[Marker])` replaces every marker with a new set; an empty slice clears them.
A `Marker` is a `SourceRange` plus a Ratatui `Style`:

```rust
use diffs_rs::{engine::{Marker, Side}, reading::SourceRange};
use ratatui::style::{Color, Style};

engine.set_markers(&[Marker {
range: SourceRange { review: engine.review_id(), file: 0, side: Side::New, first: 12, last: 14 },
style: Style::new().fg(Color::Yellow),
}])?;
```

Each visible row whose source line on `range.side` falls in the range shows `▌` in the first gutter cell, patched with `style`. Continuation rows of a wrapped line show it too.
In the split layout a marker shows on its own side's half. A unified row shows both line numbers, so a marker on either side applies.
The cursor `▎` and selection `┃` indicators take precedence in that cell. Where markers overlap, the later one in the slice wins.
The set is indexed per file and side when it is replaced, so each drawn row costs one lookup however many markers exist.

Markers for lines that are not displayed, or for files that have not arrived yet, draw nothing until they are. Markers can be set before the first file arrives.
`set_markers` rejects the whole set, keeping the previous one, if any range belongs to another review or has `first` of 0 or greater than `last`. It also fails after `close()`.
`replace()` and `close()` drop the markers. Set them again for the new review with its `review_id()`.

### Source reading and search

`source_read(SourceRange)` prepares an original-side range with inclusive source-line coordinates.
Expand Down Expand Up @@ -165,6 +215,8 @@ cargo run --release --locked --example embedded_viewer -- fixtures/review.patch
Use full commit IDs to keep Git inputs fixed across repeated opens. A symbolic revision resolves again on each open. File pairs capture fresh bytes on each open; editing the live files does not change an already captured review. Arguments are validated before acquiring the terminal.

The left pane belongs to the host. Tab switches outer focus; `r` opens the next review, `c` closes the review without exiting, `o` reopens it, and `q` exits the host.
`m` marks the selection (Shift-click to make one) or the cursor line with a gutter marker, and `'` selects the last mark again with `select_range`.
`--no-chrome` turns off the viewer's label row, footer and help; the host then draws its own status row from `status()` below the viewer.
These are example-host controls, not additional viewer bindings.
The example uses the current terminal and does not open windows or change preferences.
`State: source unavailable` distinguishes degraded full-source preparation from a ready review. Published patch content remains readable, and the host can replace the review. Unexpected worker/storage errors and failed cleanup terminate the example with an error; they are not treated as recoverable input errors.
Expand Down
107 changes: 102 additions & 5 deletions examples/embedded_viewer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@ use crossterm::{
LeaveAlternateScreen,
},
};
use diffs_rs::engine::{Engine, Input, Layout, Options, SidebarPreference};
use diffs_rs::engine::{Engine, Input, Layout, Marker, Options, Side, SidebarPreference};
use diffs_rs::input::LocalInput;
use diffs_rs::reading::SourceRange;
use ratatui::{
Terminal,
backend::CrosstermBackend,
layout::Rect,
style::{Color, Style},
widgets::{Block, Borders, Paragraph},
};

Expand All @@ -45,7 +47,12 @@ impl ReviewInput {
}
}

fn review_inputs() -> Result<Vec<ReviewInput>> {
struct Arguments {
inputs: Vec<ReviewInput>,
chrome: bool,
}

fn review_inputs() -> Result<Arguments> {
let matches = clap::Command::new("embedded_viewer")
.about("Open local reviews in one terminal host, in argument order")
.arg_required_else_help(true)
Expand Down Expand Up @@ -73,6 +80,12 @@ fn review_inputs() -> Result<Vec<ReviewInput>> {
.value_parser(OsStringValueParser::new())
.help("Compare Git commits; use full commit IDs to pin repeated opens"),
)
.arg(
Arg::new("no-chrome")
.long("no-chrome")
.action(ArgAction::SetTrue)
.help("Hide the viewer's label row, footer and help; the host draws a status row"),
)
.get_matches();
let mut inputs = Vec::new();
if let Some(paths) = matches.get_many::<PathBuf>("patch") {
Expand Down Expand Up @@ -114,7 +127,10 @@ fn review_inputs() -> Result<Vec<ReviewInput>> {
}
}
inputs.sort_unstable_by_key(|(index, _)| *index);
Ok(inputs.into_iter().map(|(_, input)| input).collect())
Ok(Arguments {
inputs: inputs.into_iter().map(|(_, input)| input).collect(),
chrome: !matches.get_flag("no-chrome"),
})
}

struct HostTerminal {
Expand Down Expand Up @@ -174,14 +190,65 @@ fn host_text(engine: &Engine, review: usize, focus: bool) -> Result<String> {
let focus = if focus { "viewer" } else { "host" };
Ok(format!(
"Host pane\nFocus: {focus}\nReview: {}\nState: {state}\n\n{location}\n\n\
Tab switch focus\nr next review\no reopen review\nc close review\nq exit host\n\n\
Tab switch focus\nr next review\no reopen review\nc close review\n\
m mark selection\n' select last mark\nq exit host\n\n\
Viewer keys stay local.",
review + 1
))
}

/// The host's own status row, used when the viewer draws no footer.
fn status_text(engine: &Engine, marks: usize) -> String {
let status = engine.status();
let state = if status.closed {
"Review closed"
} else if let Some(error) = status.error {
error
} else if status.loading {
"Loading patch…"
} else if status.coloring || status.preparing_source {
"Coloring visible code…"
} else if status.source_failed {
"Source unavailable · patch view retained"
} else {
"Ready"
};
format!(" {state} · {} files · {marks} marks", status.files)
}

/// Marks the selection, or the cursor line when nothing is selected.
fn mark(engine: &mut Engine, marks: &mut Vec<Marker>) -> Result<()> {
let range = match engine.selection() {
Some(range) => range,
None => {
let Some(source) = engine.selected_source()? else {
return Ok(());
};
let line = match source.side {
Side::Old => source.old_line,
Side::New => source.new_line,
};
let Some(line) = line else {
return Ok(());
};
SourceRange {
review: source.review,
file: source.file,
side: source.side,
first: line,
last: line,
}
}
};
marks.push(Marker {
range,
style: Style::new().fg(Color::Yellow),
});
engine.set_markers(marks)
}

fn run() -> Result<()> {
let inputs = review_inputs()?;
let Arguments { inputs, chrome } = review_inputs()?;
let (wake, ready) = mpsc::sync_channel(1);
let events = TerminalInput::start(wake.clone())?;
terminal::enable_raw_mode()?;
Expand All @@ -198,10 +265,12 @@ fn run() -> Result<()> {
Options {
layout: Layout::Split,
sidebar: SidebarPreference::Hide,
chrome,
..Options::default()
},
wake,
)?;
let mut marks = Vec::new();
let mut focus = true;
let mut dirty = true;
let mut resized = false;
Expand All @@ -225,6 +294,15 @@ fn run() -> Result<()> {
let width = area.width.min(28);
let beside = Rect::new(area.x, area.y, width, area.height);
viewer = Rect::new(area.x + width, area.y, area.width - width, area.height);
if !chrome {
// Without viewer chrome, the host owns a status row below the diff.
viewer.height = viewer.height.saturating_sub(1);
frame.render_widget(
Paragraph::new(status_text(&engine, marks.len())),
Rect::new(viewer.x, viewer.bottom(), viewer.width, 1)
.intersection(area),
);
}
rendered = engine.draw(frame, viewer).and_then(|()| {
let text = host_text(&engine, review, focus)?;
frame.render_widget(
Expand Down Expand Up @@ -264,6 +342,7 @@ fn run() -> Result<()> {
}
KeyCode::Char('c') => {
engine.close()?;
marks.clear();
dirty = true;
continue;
}
Expand All @@ -272,6 +351,24 @@ fn run() -> Result<()> {
review = (review + 1) % inputs.len();
}
engine.replace(inputs[review].open())?;
marks.clear();
dirty = true;
continue;
}
KeyCode::Char('m') if !engine.status().closed => {
mark(&mut engine, &mut marks)?;
dirty = true;
continue;
}
KeyCode::Char('\'') => {
// A mark on revealed context leaves the diff if its source is
// withdrawn; the error is recoverable, so drop that mark.
if let Some(last) = marks.last()
&& engine.select_range(last.range).is_err()
{
marks.pop();
engine.set_markers(&marks)?;
}
dirty = true;
continue;
}
Expand Down
5 changes: 5 additions & 0 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ pub struct App {
pub horizontal: usize,
pub wrap: bool,
pub numbers: bool,
/// Draws the label row, footer and help overlay. Hosts that own those rows turn it off.
pub chrome: bool,
pub help: bool,
pub cache: Cache,
pub geometry: crate::geometry::Cache,
Expand All @@ -65,6 +67,7 @@ pub struct App {
pub worker: Worker,
pub(crate) search_match: Option<crate::reading::SearchMatch>,
pub(crate) selection: Option<crate::reading::LineSelection>,
pub(crate) markers: crate::engine::markers::Markers,
reading_anchor: Option<ReadingAnchor>,
}

Expand Down Expand Up @@ -92,12 +95,14 @@ impl App {
worker,
search_match: None,
selection: None,
markers: Default::default(),
top: Position::default(),
cursor: Position::default(),
old_side: false,
horizontal: 0,
wrap: false,
numbers: true,
chrome: true,
help: false,
cache: Cache::default(),
geometry: crate::geometry::Cache::default(),
Expand Down
1 change: 1 addition & 0 deletions src/app/controls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ impl App {
self.sidebar.notice = None;
let mut highlight = true;
match command {
Command::Help if !self.chrome => return Ok(InputEffect::Ignored),
Command::Help => {
self.help = !self.help;
highlight = false;
Expand Down
39 changes: 27 additions & 12 deletions src/app/sidebar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,16 @@ impl App {
self.sidebar.preference = preference;
}

/// The pane height that view movement reasons about. It always counts the label and
/// footer rows, so without chrome the diff rows fill the whole supplied rectangle.
pub(crate) fn layout_height(&self, screen: u16) -> u16 {
if self.chrome {
screen
} else {
screen.saturating_add(2)
}
}

pub(crate) fn prepare_view(&mut self, screen: Rect) -> anyhow::Result<()> {
for file in &self.doc.files[self.sidebar.tree.len()..] {
self.sidebar.tree.append(file)?;
Expand All @@ -140,24 +150,21 @@ impl App {
SidebarPreference::Show => true,
SidebarPreference::Hide => false,
};
let shown = wants_tree && screen.width >= MIN_WIDTH && screen.height >= 10;
let height = self.layout_height(screen.height);
let top = screen.y + u16::from(self.chrome);
let shown = wants_tree && screen.width >= MIN_WIDTH && height >= 10;
if shown {
self.sidebar.notice = None;
}
self.sidebar.screen = screen;
self.sidebar.area = if shown {
Rect::new(screen.x, screen.y + 1, TREE_WIDTH, screen.height - 2)
Rect::new(screen.x, top, TREE_WIDTH, height - 2)
} else {
Rect::default()
};
let inset = if shown { TREE_WIDTH + 1 } else { 0 };
self.sidebar.diff = if screen.width >= 40 && screen.height >= 10 {
Rect::new(
screen.x + inset,
screen.y + 1,
screen.width - inset,
screen.height - 2,
)
self.sidebar.diff = if screen.width >= 40 && height >= 10 {
Rect::new(screen.x + inset, top, screen.width - inset, height - 2)
} else {
Rect::default()
};
Expand All @@ -169,20 +176,28 @@ impl App {
self.visible.clear();
return Ok(());
}
let changed = self.width != self.sidebar.diff.width || self.height != screen.height;
let changed = self.width != self.sidebar.diff.width || self.height != height;
if changed {
self.reflow(self.layout, self.sidebar.diff.width, screen.height)?;
self.reflow(self.layout, self.sidebar.diff.width, height)?;
}
Ok(())
}

/// Gives the diff keyboard focus and closes help, as a host-requested move expects.
pub(crate) fn focus_diff(&mut self) {
self.sidebar.focus = Focus::Diff;
self.help = false;
}

pub(crate) fn files_command(&mut self) -> anyhow::Result<()> {
if self.sidebar.focused() {
self.sidebar.preference = SidebarPreference::Hide;
self.sidebar.focus = Focus::Diff;
} else {
self.sidebar.preference = SidebarPreference::Show;
if self.sidebar.screen.width < MIN_WIDTH || self.sidebar.screen.height < 10 {
if self.sidebar.screen.width < MIN_WIDTH
|| self.layout_height(self.sidebar.screen.height) < 10
{
self.sidebar.notice = Some("Files need at least 97 columns × 10 rows");
} else {
self.sidebar.focus = Focus::Files;
Expand Down
Loading
Loading