Initial public release
Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
138
crates/luxe-tui/src/view/changes/cells.rs
Normal file
138
crates/luxe-tui/src/view/changes/cells.rs
Normal file
@@ -0,0 +1,138 @@
|
||||
//! Code cells — where each drawn row's code sits, so the pane's text can be selected and the
|
||||
//! selection painted.
|
||||
//!
|
||||
//! The renderers know which source row a drawn row shows, where its code starts and which stretch of
|
||||
//! a wrapped line it holds; this turns that into selectable text for the pointer and paints the
|
||||
//! pick over the cells it covers. Gutters are never published, so a drag over line numbers is left
|
||||
//! to the line pick and a copy never carries them.
|
||||
|
||||
use crate::app::App;
|
||||
use crate::changes::ChangesView;
|
||||
use crate::mouse::{PeekSide, TextRow, TextSurface};
|
||||
use crate::view::transcript::selection::highlight_columns;
|
||||
use ratatui::{layout::Rect, text::Line};
|
||||
use std::ops::Range;
|
||||
|
||||
/// One drawn piece of a source row.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct CodeCell {
|
||||
/// Row in the pane's row space
|
||||
pub(super) row: usize,
|
||||
/// Column of a side-by-side diff it sits in, or `Whole`
|
||||
pub(super) side: PeekSide,
|
||||
/// Cells from the body's left edge to the code
|
||||
pub(super) x: u16,
|
||||
/// Cells of code the drawn row has room for
|
||||
pub(super) width: u16,
|
||||
/// Column of the whole line this piece starts at
|
||||
pub(super) first_column: usize,
|
||||
/// Cells the whole line takes, so a pick running to its end stops there
|
||||
pub(super) line_width: usize,
|
||||
}
|
||||
|
||||
/// Where the code of each drawn piece of a source line sits: one piece unwrapped, one per wrapped
|
||||
/// row otherwise, each `width` cells wide starting `x` cells in.
|
||||
pub(super) fn code_pieces(
|
||||
text: &str,
|
||||
row: usize,
|
||||
side: PeekSide,
|
||||
(x, width): (usize, usize),
|
||||
wrap: bool,
|
||||
) -> Vec<CodeCell> {
|
||||
let drawn = crate::tabstop::display_text(text);
|
||||
let line_width = crate::selection::cell_width(&drawn);
|
||||
let cells = |value: usize| u16::try_from(value).unwrap_or(u16::MAX);
|
||||
piece_starts(&drawn, width, wrap)
|
||||
.into_iter()
|
||||
.map(|first_column| CodeCell {
|
||||
row,
|
||||
side,
|
||||
x: cells(x),
|
||||
width: cells(width),
|
||||
first_column,
|
||||
line_width,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Columns of the whole line each drawn piece starts at, when `text` wraps at `width` cells.
|
||||
///
|
||||
/// The break rule of [`crate::widgets::wrap_cells`], so the pieces line up with what it drew, but
|
||||
/// counted rather than built: this runs for every row of every frame.
|
||||
fn piece_starts(text: &str, width: usize, wrap: bool) -> Vec<usize> {
|
||||
let mut starts = vec![0];
|
||||
if !wrap {
|
||||
return starts;
|
||||
}
|
||||
let (mut column, mut used) = (0usize, 0usize);
|
||||
for character in text.chars() {
|
||||
let cells = unicode_width::UnicodeWidthChar::width(character).unwrap_or(0);
|
||||
if used + cells > width && used > 0 {
|
||||
starts.push(column);
|
||||
used = 0;
|
||||
}
|
||||
used += cells;
|
||||
column += cells;
|
||||
}
|
||||
starts
|
||||
}
|
||||
|
||||
/// Publishes every piece as selectable text and paints the pick over the pieces it covers.
|
||||
///
|
||||
/// `cells[i]` describes `lines[i]`, the `i`th row down from `body`'s top.
|
||||
pub(super) fn publish_and_paint(
|
||||
app: &App,
|
||||
view: &ChangesView,
|
||||
lines: &mut [Line<'static>],
|
||||
cells: &[Vec<CodeCell>],
|
||||
body: Rect,
|
||||
) {
|
||||
let mut hit = app.hit.borrow_mut();
|
||||
for (index, (line, pieces)) in lines.iter_mut().zip(cells).enumerate() {
|
||||
let y = body.y.saturating_add(u16::try_from(index).unwrap_or(u16::MAX));
|
||||
if y >= body.bottom() {
|
||||
break;
|
||||
}
|
||||
for piece in pieces {
|
||||
let x = body.x + piece.x;
|
||||
let width = piece.width.min(body.right().saturating_sub(x));
|
||||
let row = TextRow {
|
||||
surface: TextSurface::Peek(piece.side),
|
||||
line: piece.row,
|
||||
x,
|
||||
first_column: piece.first_column,
|
||||
pin: None,
|
||||
};
|
||||
hit.push_text(Rect::new(x, y, width, 1), row);
|
||||
if let Some(columns) = drawn_pick(view, piece) {
|
||||
*line = highlight_columns(line, columns, app.theme_styles.selected_bg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pick's columns on `piece`, moved from the whole line onto the drawn row.
|
||||
fn drawn_pick(view: &ChangesView, piece: &CodeCell) -> Option<Range<usize>> {
|
||||
let pick = view.cells?;
|
||||
let covered = pick.columns_on(view.view, piece.side, piece.row, piece.line_width)?;
|
||||
let start = covered.start.max(piece.first_column);
|
||||
let end = covered.end.min(piece.first_column + usize::from(piece.width));
|
||||
let shift = |column: usize| column - piece.first_column + usize::from(piece.x);
|
||||
(start < end).then(|| shift(start)..shift(end))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A wrapped line's pieces start where the one before ended; a wide glyph that will not fit
|
||||
/// moves whole to the next piece, so that piece starts a cell early.
|
||||
#[test]
|
||||
fn pieces_start_where_the_wrap_broke() {
|
||||
assert_eq!(piece_starts("abcdefgh", 3, true), vec![0, 3, 6]);
|
||||
// `ab`, then `日c`, then `d`
|
||||
assert_eq!(piece_starts("ab\u{65e5}cd", 3, true), vec![0, 2, 5]);
|
||||
assert_eq!(piece_starts("abcdefgh", 3, false), vec![0], "unwrapped is one piece");
|
||||
assert_eq!(piece_starts("", 3, true), vec![0], "an empty line is still a row");
|
||||
}
|
||||
}
|
||||
382
crates/luxe-tui/src/view/changes/diff.rs
Normal file
382
crates/luxe-tui/src/view/changes/diff.rs
Normal file
@@ -0,0 +1,382 @@
|
||||
//! Changes diff — the diff's rows, windowed to the pane, unified or side by side.
|
||||
|
||||
use super::cells::{code_pieces, publish_and_paint, CodeCell};
|
||||
use super::split::split_lines;
|
||||
use crate::app::App;
|
||||
use crate::changes::{ChangesView, PeekView};
|
||||
use crate::mouse::PeekSide;
|
||||
use crate::theme::styles::ThemeStyles;
|
||||
use crate::view::diff_lines::{
|
||||
changed_spans, clip_styled_spans, diff_line_background, highlighted_source_spans,
|
||||
intraline_emphasis, line_style, owned_spans as owned, rendered_marker, tint_row,
|
||||
IntralineEmphasis,
|
||||
};
|
||||
use crate::view::emphasis;
|
||||
use luxe_core::guided_review::{ReviewFile, ReviewLine, ReviewLineKind};
|
||||
use ratatui::{
|
||||
layout::Rect,
|
||||
style::Style,
|
||||
text::{Line, Span},
|
||||
widgets::Paragraph,
|
||||
Frame,
|
||||
};
|
||||
|
||||
/// One row of the pane's own row space.
|
||||
///
|
||||
/// Flat, like the review's, so the offset the reader scrolls is an index into something the
|
||||
/// renderer can walk without materializing the whole file.
|
||||
enum DiffRow<'a> {
|
||||
/// A hunk's orientation band, drawn under a blank when it is not the first.
|
||||
Header(&'a luxe_core::guided_review::ReviewHunk),
|
||||
/// One source line.
|
||||
Source(&'a ReviewLine),
|
||||
}
|
||||
|
||||
/// Every hunk of `file`, windowed to what fits, with a scrollbar when there is more.
|
||||
pub(super) fn render_diff(
|
||||
frame: &mut Frame,
|
||||
area: Rect,
|
||||
app: &App,
|
||||
view: &ChangesView,
|
||||
file: &ReviewFile,
|
||||
) {
|
||||
let (body, scrollbar) = if area.width > 2 {
|
||||
(
|
||||
Rect { width: area.width.saturating_sub(1), ..area },
|
||||
Some(Rect { x: area.right().saturating_sub(1), width: 1, ..area }),
|
||||
)
|
||||
} else {
|
||||
(area, None)
|
||||
};
|
||||
let viewport = usize::from(body.height);
|
||||
let numbers = crate::guided_review::diff::gutter_width(&file.hunks);
|
||||
|
||||
// One row space for both layouts — a hunk header, then its lines — so the offset means the same
|
||||
// thing either way and toggling the layout keeps the reader where they were.
|
||||
let rows = diff_rows(file);
|
||||
let sources: Vec<Option<&ReviewLine>> = rows
|
||||
.iter()
|
||||
.map(|row| match row {
|
||||
DiffRow::Source(line) => Some(*line),
|
||||
DiffRow::Header(_) => None,
|
||||
})
|
||||
.collect();
|
||||
let emphasized = intraline_emphasis(&sources);
|
||||
|
||||
let unified_gutter = numbers * 2 + 3;
|
||||
let unified_code = usize::from(body.width).saturating_sub(unified_gutter).max(4);
|
||||
let split = crate::view::diff_lines::split_layout(
|
||||
&app.theme_styles,
|
||||
body.width,
|
||||
numbers,
|
||||
0,
|
||||
file.language.as_deref(),
|
||||
);
|
||||
let side_by_side = view.split_active(app.config.diff.layout(), split.source, Some(file));
|
||||
|
||||
// Scroll bounds come from the *unified* heights whichever layout is showing. Side-by-side pairs
|
||||
// rows together, so it always shows at least as much as unified from the same offset — which
|
||||
// makes this bound reachable in both and dead space at the bottom impossible in either.
|
||||
let heights: Vec<usize> = rows
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, row)| row_height(row, index, view.word_wrap, unified_code))
|
||||
.collect();
|
||||
view.viewport_rows.set(viewport.max(1));
|
||||
view.scroll_max.set(max_offset(&heights, viewport));
|
||||
let offset = view.scroll.min(view.scroll_max.get());
|
||||
|
||||
let (mut lines, cells) = if side_by_side {
|
||||
split_lines(file, &split, view, offset, viewport)
|
||||
} else {
|
||||
let context = UnifiedRowContext {
|
||||
file,
|
||||
styles: &app.theme_styles,
|
||||
word_wrap: view.word_wrap,
|
||||
emphasized: &emphasized,
|
||||
numbers,
|
||||
gutter_width: unified_gutter,
|
||||
code_width: unified_code,
|
||||
width: body.width,
|
||||
};
|
||||
unified_lines(&rows, &context, offset, viewport)
|
||||
};
|
||||
|
||||
publish_and_paint(app, view, &mut lines, &cells, body);
|
||||
frame.render_widget(Paragraph::new(lines), body);
|
||||
if let Some(scrollbar) = scrollbar {
|
||||
let consumed: usize = heights.iter().take(offset).sum();
|
||||
crate::widgets::steered_scrollbar(
|
||||
frame,
|
||||
&mut app.hit.borrow_mut(),
|
||||
scrollbar,
|
||||
crate::mouse::ScrollRegionId::Changes,
|
||||
consumed,
|
||||
heights.iter().sum(),
|
||||
viewport,
|
||||
&app.theme_styles,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The pane's row space: each hunk's header, then its lines.
|
||||
///
|
||||
/// The same shape `visible_split_rows` counts in, so the two layouts share one offset and toggling
|
||||
/// between them keeps the reader where they were.
|
||||
fn diff_rows(file: &ReviewFile) -> Vec<DiffRow<'_>> {
|
||||
let mut rows = Vec::new();
|
||||
for hunk in &file.hunks {
|
||||
rows.push(DiffRow::Header(hunk));
|
||||
rows.extend(hunk.lines.iter().map(DiffRow::Source));
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// The line of the new file at the top of the pane, for opening the file there: the first row in
|
||||
/// view, a hunk's header standing for its first line.
|
||||
pub(crate) fn line_in_view(view: &ChangesView) -> Option<u32> {
|
||||
// The File view's rows are the file's own lines, and a pick says which one the reader means
|
||||
if view.view == PeekView::File {
|
||||
let standing = view.cursor.filter(|_| view.focused).unwrap_or_else(|| view.top_line());
|
||||
return Some(view.selected_lines().map_or(standing, |(first, _)| first));
|
||||
}
|
||||
let file = view.file()?;
|
||||
let mut row = 0usize;
|
||||
for hunk in &file.hunks {
|
||||
if row >= view.scroll {
|
||||
return (hunk.new_range.start > 0).then_some(hunk.new_range.start);
|
||||
}
|
||||
row += 1;
|
||||
for index in 0..hunk.lines.len() {
|
||||
if row >= view.scroll {
|
||||
return crate::guided_review::new_side_line(hunk, index);
|
||||
}
|
||||
row += 1;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Visual lines one row occupies at this width.
|
||||
///
|
||||
/// A hunk header past the first carries the blank that separates it from the hunk above, so the
|
||||
/// separator costs a line without costing a row — which is what keeps the row space identical to
|
||||
/// the one side-by-side counts in.
|
||||
fn row_height(row: &DiffRow<'_>, index: usize, word_wrap: bool, code_width: usize) -> usize {
|
||||
match row {
|
||||
DiffRow::Header(_) => 1 + usize::from(index > 0),
|
||||
DiffRow::Source(line) if word_wrap => {
|
||||
let cells = crate::tabstop::display_width(&line.text);
|
||||
cells.div_ceil(code_width.max(1)).max(1)
|
||||
}
|
||||
DiffRow::Source(_) => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// What every unified row is drawn against.
|
||||
struct UnifiedRowContext<'a> {
|
||||
file: &'a ReviewFile,
|
||||
styles: &'a ThemeStyles,
|
||||
word_wrap: bool,
|
||||
emphasized: &'a IntralineEmphasis,
|
||||
/// Digits each line number takes
|
||||
numbers: usize,
|
||||
gutter_width: usize,
|
||||
code_width: usize,
|
||||
width: u16,
|
||||
}
|
||||
|
||||
/// One unified row as the visual lines it occupies.
|
||||
fn render_row(row: &DiffRow<'_>, index: usize, ctx: &UnifiedRowContext<'_>) -> Vec<Line<'static>> {
|
||||
match row {
|
||||
DiffRow::Header(hunk) => {
|
||||
let header = hunk_header_line(
|
||||
hunk.old_range,
|
||||
hunk.new_range,
|
||||
hunk.heading.as_deref(),
|
||||
ctx.styles,
|
||||
Some(ctx.width),
|
||||
);
|
||||
if index > 0 {
|
||||
vec![Line::default(), header]
|
||||
} else {
|
||||
vec![header]
|
||||
}
|
||||
}
|
||||
DiffRow::Source(line) if ctx.word_wrap => wrapped_source_rows(line, index, ctx),
|
||||
DiffRow::Source(line) => vec![clipped_source_row(line, index, ctx)],
|
||||
}
|
||||
}
|
||||
|
||||
/// A source line's `old new sign` gutter.
|
||||
fn unified_gutter(line: &ReviewLine, ctx: &UnifiedRowContext<'_>) -> Vec<Span<'static>> {
|
||||
let numbers = ctx.numbers;
|
||||
let old =
|
||||
line.old_line.map_or_else(|| " ".repeat(numbers), |number| format!("{number:>numbers$}"));
|
||||
let new =
|
||||
line.new_line.map_or_else(|| " ".repeat(numbers), |number| format!("{number:>numbers$}"));
|
||||
vec![
|
||||
Span::styled(format!("{old} {new} "), ctx.styles.muted),
|
||||
Span::styled(rendered_marker(line.kind), line_style(line.kind, ctx.styles)),
|
||||
]
|
||||
}
|
||||
|
||||
/// A source line wrapped to the code column, each row after the first behind a continuation mark.
|
||||
fn wrapped_source_rows(
|
||||
line: &ReviewLine,
|
||||
index: usize,
|
||||
ctx: &UnifiedRowContext<'_>,
|
||||
) -> Vec<Line<'static>> {
|
||||
let styles = ctx.styles;
|
||||
let changed = changed_spans(ctx.emphasized, index);
|
||||
let background = diff_line_background(line.kind, styles);
|
||||
let full = crate::view::diff_lines::source_spans(
|
||||
line,
|
||||
changed,
|
||||
ctx.file.language.as_deref(),
|
||||
styles,
|
||||
false,
|
||||
);
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
for (segment_index, segment) in
|
||||
crate::widgets::wrap_cells(full, ctx.code_width).into_iter().enumerate()
|
||||
{
|
||||
let mut spans = if segment_index == 0 {
|
||||
unified_gutter(line, ctx)
|
||||
} else {
|
||||
vec![Span::styled(
|
||||
format!(
|
||||
"{}{}",
|
||||
" ".repeat(ctx.gutter_width.saturating_sub(1)),
|
||||
crate::glyphs::Mark::Continuation
|
||||
),
|
||||
styles.dim,
|
||||
)]
|
||||
};
|
||||
spans.extend(segment);
|
||||
lines.push(finish(spans, background, ctx.width));
|
||||
}
|
||||
if lines.is_empty() {
|
||||
lines.push(finish(unified_gutter(line, ctx), background, ctx.width));
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// A source line clipped to the code column, marked where it runs past the edge.
|
||||
fn clipped_source_row(
|
||||
line: &ReviewLine,
|
||||
index: usize,
|
||||
ctx: &UnifiedRowContext<'_>,
|
||||
) -> Line<'static> {
|
||||
let (styles, code_width) = (ctx.styles, ctx.code_width);
|
||||
let style = line_style(line.kind, styles);
|
||||
let changed = changed_spans(ctx.emphasized, index);
|
||||
let background = diff_line_background(line.kind, styles);
|
||||
// Without wrapping there is no horizontal scroll either, so a line that runs past
|
||||
// the edge has to say so — a clipped statement reads as a complete one, which in a
|
||||
// diff is a claim about the code.
|
||||
let source = crate::tabstop::display_text(&line.text);
|
||||
let clipped = crate::tabstop::display_width(&line.text) > code_width;
|
||||
let room = if clipped { code_width.saturating_sub(1) } else { code_width };
|
||||
let mut spans = unified_gutter(line, ctx);
|
||||
spans.extend(match line.kind {
|
||||
ReviewLineKind::Context => highlighted_source_spans(
|
||||
&crate::guided_review::diff::clip_terminal_cells(&source, 0, room),
|
||||
ctx.file.language.as_deref(),
|
||||
styles,
|
||||
),
|
||||
_ => owned(clip_styled_spans(
|
||||
&emphasis::parts(
|
||||
&source,
|
||||
changed,
|
||||
style,
|
||||
styles.diff_emphasis(style, line.kind == ReviewLineKind::Addition),
|
||||
),
|
||||
0,
|
||||
room,
|
||||
)),
|
||||
});
|
||||
if clipped {
|
||||
spans.push(Span::styled("…", styles.dim));
|
||||
}
|
||||
finish(spans, background, ctx.width)
|
||||
}
|
||||
|
||||
/// The largest offset that still puts the last row on screen.
|
||||
fn max_offset(heights: &[usize], viewport: usize) -> usize {
|
||||
let mut used = 0usize;
|
||||
for (index, height) in heights.iter().enumerate().rev() {
|
||||
used = used.saturating_add(*height);
|
||||
if used > viewport {
|
||||
return index + 1;
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
/// The drawn rows, and where each one's code sits.
|
||||
pub(super) type DrawnRows = (Vec<Line<'static>>, Vec<Vec<CodeCell>>);
|
||||
|
||||
/// The unified list: `old new sign source`, one row per line.
|
||||
fn unified_lines(
|
||||
rows: &[DiffRow<'_>],
|
||||
ctx: &UnifiedRowContext<'_>,
|
||||
offset: usize,
|
||||
viewport: usize,
|
||||
) -> DrawnRows {
|
||||
let mut drawn: DrawnRows = (Vec::with_capacity(viewport), Vec::with_capacity(viewport));
|
||||
for (index, row) in rows.iter().enumerate().skip(offset) {
|
||||
if drawn.0.len() >= viewport {
|
||||
break;
|
||||
}
|
||||
let pieces = match row {
|
||||
DiffRow::Source(line) => {
|
||||
let at = (ctx.gutter_width, ctx.code_width);
|
||||
code_pieces(&line.text, index, PeekSide::Whole, at, ctx.word_wrap)
|
||||
}
|
||||
DiffRow::Header(_) => Vec::new(),
|
||||
};
|
||||
for (piece, line) in render_row(row, index, ctx).into_iter().enumerate() {
|
||||
if drawn.0.len() >= viewport {
|
||||
break;
|
||||
}
|
||||
drawn.0.push(line);
|
||||
drawn.1.push(pieces.get(piece).copied().into_iter().collect());
|
||||
}
|
||||
}
|
||||
drawn
|
||||
}
|
||||
|
||||
/// `@@ -1,2 +1,2 @@ fn sum` — the band that opens a hunk, in either layout.
|
||||
pub(super) fn hunk_header_line(
|
||||
old: luxe_core::guided_review::LineRange,
|
||||
new: luxe_core::guided_review::LineRange,
|
||||
heading: Option<&str>,
|
||||
styles: &crate::theme::styles::ThemeStyles,
|
||||
clip: Option<u16>,
|
||||
) -> Line<'static> {
|
||||
let heading = heading
|
||||
.filter(|heading| !heading.trim().is_empty())
|
||||
.map(|heading| format!(" {heading}"))
|
||||
.unwrap_or_default();
|
||||
let text = format!("@@ -{},{} +{},{} @@{heading}", old.start, old.count, new.start, new.count);
|
||||
let text = match clip {
|
||||
Some(width) => {
|
||||
crate::guided_review::diff::clip_terminal_cells(&text, 0, usize::from(width))
|
||||
}
|
||||
None => text,
|
||||
};
|
||||
Line::from(Span::styled(text, styles.accent))
|
||||
}
|
||||
|
||||
/// Detaches spans from the source line they were clipped out of.
|
||||
///
|
||||
/// The pane hands finished `Line`s back to its caller, so nothing may still borrow the review file
|
||||
/// they came from.
|
||||
/// Closes one rendered row, laying the changed-row tint across its full width.
|
||||
fn finish(spans: Vec<Span<'static>>, background: Option<Style>, width: u16) -> Line<'static> {
|
||||
match background {
|
||||
Some(background) => Line::from(tint_row(spans, background, width)),
|
||||
None => Line::from(spans),
|
||||
}
|
||||
}
|
||||
234
crates/luxe-tui/src/view/changes/footer.rs
Normal file
234
crates/luxe-tui/src/view/changes/footer.rs
Normal file
@@ -0,0 +1,234 @@
|
||||
//! Changes footer — the pane's shortcuts, fitted to the width it has.
|
||||
|
||||
use crate::app::App;
|
||||
use crate::changes::{ChangesView, PeekView};
|
||||
use crate::mouse::{ChangesFooterAction, MouseTarget};
|
||||
use ratatui::{
|
||||
layout::Rect,
|
||||
style::Modifier,
|
||||
text::{Line, Span},
|
||||
widgets::Paragraph,
|
||||
Frame,
|
||||
};
|
||||
|
||||
/// One clickable footer shortcut: its chord, then what it does.
|
||||
struct Shortcut {
|
||||
chord: String,
|
||||
label: &'static str,
|
||||
action: ChangesFooterAction,
|
||||
}
|
||||
|
||||
impl Shortcut {
|
||||
/// Cells this shortcut occupies, its separating space included.
|
||||
fn width(&self) -> usize {
|
||||
self.chord.chars().count() + 1 + self.label.chars().count()
|
||||
}
|
||||
}
|
||||
|
||||
/// Cells between two shortcuts.
|
||||
const SHORTCUT_GAP: usize = 3;
|
||||
|
||||
/// Which shortcut yields first when the footer will not fit.
|
||||
///
|
||||
/// Least actionable first, and `close` is never in the list: a surface that has taken the column
|
||||
/// must always say how to give it back. Dropping whole shortcuts rather than letting the row
|
||||
/// truncate is the point — `Alt+W no wr` is worse than no mention of wrapping at all.
|
||||
const SHORTCUT_SACRIFICE: [ChangesFooterAction; 7] = [
|
||||
ChangesFooterAction::FilePrev,
|
||||
ChangesFooterAction::Focus,
|
||||
ChangesFooterAction::ToggleView,
|
||||
ChangesFooterAction::ToggleWordWrap,
|
||||
ChangesFooterAction::OpenInEditor,
|
||||
ChangesFooterAction::ToggleSplit,
|
||||
ChangesFooterAction::FileNext,
|
||||
];
|
||||
|
||||
/// Drops shortcuts by priority until the row fits `width`.
|
||||
fn fit_shortcuts(shortcuts: &mut Vec<Shortcut>, width: usize) {
|
||||
let rendered = |shortcuts: &Vec<Shortcut>| {
|
||||
shortcuts.iter().map(Shortcut::width).sum::<usize>()
|
||||
+ SHORTCUT_GAP * shortcuts.len().saturating_sub(1)
|
||||
};
|
||||
for action in SHORTCUT_SACRIFICE {
|
||||
if rendered(shortcuts) <= width {
|
||||
return;
|
||||
}
|
||||
shortcuts.retain(|shortcut| shortcut.action != action);
|
||||
}
|
||||
// Whatever is left over: trim from the end, so `Esc close` is the last thing standing.
|
||||
while rendered(shortcuts) > width && shortcuts.len() > 1 {
|
||||
shortcuts.remove(shortcuts.len() - 2);
|
||||
}
|
||||
}
|
||||
|
||||
/// The keys that do something here, and only those.
|
||||
///
|
||||
/// Chords are read from the live keymap rather than typed in, so a remapped binding cannot leave
|
||||
/// the footer advertising a key that does nothing. Stepping disappears when there is nowhere to
|
||||
/// step: a control that cannot act is worse than an absent one.
|
||||
fn shortcuts(app: &App, view: &ChangesView, side_by_side: bool) -> Vec<Shortcut> {
|
||||
use luxe_core::keymap::UiAction;
|
||||
let chord = |action: UiAction, fallback: &str| {
|
||||
app.keymap
|
||||
.chords_for(action)
|
||||
.and_then(|chords| chords.first())
|
||||
.map_or_else(|| fallback.to_string(), ToString::to_string)
|
||||
};
|
||||
if view.focused {
|
||||
return focused_shortcuts(view);
|
||||
}
|
||||
let mut shortcuts = Vec::new();
|
||||
if view.changed() {
|
||||
shortcuts.push(Shortcut {
|
||||
chord: chord(UiAction::ChangesToggleView, "alt+m"),
|
||||
label: match view.view {
|
||||
PeekView::Diff => "whole file",
|
||||
PeekView::File => "changes",
|
||||
},
|
||||
action: ChangesFooterAction::ToggleView,
|
||||
});
|
||||
}
|
||||
if view.files.len() > 1 && view.changed() {
|
||||
shortcuts.push(Shortcut {
|
||||
chord: chord(UiAction::ChangesFileNext, "alt+n"),
|
||||
label: "next file",
|
||||
action: ChangesFooterAction::FileNext,
|
||||
});
|
||||
shortcuts.push(Shortcut {
|
||||
chord: chord(UiAction::ChangesFilePrev, "alt+p"),
|
||||
label: "previous",
|
||||
action: ChangesFooterAction::FilePrev,
|
||||
});
|
||||
}
|
||||
// Only where the pane could actually draw two columns: a control that cannot act is worse than
|
||||
// an absent one, because pressing it teaches the reader that the footer is not to be trusted.
|
||||
// Mid-switch `side_by_side` carries the last resolved layout, which is what keeps this from
|
||||
// blinking out for the frame the next diff spends loading.
|
||||
let diffing = view.view == PeekView::Diff;
|
||||
if diffing
|
||||
&& (view.two_sided.get() || view.file().is_some_and(crate::guided_review::has_two_sides))
|
||||
{
|
||||
shortcuts.push(Shortcut {
|
||||
chord: chord(UiAction::ReviewToggleSplit, "/diff"),
|
||||
// Name the layout it switches *to*, and say what the layout is *of*: "side by side"
|
||||
// alone reads as a property of the pane rather than of the diff in it.
|
||||
label: if side_by_side { "unified diff" } else { "side-by-side diff" },
|
||||
action: ChangesFooterAction::ToggleSplit,
|
||||
});
|
||||
}
|
||||
shortcuts.push(Shortcut {
|
||||
chord: chord(UiAction::ChangesToggleWordWrap, "alt+w"),
|
||||
label: if view.word_wrap { "stop wrapping" } else { "wrap lines" },
|
||||
action: ChangesFooterAction::ToggleWordWrap,
|
||||
});
|
||||
// Only for a file the review could actually contain. A review is captured from the project's
|
||||
// own worktree, so offering it over a file that lives somewhere else advertises a destination
|
||||
// that does not exist.
|
||||
if !luxe_core::file_diff::is_external_path(&view.path) && view.changed() {
|
||||
shortcuts.push(Shortcut {
|
||||
chord: chord(UiAction::ReviewOpen, "/diff"),
|
||||
label: "review this file",
|
||||
action: ChangesFooterAction::OpenReview,
|
||||
});
|
||||
}
|
||||
shortcuts.push(Shortcut {
|
||||
chord: chord(UiAction::ChangesOpenInEditor, "/editor"),
|
||||
label: "open in editor",
|
||||
action: ChangesFooterAction::OpenInEditor,
|
||||
});
|
||||
shortcuts.push(Shortcut {
|
||||
chord: chord(UiAction::FocusFiles, "ctrl+t"),
|
||||
label: "navigate",
|
||||
action: ChangesFooterAction::Focus,
|
||||
});
|
||||
shortcuts.push(Shortcut {
|
||||
chord: "esc".to_string(),
|
||||
label: "close",
|
||||
action: ChangesFooterAction::Close,
|
||||
});
|
||||
shortcuts
|
||||
}
|
||||
|
||||
/// The keys the pane answers to while the keyboard is in it, which are not the ones it shows
|
||||
/// otherwise: a reader who just walked in needs the way around, and the way out.
|
||||
fn focused_shortcuts(view: &ChangesView) -> Vec<Shortcut> {
|
||||
let keys: &[(&str, &'static str)] = match view.view {
|
||||
PeekView::File if view.visual => &[
|
||||
("VISUAL", "j k grow"),
|
||||
("o", "other end"),
|
||||
("enter", "ask"),
|
||||
("y", "copy"),
|
||||
("esc", "cancel"),
|
||||
],
|
||||
PeekView::File => &[
|
||||
("j k", "line"),
|
||||
("v", "select"),
|
||||
("enter", "ask"),
|
||||
("y", "copy"),
|
||||
("o", "editor"),
|
||||
("tab", "files"),
|
||||
("esc", "back"),
|
||||
],
|
||||
PeekView::Diff => &[
|
||||
("j k", "scroll"),
|
||||
("space", "page"),
|
||||
("g G", "ends"),
|
||||
("o", "editor"),
|
||||
("tab", "files"),
|
||||
("esc", "back"),
|
||||
],
|
||||
};
|
||||
keys.iter()
|
||||
.map(|(chord, label)| Shortcut {
|
||||
chord: (*chord).to_string(),
|
||||
label,
|
||||
action: ChangesFooterAction::Hint,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The footer, with a click region per shortcut so the mouse can do what the keys do.
|
||||
pub(super) fn render_footer(
|
||||
frame: &mut Frame,
|
||||
area: Rect,
|
||||
app: &App,
|
||||
view: &ChangesView,
|
||||
side_by_side: bool,
|
||||
) {
|
||||
let styles = &app.theme_styles;
|
||||
let mut shortcuts = shortcuts(app, view, side_by_side);
|
||||
fit_shortcuts(&mut shortcuts, usize::from(area.width));
|
||||
let mut spans = Vec::new();
|
||||
let mut regions: Vec<(u16, u16, ChangesFooterAction)> = Vec::new();
|
||||
let mut column = 0usize;
|
||||
for (index, shortcut) in shortcuts.iter().enumerate() {
|
||||
if index > 0 {
|
||||
spans.push(Span::styled(" · ", styles.border_muted));
|
||||
column += SHORTCUT_GAP;
|
||||
}
|
||||
let start = column;
|
||||
let hovered = app.pointer.hover == Some(MouseTarget::ChangesFooter(shortcut.action));
|
||||
let key_style =
|
||||
if hovered { styles.accent.add_modifier(Modifier::BOLD) } else { styles.accent };
|
||||
let label_style = if hovered { styles.text } else { styles.muted };
|
||||
spans.push(Span::styled(format!("{} ", shortcut.chord), key_style));
|
||||
spans.push(Span::styled(shortcut.label.to_string(), label_style));
|
||||
column += shortcut.chord.chars().count() + 1 + shortcut.label.chars().count();
|
||||
if let (Ok(x), Ok(span)) =
|
||||
(u16::try_from(start), u16::try_from(column.saturating_sub(start)))
|
||||
{
|
||||
regions.push((x, span, shortcut.action));
|
||||
}
|
||||
}
|
||||
frame.render_widget(Paragraph::new(Line::from(spans)), area);
|
||||
|
||||
let mut hit = app.hit.borrow_mut();
|
||||
for (x, span, action) in regions {
|
||||
let x = area.x.saturating_add(x);
|
||||
if x >= area.right() {
|
||||
continue;
|
||||
}
|
||||
let width = span.min(area.right().saturating_sub(x));
|
||||
hit.push(Rect::new(x, area.y, width, 1), MouseTarget::ChangesFooter(action));
|
||||
}
|
||||
}
|
||||
189
crates/luxe-tui/src/view/changes/header.rs
Normal file
189
crates/luxe-tui/src/view/changes/header.rs
Normal file
@@ -0,0 +1,189 @@
|
||||
//! Changes header — the file's identity, its path and the view tabs above the diff.
|
||||
|
||||
use crate::app::App;
|
||||
use crate::changes::{ChangedFile, ChangesView, PeekView};
|
||||
use crate::mouse::{ChangesFooterAction, MouseTarget};
|
||||
use crate::widgets::truncate_start as truncate_path_left;
|
||||
use ratatui::{
|
||||
layout::Rect,
|
||||
style::{Modifier, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{Block, Borders, Paragraph},
|
||||
Frame,
|
||||
};
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
/// `M src/app/toasts.rs +6 −8 2 of 5`, then a rule.
|
||||
///
|
||||
/// The position counter is the part that makes the pane a browser rather than a dead end: it says
|
||||
/// there are others and that stepping is a thing you can do, which is what the footer's bracket
|
||||
/// keys then explain.
|
||||
pub(super) fn render_header(frame: &mut Frame, area: Rect, app: &App, view: &ChangesView) {
|
||||
let styles = &app.theme_styles;
|
||||
let entry = view.current();
|
||||
let width = usize::from(area.width);
|
||||
|
||||
let position = match (view.position(), view.files.len()) {
|
||||
(Some(index), total) if total > 1 => format!("{} of {total}", index + 1),
|
||||
_ => String::new(),
|
||||
};
|
||||
let counts = entry.and_then(count_label).unwrap_or_default();
|
||||
// Give the path whatever the fixed parts leave, and cut it from the left: the tail of a path
|
||||
// is the file, which is the thing being named. A file outside the project arrives absolute and
|
||||
// is said the way a person would say it, which is also what tells the reader at a glance that
|
||||
// they are not looking at project code.
|
||||
let reserved = position.chars().count() + counts.chars().count() + 6;
|
||||
let titled = home_relative(&view.path);
|
||||
let path = truncate_path_left(&titled, width.saturating_sub(reserved).max(8));
|
||||
|
||||
// A changed file leads with its git letter; any other file with the mark of its language
|
||||
let lead = match entry {
|
||||
Some(file) => {
|
||||
Span::styled(format!("{} ", marker_of(file.status)), status_style(file.status, app))
|
||||
}
|
||||
None => {
|
||||
let extension = view.path.rsplit_once('.').map_or("", |(_, extension)| extension);
|
||||
let icon = crate::widgets::language_icon(&extension.to_ascii_lowercase());
|
||||
Span::styled(
|
||||
crate::glyphs::icon_label(icon.glyph(), ""),
|
||||
crate::widgets::language_hue(icon, styles),
|
||||
)
|
||||
}
|
||||
};
|
||||
let mut spans = vec![lead];
|
||||
spans.push(Span::styled(path, styles.text.add_modifier(Modifier::BOLD)));
|
||||
// What the File view is showing: how long it is, and that it was cut short when it was
|
||||
if let (PeekView::File, crate::changes::TextLoad::Ready(file)) = (view.view, &view.text) {
|
||||
let lines = file.text.lines().count();
|
||||
let mut meta = format!(" {lines} line{}", if lines == 1 { "" } else { "s" });
|
||||
if file.truncated {
|
||||
meta.push_str(" · cut short");
|
||||
}
|
||||
spans.push(Span::styled(meta, styles.muted));
|
||||
}
|
||||
if let Some((additions, deletions)) = entry.and_then(|file| file.additions.zip(file.deletions))
|
||||
{
|
||||
spans.push(Span::styled(format!(" +{additions}"), styles.success));
|
||||
spans.push(Span::styled(format!(" −{deletions}"), styles.error));
|
||||
}
|
||||
// A changed file has two faces, and the one not showing is a click away
|
||||
let tabs = match view.changed() {
|
||||
true => view_tabs(view.view, app),
|
||||
false => ViewTabs::default(),
|
||||
};
|
||||
let tabs_width: usize = tabs.spans.iter().map(|span| span.content.width()).sum();
|
||||
let used: usize = spans.iter().map(|span| UnicodeWidthStr::width(span.content.as_ref())).sum();
|
||||
let tail = tabs_width + position.chars().count() + usize::from(!position.is_empty()) * 2;
|
||||
if tail > 0 {
|
||||
let pad = width.saturating_sub(used + tail);
|
||||
spans.push(Span::raw(" ".repeat(pad)));
|
||||
let tabs_at = used + pad;
|
||||
if let Some((start, cells)) = tabs.other {
|
||||
if let (Ok(x), Ok(cells)) = (u16::try_from(tabs_at + start), u16::try_from(cells)) {
|
||||
app.hit.borrow_mut().push(
|
||||
Rect::new(area.x + x, area.y, cells, 1),
|
||||
MouseTarget::ChangesFooter(ChangesFooterAction::ToggleView),
|
||||
);
|
||||
}
|
||||
}
|
||||
spans.extend(tabs.spans);
|
||||
if !position.is_empty() {
|
||||
spans.push(Span::raw(" "));
|
||||
spans.push(Span::styled(position, styles.muted));
|
||||
}
|
||||
}
|
||||
|
||||
frame.render_widget(Paragraph::new(Line::from(spans)), Rect { height: 1, ..area });
|
||||
if area.height > 1 {
|
||||
frame.render_widget(
|
||||
Block::default().borders(Borders::TOP).border_style(styles.border_muted),
|
||||
Rect { y: area.y + 1, height: 1, ..area },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The FILE / DIFF switch, and where in it the face that is not showing sits.
|
||||
#[derive(Default)]
|
||||
struct ViewTabs {
|
||||
spans: Vec<Span<'static>>,
|
||||
/// `(start, cells)` of the hidden face, measured from the first span — the click target
|
||||
other: Option<(usize, usize)>,
|
||||
}
|
||||
|
||||
/// `FILE DIFF`, both cut into badges: the showing face lit, the other on the idle surface.
|
||||
///
|
||||
/// Both in capitals and both slabs, so the pair reads as a switch with two positions rather than a
|
||||
/// heading with a caption beside it. They are the same width, so neither label moves when the view
|
||||
/// flips, and the hidden face lifts under the pointer to say it is the one a click reaches.
|
||||
fn view_tabs(showing: PeekView, app: &App) -> ViewTabs {
|
||||
let styles = &app.theme_styles;
|
||||
let canvas = styles.background.bg.unwrap_or(styles.slab.canvas);
|
||||
let hovered = app.pointer.hover.as_ref()
|
||||
== Some(&MouseTarget::ChangesFooter(ChangesFooterAction::ToggleView));
|
||||
let mut tabs = ViewTabs::default();
|
||||
for (face, label) in [(PeekView::File, "FILE"), (PeekView::Diff, "DIFF")] {
|
||||
if !tabs.spans.is_empty() {
|
||||
tabs.spans.push(Span::raw(" "));
|
||||
}
|
||||
let start: usize = tabs.spans.iter().map(|span| span.content.width()).sum();
|
||||
let badge = match face == showing {
|
||||
true => {
|
||||
crate::widgets::badge(label, crate::theme::styles::Depth::Raised, canvas, styles)
|
||||
}
|
||||
false => crate::widgets::idle_badge(label, hovered, canvas, styles),
|
||||
};
|
||||
if face != showing {
|
||||
tabs.other = Some((start, badge.iter().map(|span| span.content.width()).sum()));
|
||||
}
|
||||
tabs.spans.extend(badge);
|
||||
}
|
||||
tabs
|
||||
}
|
||||
|
||||
/// A path as a person would say it: `~/.config/ghostty/config`, and a project-relative path
|
||||
/// unchanged.
|
||||
fn home_relative(path: &str) -> String {
|
||||
if luxe_core::file_diff::is_external_path(path) {
|
||||
return luxe_core::paths::home_relative(std::path::Path::new(path));
|
||||
}
|
||||
path.to_string()
|
||||
}
|
||||
|
||||
/// A typed error's message as a line a person reads.
|
||||
///
|
||||
/// Library errors are lowercase by convention because they are usually a clause inside a larger
|
||||
/// sentence. Here the error *is* the sentence, and starting it in lower case reads as a fragment.
|
||||
pub(super) fn sentence(message: &str) -> String {
|
||||
let mut characters = message.chars();
|
||||
characters.next().map_or_else(String::new, |first| {
|
||||
first.to_uppercase().collect::<String>() + characters.as_str()
|
||||
})
|
||||
}
|
||||
|
||||
/// `+6 −8`, or nothing at all when git could not count (a binary blob).
|
||||
fn count_label(file: &ChangedFile) -> Option<String> {
|
||||
let (additions, deletions) = file.additions.zip(file.deletions)?;
|
||||
Some(format!(" +{additions} −{deletions}"))
|
||||
}
|
||||
|
||||
fn marker_of(status: luxe_core::FileChangeStatus) -> &'static str {
|
||||
use luxe_core::FileChangeStatus as Status;
|
||||
match status {
|
||||
Status::Added => "A",
|
||||
Status::Modified => "M",
|
||||
Status::Deleted => "D",
|
||||
Status::Renamed => "R",
|
||||
Status::Untracked => "?",
|
||||
}
|
||||
}
|
||||
|
||||
/// Git-status color, matching the dock rail the reader clicked from.
|
||||
fn status_style(status: luxe_core::FileChangeStatus, app: &App) -> Style {
|
||||
use luxe_core::FileChangeStatus as Status;
|
||||
match status {
|
||||
Status::Added | Status::Untracked => app.theme_styles.success,
|
||||
Status::Modified => app.theme_styles.warning,
|
||||
Status::Deleted => app.theme_styles.error,
|
||||
Status::Renamed => app.theme_styles.info,
|
||||
}
|
||||
}
|
||||
116
crates/luxe-tui/src/view/changes/split.rs
Normal file
116
crates/luxe-tui/src/view/changes/split.rs
Normal file
@@ -0,0 +1,116 @@
|
||||
//! Changes split — the diff side by side: old on the left, new on the right.
|
||||
//!
|
||||
//! The same row space as the unified list, so toggling the layout keeps the reader where they were,
|
||||
//! and each column's code published on its own side so a selection stays in the file it began in.
|
||||
|
||||
use super::cells::{code_pieces, CodeCell};
|
||||
use super::diff::{hunk_header_line, DrawnRows};
|
||||
use crate::changes::ChangesView;
|
||||
use crate::guided_review::diff::SplitDiffCell;
|
||||
use crate::mouse::PeekSide;
|
||||
use crate::view::diff_lines::{SplitLayout, SplitSide};
|
||||
use luxe_core::guided_review::ReviewFile;
|
||||
use ratatui::text::Line;
|
||||
|
||||
/// The side-by-side view from `offset`, `viewport` rows of it.
|
||||
pub(super) fn split_lines(
|
||||
file: &ReviewFile,
|
||||
layout: &SplitLayout<'_>,
|
||||
view: &ChangesView,
|
||||
offset: usize,
|
||||
viewport: usize,
|
||||
) -> DrawnRows {
|
||||
use crate::guided_review::diff::{visible_split_rows, SplitRow};
|
||||
use crate::guided_review::VisibleGroup;
|
||||
|
||||
let groups: Vec<VisibleGroup<'_>> = file.hunks.iter().map(VisibleGroup::Hunk).collect();
|
||||
let rows = visible_split_rows(&groups, offset, viewport);
|
||||
let mut drawn: DrawnRows = (Vec::with_capacity(viewport), Vec::with_capacity(viewport));
|
||||
for row in &rows {
|
||||
if drawn.0.len() >= viewport {
|
||||
break;
|
||||
}
|
||||
match row {
|
||||
// A collapsed run cannot happen here: the pane folds nothing.
|
||||
SplitRow::Folded { .. } => {}
|
||||
SplitRow::Header { old_range, new_range, heading, .. } => {
|
||||
if !drawn.0.is_empty() {
|
||||
drawn.0.push(Line::default());
|
||||
drawn.1.push(Vec::new());
|
||||
}
|
||||
let header =
|
||||
hunk_header_line(*old_range, *new_range, *heading, layout.styles, None);
|
||||
drawn.0.push(header);
|
||||
drawn.1.push(Vec::new());
|
||||
}
|
||||
SplitRow::Pair { old, new, unified_index, last_index, .. } => {
|
||||
// A pair's first row is its old line and its last the new one; a context line, or
|
||||
// a line with nothing beside it, is one row and both
|
||||
let rows = (*unified_index, *last_index);
|
||||
let pair = SplitPair { old: *old, new: *new, rows, wrap: view.word_wrap };
|
||||
push_pair(&mut drawn, layout, &pair);
|
||||
}
|
||||
}
|
||||
}
|
||||
drawn.0.truncate(viewport);
|
||||
drawn.1.truncate(viewport);
|
||||
drawn
|
||||
}
|
||||
|
||||
/// One row of a side-by-side diff: the old line and the new one, either possibly missing.
|
||||
struct SplitPair<'a> {
|
||||
old: SplitDiffCell<'a>,
|
||||
new: SplitDiffCell<'a>,
|
||||
/// The old and the new line's rows in the pane's row space
|
||||
rows: (usize, usize),
|
||||
wrap: bool,
|
||||
}
|
||||
|
||||
/// Draws one side-by-side pair, wrapped or clipped, with where each side's code sits.
|
||||
fn push_pair(drawn: &mut DrawnRows, layout: &SplitLayout<'_>, pair: &SplitPair<'_>) {
|
||||
let plain = crate::view::diff_lines::SplitCellStyle::default();
|
||||
// Pairing is exact here, so the marks are too — no run-matching heuristic.
|
||||
let changed = match (pair.old, pair.new) {
|
||||
(SplitDiffCell::Source(old), SplitDiffCell::Source(new)) if old.kind != new.kind => {
|
||||
luxe_core::intraline::intraline_change(
|
||||
&crate::tabstop::display_text(&old.text),
|
||||
&crate::tabstop::display_text(&new.text),
|
||||
)
|
||||
}
|
||||
_ => luxe_core::intraline::IntralineChange::default(),
|
||||
};
|
||||
let old = side_pieces(pair.old, (SplitSide::Old, pair.rows.0), layout, pair.wrap);
|
||||
let new = side_pieces(pair.new, (SplitSide::New, pair.rows.1), layout, pair.wrap);
|
||||
let lines = match pair.wrap {
|
||||
true => layout
|
||||
.wrapped_pair((pair.old, &changed.removed, &plain), (pair.new, &changed.added, &plain)),
|
||||
false => {
|
||||
let mut spans = layout.cell_spans(SplitSide::Old, pair.old, &changed.removed, &plain);
|
||||
spans.push(layout.divider());
|
||||
spans.extend(layout.cell_spans(SplitSide::New, pair.new, &changed.added, &plain));
|
||||
vec![Line::from(spans)]
|
||||
}
|
||||
};
|
||||
for (index, line) in lines.into_iter().enumerate() {
|
||||
drawn.0.push(line);
|
||||
drawn.1.push(old.get(index).into_iter().chain(new.get(index)).copied().collect());
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the code of one side of a pair sits on each row it wraps to.
|
||||
fn side_pieces(
|
||||
cell: SplitDiffCell<'_>,
|
||||
(side, row): (SplitSide, usize),
|
||||
layout: &SplitLayout<'_>,
|
||||
wrap: bool,
|
||||
) -> Vec<CodeCell> {
|
||||
let SplitDiffCell::Source(line) = cell else { return Vec::new() };
|
||||
let (x, peek_side) = match side {
|
||||
SplitSide::Old => (layout.continuation(), PeekSide::Old),
|
||||
SplitSide::New => (
|
||||
layout.side + crate::view::diff_lines::SPLIT_DIVIDER_CELLS + layout.continuation(),
|
||||
PeekSide::New,
|
||||
),
|
||||
};
|
||||
code_pieces(&line.text, row, peek_side, (x, layout.source.max(1)), wrap)
|
||||
}
|
||||
444
crates/luxe-tui/src/view/changes/text.rs
Normal file
444
crates/luxe-tui/src/view/changes/text.rs
Normal file
@@ -0,0 +1,444 @@
|
||||
//! The File view — a project file as it is now, in the column the preview takes.
|
||||
//!
|
||||
//! Numbered, highlighted the way the transcript highlights code, with a bar in the gutter beside
|
||||
//! every line the file's change added when it has one. A drag over the code selects text, the way
|
||||
//! it does in the transcript; a drag down the line numbers picks whole lines, and an action row
|
||||
//! under the pick offers what a reader does next: ask the agent about them, or copy them.
|
||||
|
||||
use super::cells::{code_pieces, publish_and_paint, CodeCell};
|
||||
use super::{sentence, MouseTarget};
|
||||
use crate::app::App;
|
||||
use crate::changes::{ChangesView, TextLoad};
|
||||
use crate::mouse::PeekSelectionAction;
|
||||
use crate::view::diff_lines::highlighted_source_spans;
|
||||
use luxe_core::guided_review::ReviewLineKind;
|
||||
use luxe_core::project_files::ProjectFile;
|
||||
use ratatui::{
|
||||
layout::Rect,
|
||||
style::Style,
|
||||
text::{Line, Span},
|
||||
widgets::{Paragraph, Wrap},
|
||||
Frame,
|
||||
};
|
||||
use std::collections::HashSet;
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
/// Draws the File view's body, or the one line explaining why there is none.
|
||||
pub(super) fn render(frame: &mut Frame, area: Rect, app: &App, view: &ChangesView) {
|
||||
view.viewport_rows.set(usize::from(area.height).max(1));
|
||||
let Some(file) = loaded_text_or_notice(frame, area, app, view) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let (body, scrollbar) = match area.width > 2 {
|
||||
true => (
|
||||
Rect { width: area.width - 1, ..area },
|
||||
Some(Rect { x: area.right() - 1, width: 1, ..area }),
|
||||
),
|
||||
false => (area, None),
|
||||
};
|
||||
let lines: Vec<&str> = file.text.lines().collect();
|
||||
let numbers = lines.len().max(1).to_string().len();
|
||||
// number, a space, the change bar, a space
|
||||
let gutter = numbers + 3;
|
||||
let columns = TextColumns {
|
||||
numbers,
|
||||
gutter,
|
||||
code: usize::from(body.width).saturating_sub(gutter).max(4),
|
||||
width: body.width,
|
||||
viewport: usize::from(body.height),
|
||||
};
|
||||
let offset = text_window(view, &lines, &columns);
|
||||
let TextFrame { mut rows, hits, cells } = text_rows(app, view, file, &lines, offset, &columns);
|
||||
publish_and_paint(app, view, &mut rows, &cells, body);
|
||||
frame.render_widget(Paragraph::new(rows.clone()), body);
|
||||
publish_text_hits(app, &rows, hits, body, gutter);
|
||||
if let Some(scrollbar) = scrollbar {
|
||||
crate::widgets::steered_scrollbar(
|
||||
frame,
|
||||
&mut app.hit.borrow_mut(),
|
||||
scrollbar,
|
||||
crate::mouse::ScrollRegionId::Changes,
|
||||
offset,
|
||||
lines.len(),
|
||||
columns.viewport,
|
||||
&app.theme_styles,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The file's text when it is here and is text; otherwise draws the line saying why not.
|
||||
fn loaded_text_or_notice<'a>(
|
||||
frame: &mut Frame,
|
||||
area: Rect,
|
||||
app: &App,
|
||||
view: &'a ChangesView,
|
||||
) -> Option<&'a ProjectFile> {
|
||||
let styles = &app.theme_styles;
|
||||
let file = match &view.text {
|
||||
TextLoad::Ready(file) => file,
|
||||
other => {
|
||||
let (text, style) = match other {
|
||||
TextLoad::Failed(error) => (sentence(&error.to_string()), styles.warning),
|
||||
_ => ("Reading the file…".to_string(), styles.muted),
|
||||
};
|
||||
view.scroll_max.set(0);
|
||||
frame.render_widget(
|
||||
Paragraph::new(Line::from(Span::styled(text, style))).wrap(Wrap { trim: true }),
|
||||
area,
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if file.binary {
|
||||
view.scroll_max.set(0);
|
||||
frame.render_widget(
|
||||
Paragraph::new(Line::from(Span::styled(
|
||||
"This file is not text, so there are no lines to show. Open it in your editor.",
|
||||
styles.warning,
|
||||
)))
|
||||
.wrap(Wrap { trim: true }),
|
||||
area,
|
||||
);
|
||||
return None;
|
||||
}
|
||||
Some(file)
|
||||
}
|
||||
|
||||
/// How the body divides its width, and how many rows it shows.
|
||||
struct TextColumns {
|
||||
/// Digits the line numbers take
|
||||
numbers: usize,
|
||||
gutter: usize,
|
||||
code: usize,
|
||||
width: u16,
|
||||
viewport: usize,
|
||||
}
|
||||
|
||||
/// Publishes the largest offset that still puts the last line on screen, and returns this frame's
|
||||
/// offset clamped to it.
|
||||
fn text_window(view: &ChangesView, lines: &[&str], columns: &TextColumns) -> usize {
|
||||
let height = |index: usize| -> usize {
|
||||
match view.word_wrap {
|
||||
true => crate::tabstop::display_width(lines[index]).div_ceil(columns.code).max(1),
|
||||
false => 1,
|
||||
}
|
||||
};
|
||||
// The largest offset that still puts the last line on screen, measured from the end only
|
||||
let mut used = 0usize;
|
||||
let mut max = 0usize;
|
||||
for index in (0..lines.len()).rev() {
|
||||
used += height(index);
|
||||
if used > columns.viewport {
|
||||
max = index + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
view.scroll_max.set(max);
|
||||
view.scroll.min(max)
|
||||
}
|
||||
|
||||
/// The rows on screen, what a click on each means, and where each row's code sits.
|
||||
#[derive(Default)]
|
||||
struct TextFrame {
|
||||
rows: Vec<Line<'static>>,
|
||||
hits: Vec<(usize, MouseTarget)>,
|
||||
/// One entry per row: the code it shows, or nothing for the action row and the closing note
|
||||
cells: Vec<Vec<CodeCell>>,
|
||||
}
|
||||
|
||||
impl TextFrame {
|
||||
/// Adds a row that holds no code.
|
||||
fn push_plain(&mut self, row: Line<'static>) {
|
||||
self.rows.push(row);
|
||||
self.cells.push(Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows on screen from `offset`: numbered lines, the action row under a pick, and a note when
|
||||
/// the file goes on past what was read.
|
||||
fn text_rows(
|
||||
app: &App,
|
||||
view: &ChangesView,
|
||||
file: &ProjectFile,
|
||||
lines: &[&str],
|
||||
offset: usize,
|
||||
columns: &TextColumns,
|
||||
) -> TextFrame {
|
||||
let (gutter, viewport) = (columns.gutter, columns.viewport);
|
||||
let picked = view.selected_lines();
|
||||
let context = LineContext {
|
||||
language: view.path.rsplit_once('.').map(|(_, ext)| ext.to_ascii_lowercase()),
|
||||
added: added_lines(view),
|
||||
picked,
|
||||
};
|
||||
let mut frame = TextFrame::default();
|
||||
for (index, line) in lines.iter().enumerate().skip(offset) {
|
||||
if frame.rows.len() >= viewport {
|
||||
break;
|
||||
}
|
||||
push_line_rows(&mut frame, app, view, (index, line), &context, columns);
|
||||
let closes_pick = picked.is_some_and(|(_, last)| last as usize == index + 1);
|
||||
if closes_pick && !app.pointer.peek_dragging && frame.rows.len() < viewport {
|
||||
let (row, regions) = action_row(app, view, gutter);
|
||||
let at = frame.rows.len();
|
||||
frame.hits.extend(regions.into_iter().map(|(_, target)| (at, target)));
|
||||
frame.push_plain(row);
|
||||
}
|
||||
}
|
||||
if file.truncated && frame.rows.len() < viewport && offset + frame.rows.len() >= lines.len() {
|
||||
frame.push_plain(Line::from(Span::styled(
|
||||
format!(
|
||||
"{}… the file goes on past {} — open it in your editor for the rest",
|
||||
" ".repeat(gutter),
|
||||
human_bytes(file.text.len() as u64)
|
||||
),
|
||||
app.theme_styles.muted,
|
||||
)));
|
||||
}
|
||||
frame
|
||||
}
|
||||
|
||||
/// What every numbered line is drawn against.
|
||||
struct LineContext {
|
||||
language: Option<String>,
|
||||
added: HashSet<u32>,
|
||||
picked: Option<(u32, u32)>,
|
||||
}
|
||||
|
||||
/// One numbered line as the rows it wraps to, each with its gutter, its tint and its code.
|
||||
fn push_line_rows(
|
||||
frame: &mut TextFrame,
|
||||
app: &App,
|
||||
view: &ChangesView,
|
||||
(index, line): (usize, &str),
|
||||
context: &LineContext,
|
||||
columns: &TextColumns,
|
||||
) {
|
||||
let styles = &app.theme_styles;
|
||||
let number = u32::try_from(index + 1).unwrap_or(u32::MAX);
|
||||
let in_pick = context.picked.is_some_and(|(first, last)| (first..=last).contains(&number));
|
||||
// The keyboard's line, while the keyboard is here: its number lit and a mark beside it
|
||||
let standing = view.focused && view.cursor == Some(number);
|
||||
let lead = line_lead(app, (index, number), standing, in_pick, context, columns.numbers);
|
||||
let segments = source_row_segments(
|
||||
line,
|
||||
context.language.as_deref(),
|
||||
columns.code,
|
||||
view.word_wrap,
|
||||
styles,
|
||||
);
|
||||
let pieces = code_pieces(
|
||||
line,
|
||||
index,
|
||||
crate::mouse::PeekSide::Whole,
|
||||
(columns.gutter, columns.code),
|
||||
view.word_wrap,
|
||||
);
|
||||
for (segment_index, segment) in segments.into_iter().enumerate() {
|
||||
if frame.rows.len() >= columns.viewport {
|
||||
break;
|
||||
}
|
||||
let mut row = match segment_index {
|
||||
0 => lead.clone(),
|
||||
_ => vec![Span::styled(
|
||||
format!("{}{} ", " ".repeat(columns.gutter - 2), crate::glyphs::Mark::Continuation),
|
||||
styles.dim,
|
||||
)],
|
||||
};
|
||||
row.extend(segment);
|
||||
frame.hits.push((frame.rows.len(), MouseTarget::PeekLine(number)));
|
||||
frame.cells.push(pieces.get(segment_index).copied().into_iter().collect());
|
||||
frame.rows.push(match (in_pick, standing) {
|
||||
(true, _) => paint(row, true, columns.width, styles.pick_bg()),
|
||||
(false, true) => paint(row, true, columns.width, styles.cursor_line_bg()),
|
||||
(false, false) => paint(row, false, columns.width, styles.cursor_line_bg()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The line number, the keyboard's mark beside it, and the change bar.
|
||||
fn line_lead(
|
||||
app: &App,
|
||||
(index, number): (usize, u32),
|
||||
standing: bool,
|
||||
in_pick: bool,
|
||||
context: &LineContext,
|
||||
numbers: usize,
|
||||
) -> Vec<Span<'static>> {
|
||||
let styles = &app.theme_styles;
|
||||
let number_style = match (standing, in_pick) {
|
||||
(true, _) => styles.accent.add_modifier(ratatui::style::Modifier::BOLD),
|
||||
(false, true) => styles.text,
|
||||
(false, false) => styles.dim,
|
||||
};
|
||||
vec![
|
||||
Span::styled(
|
||||
format!("{:>numbers$}{}", index + 1, if standing { "›" } else { " " }),
|
||||
number_style,
|
||||
),
|
||||
Span::styled(if context.added.contains(&number) { "▎ " } else { " " }, styles.success),
|
||||
]
|
||||
}
|
||||
|
||||
/// One source line highlighted and either wrapped to the code column or clipped to it, marked
|
||||
/// where it runs past the edge.
|
||||
fn source_row_segments(
|
||||
line: &str,
|
||||
language: Option<&str>,
|
||||
code: usize,
|
||||
word_wrap: bool,
|
||||
styles: &crate::theme::styles::ThemeStyles,
|
||||
) -> Vec<Vec<Span<'static>>> {
|
||||
let source = crate::tabstop::display_text(line);
|
||||
let spans = highlighted_source_spans(&source, language, styles);
|
||||
match word_wrap {
|
||||
true => crate::widgets::wrap_cells(spans, code),
|
||||
false => {
|
||||
let clipped = crate::tabstop::display_width(line) > code;
|
||||
let mut kept = crate::view::diff_lines::clip_styled_spans(
|
||||
&spans.iter().map(|span| (span.content.as_ref(), span.style)).collect::<Vec<_>>(),
|
||||
0,
|
||||
if clipped { code - 1 } else { code },
|
||||
)
|
||||
.into_iter()
|
||||
.map(|span| Span::styled(span.content.into_owned(), span.style))
|
||||
.collect::<Vec<_>>();
|
||||
if clipped {
|
||||
kept.push(Span::styled("…", styles.dim));
|
||||
}
|
||||
vec![kept]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Publishes each row's click: the line it shows, or the action whose words it carries.
|
||||
///
|
||||
/// A line's click covers only its gutter: the code beside it is selectable text, and a press there
|
||||
/// has to start a selection rather than a line pick.
|
||||
fn publish_text_hits(
|
||||
app: &App,
|
||||
rows: &[Line<'static>],
|
||||
hits: Vec<(usize, MouseTarget)>,
|
||||
body: Rect,
|
||||
gutter: usize,
|
||||
) {
|
||||
let gutter = u16::try_from(gutter).unwrap_or(u16::MAX).min(body.width);
|
||||
let mut hit = app.hit.borrow_mut();
|
||||
for (row, target) in hits {
|
||||
let y = body.y + u16::try_from(row).unwrap_or(u16::MAX);
|
||||
if y >= body.bottom() {
|
||||
continue;
|
||||
}
|
||||
match &target {
|
||||
MouseTarget::PeekSelection(action) => {
|
||||
if let Some((x, width)) = action_columns(&rows[row], *action) {
|
||||
hit.push(Rect::new(body.x + x, y, width, 1), target);
|
||||
}
|
||||
}
|
||||
_ => hit.push(Rect::new(body.x, y, gutter, 1), target),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The new-file lines the change added, for the gutter bar.
|
||||
fn added_lines(view: &ChangesView) -> HashSet<u32> {
|
||||
view.file()
|
||||
.map(|file| {
|
||||
file.hunks
|
||||
.iter()
|
||||
.flat_map(|hunk| &hunk.lines)
|
||||
.filter(|line| line.kind == ReviewLineKind::Addition)
|
||||
.filter_map(|line| line.new_line)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A row, tinted across the pane's width while picked.
|
||||
fn paint(spans: Vec<Span<'static>>, picked: bool, width: u16, tint: Style) -> Line<'static> {
|
||||
match picked {
|
||||
true => Line::from(crate::view::diff_lines::tint_row(spans, tint, width)),
|
||||
false => Line::from(spans),
|
||||
}
|
||||
}
|
||||
|
||||
/// Labels of the action row, in order. Open in editor is not among them: the footer offers it
|
||||
/// already, and it cannot carry the pick with it.
|
||||
const ACTIONS: [(PeekSelectionAction, &str); 3] = [
|
||||
(PeekSelectionAction::Ask, "ask about these lines"),
|
||||
(PeekSelectionAction::Copy, "copy"),
|
||||
(PeekSelectionAction::Clear, "clear"),
|
||||
];
|
||||
|
||||
/// `Alt+L ask about lines 12–30 · copy · clear`, under the last picked line.
|
||||
fn action_row(
|
||||
app: &App,
|
||||
view: &ChangesView,
|
||||
gutter: usize,
|
||||
) -> (Line<'static>, Vec<(usize, MouseTarget)>) {
|
||||
let styles = &app.theme_styles;
|
||||
let chord = app
|
||||
.keymap
|
||||
.chords_for(luxe_core::keymap::UiAction::AskAboutSelection)
|
||||
.and_then(|chords| chords.first())
|
||||
.map(ToString::to_string);
|
||||
let mut spans = vec![Span::raw(" ".repeat(gutter))];
|
||||
let mut regions = Vec::new();
|
||||
for (index, (action, label)) in ACTIONS.iter().enumerate() {
|
||||
if index > 0 {
|
||||
spans.push(Span::styled(" · ", styles.border_muted));
|
||||
}
|
||||
let target = MouseTarget::PeekSelection(*action);
|
||||
let hovered = app.pointer.hover.as_ref() == Some(&target);
|
||||
if let (PeekSelectionAction::Ask, Some(chord)) = (action, chord.as_ref()) {
|
||||
spans.push(Span::styled(format!("{chord} "), styles.accent));
|
||||
}
|
||||
let label = match (action, view.selected_lines()) {
|
||||
(PeekSelectionAction::Ask, Some((first, last))) if first != last => {
|
||||
format!("ask about lines {first}–{last}")
|
||||
}
|
||||
(PeekSelectionAction::Ask, Some((line, _))) => format!("ask about line {line}"),
|
||||
_ => (*label).to_string(),
|
||||
};
|
||||
spans.push(Span::styled(label, if hovered { styles.text } else { styles.muted }));
|
||||
regions.push((0, target));
|
||||
}
|
||||
(Line::from(spans), regions)
|
||||
}
|
||||
|
||||
/// Where one action's words sit in its rendered row, for its click region.
|
||||
fn action_columns(row: &Line<'_>, action: PeekSelectionAction) -> Option<(u16, u16)> {
|
||||
let index = ACTIONS.iter().position(|(candidate, _)| *candidate == action)?;
|
||||
// Spans: indent, then per action an optional chord, its label, and a separator between
|
||||
let mut column = 0usize;
|
||||
let mut seen = 0usize;
|
||||
let mut spans = row.spans.iter().skip(1).peekable();
|
||||
while let Some(span) = spans.next() {
|
||||
let cells = span.content.width();
|
||||
if span.content == " · " {
|
||||
seen += 1;
|
||||
column += cells;
|
||||
continue;
|
||||
}
|
||||
if seen == index {
|
||||
let mut width = cells;
|
||||
// the chord and its label act together
|
||||
if let Some(next) = spans.peek().filter(|next| next.content != " · ") {
|
||||
width += next.content.width();
|
||||
}
|
||||
let start = row.spans[0].content.width() + column;
|
||||
return Some((u16::try_from(start).ok()?, u16::try_from(width).ok()?));
|
||||
}
|
||||
column += cells;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn human_bytes(bytes: u64) -> String {
|
||||
match bytes {
|
||||
bytes if bytes >= 1024 * 1024 => format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0)),
|
||||
bytes if bytes >= 1024 => format!("{} KB", bytes / 1024),
|
||||
bytes => format!("{bytes} bytes"),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user