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:
391
crates/luxe-tui/src/editor/layout.rs
Normal file
391
crates/luxe-tui/src/editor/layout.rs
Normal file
@@ -0,0 +1,391 @@
|
||||
//! Layout — soft-wrapping the draft into visual rows, and the cursor and selection on them.
|
||||
|
||||
use super::parts::PromptPart;
|
||||
use super::Editor;
|
||||
use unicode_width::UnicodeWidthChar;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct VisualSegment {
|
||||
pub(crate) text: String,
|
||||
pub(crate) is_chip: bool,
|
||||
/// Covered by the active selection (mouse drag or shift-select).
|
||||
pub(crate) is_selected: bool,
|
||||
/// Part of a slash command the composer lights, when it is
|
||||
pub(crate) mark: Option<crate::slash_args::Mark>,
|
||||
}
|
||||
|
||||
/// Cursor location in the wrapped editor viewport.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct VisualCursor {
|
||||
/// Zero-based visual row
|
||||
pub row: usize,
|
||||
/// Zero-based terminal-cell column
|
||||
pub column: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct CursorPoint {
|
||||
offset: usize,
|
||||
row: usize,
|
||||
column: usize,
|
||||
}
|
||||
|
||||
/// One wrap of the draft: its rows, the styled runs on each, and where every offset landed.
|
||||
///
|
||||
/// Handed out whole rather than re-derived per question, because the composer asks three — how
|
||||
/// tall am I, what do I draw, where is the caret — and each would otherwise walk the draft again.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct TextLayout {
|
||||
lines: Vec<String>,
|
||||
segments: Vec<Vec<VisualSegment>>,
|
||||
points: Vec<CursorPoint>,
|
||||
}
|
||||
|
||||
impl TextLayout {
|
||||
/// Visual rows the draft occupies. Never zero: an empty draft still has a row to type into.
|
||||
pub(crate) fn row_count(&self) -> usize {
|
||||
self.lines.len().max(1)
|
||||
}
|
||||
|
||||
/// The styled runs on each row, in order.
|
||||
pub(crate) fn rows(&self) -> &[Vec<VisualSegment>] {
|
||||
&self.segments
|
||||
}
|
||||
}
|
||||
|
||||
/// One laid-out character: where it came from, what it draws as, and the cells it consumes.
|
||||
struct LaidCell<'a> {
|
||||
offset: usize,
|
||||
len: usize,
|
||||
/// The cell's glyphs, borrowed from the draft. Owned only by a tab, which becomes spaces.
|
||||
text: std::borrow::Cow<'a, str>,
|
||||
/// Width the character wants; a tab's depends on the column it lands in.
|
||||
natural_width: usize,
|
||||
/// Width it actually consumed (clamped when whitespace hangs past the wrap column).
|
||||
width: usize,
|
||||
is_chip: bool,
|
||||
is_selected: bool,
|
||||
mark: Option<crate::slash_args::Mark>,
|
||||
is_tab: bool,
|
||||
/// Whitespace: a soft wrap may break right after it.
|
||||
breakable: bool,
|
||||
}
|
||||
|
||||
/// A visual row under construction: the source offset it starts at plus its characters.
|
||||
struct LaidRow<'a> {
|
||||
start: usize,
|
||||
cells: Vec<LaidCell<'a>>,
|
||||
}
|
||||
|
||||
/// Cells a laid row consumes, after tab expansion and wrap-column clamping.
|
||||
fn row_width(row: &LaidRow<'_>) -> usize {
|
||||
row.cells.iter().map(|cell| cell.width).sum()
|
||||
}
|
||||
|
||||
/// Soft-wrap `text` to `width`, breaking at word boundaries.
|
||||
///
|
||||
/// A word that would overflow moves to the next row whole; only a word longer than the whole row
|
||||
/// is split mid-character (nothing to wrap it to). Whitespace at a wrap column hangs off the end
|
||||
/// rather than being orphaned at the head of the next row — it draws blank and the composer's
|
||||
/// paragraph clips it.
|
||||
///
|
||||
/// A final row filled to its last cell gets an empty row after it. The caret has to live
|
||||
/// somewhere once a row is full, and clamping it onto the last glyph both hides the caret and
|
||||
/// defers the composer's growth until the *next* word actually moves down — which reads as the
|
||||
/// box expanding a keystroke late, with the first line scrolled out of view in the meantime.
|
||||
fn layout_text(
|
||||
text: &str,
|
||||
width: u16,
|
||||
parts: &[PromptPart],
|
||||
selection: Option<std::ops::Range<usize>>,
|
||||
marks: &[(std::ops::Range<usize>, crate::slash_args::Mark)],
|
||||
) -> TextLayout {
|
||||
let width = usize::from(width.max(1));
|
||||
let mut rows = vec![LaidRow { start: 0, cells: Vec::new() }];
|
||||
let mut column = 0usize;
|
||||
|
||||
for (offset, character) in text.char_indices() {
|
||||
if character == '\n' {
|
||||
rows.push(LaidRow { start: offset + 1, cells: Vec::new() });
|
||||
column = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
let natural_width =
|
||||
if character == '\t' { 4 - (column % 4) } else { character.width().unwrap_or(0) };
|
||||
let overflows = column > 0 && column + natural_width > width;
|
||||
if overflows && !character.is_whitespace() {
|
||||
// Carry the word this character belongs to onto the next row, unless the row is one
|
||||
// long word (nothing to break at) or already ends in whitespace.
|
||||
let current = rows.last_mut().expect("rows is never empty");
|
||||
let split =
|
||||
current.cells.iter().rposition(|cell| cell.breakable).map_or(0, |at| at + 1);
|
||||
let carried = if split == 0 || split == current.cells.len() {
|
||||
Vec::new()
|
||||
} else {
|
||||
current.cells.split_off(split)
|
||||
};
|
||||
let start = carried.first().map_or(offset, |cell| cell.offset);
|
||||
rows.push(LaidRow { start, cells: Vec::new() });
|
||||
column = 0;
|
||||
for cell in carried {
|
||||
push_cell(rows.last_mut().expect("row just pushed"), &mut column, cell, width);
|
||||
}
|
||||
}
|
||||
|
||||
let cell = LaidCell {
|
||||
offset,
|
||||
len: character.len_utf8(),
|
||||
text: std::borrow::Cow::Borrowed(&text[offset..offset + character.len_utf8()]),
|
||||
natural_width,
|
||||
width: natural_width,
|
||||
is_chip: parts.iter().any(|part| offset >= part.start && offset < part.end),
|
||||
is_selected: selection.as_ref().is_some_and(|range| range.contains(&offset)),
|
||||
mark: marks.iter().find(|(range, _)| range.contains(&offset)).map(|(_, mark)| *mark),
|
||||
is_tab: character == '\t',
|
||||
breakable: character.is_whitespace(),
|
||||
};
|
||||
push_cell(rows.last_mut().expect("rows is never empty"), &mut column, cell, width);
|
||||
}
|
||||
|
||||
if rows.last().is_some_and(|row| row_width(row) >= width) {
|
||||
rows.push(LaidRow { start: text.len(), cells: Vec::new() });
|
||||
}
|
||||
|
||||
let mut lines = Vec::with_capacity(rows.len());
|
||||
let mut segments = Vec::with_capacity(rows.len());
|
||||
let mut points: Vec<CursorPoint> = Vec::new();
|
||||
for (row, laid) in rows.iter().enumerate() {
|
||||
let mut line = String::new();
|
||||
let mut row_segments = Vec::new();
|
||||
push_point(&mut points, CursorPoint { offset: laid.start, row, column: 0 });
|
||||
let mut column = 0;
|
||||
for cell in &laid.cells {
|
||||
line.push_str(&cell.text);
|
||||
push_visual_segment(&mut row_segments, cell);
|
||||
column += cell.width;
|
||||
push_point(&mut points, CursorPoint { offset: cell.offset + cell.len, row, column });
|
||||
}
|
||||
lines.push(line);
|
||||
segments.push(row_segments);
|
||||
}
|
||||
|
||||
TextLayout { lines, segments, points }
|
||||
}
|
||||
|
||||
/// Append `cell` to a row, expanding a tab against its final column and clamping the row to
|
||||
/// `width` (only reached by whitespace hanging past the wrap column).
|
||||
fn push_cell<'a>(row: &mut LaidRow<'a>, column: &mut usize, mut cell: LaidCell<'a>, width: usize) {
|
||||
if cell.is_tab {
|
||||
cell.natural_width = 4 - (*column % 4);
|
||||
cell.text = std::borrow::Cow::Owned(" ".repeat(cell.natural_width));
|
||||
}
|
||||
cell.width = cell.natural_width.min(width.saturating_sub(*column));
|
||||
*column += cell.width;
|
||||
row.cells.push(cell);
|
||||
}
|
||||
|
||||
/// Record a cursor position, letting a later row claim a boundary offset from the row before it —
|
||||
/// so the caret sits at the head of the wrapped row rather than off the right edge of the one
|
||||
/// above.
|
||||
fn push_point(points: &mut Vec<CursorPoint>, point: CursorPoint) {
|
||||
match points.last_mut() {
|
||||
Some(last) if last.offset == point.offset => *last = point,
|
||||
_ => points.push(point),
|
||||
}
|
||||
}
|
||||
|
||||
fn push_visual_segment(segments: &mut Vec<VisualSegment>, cell: &LaidCell<'_>) {
|
||||
let LaidCell { is_chip, is_selected, mark, .. } = *cell;
|
||||
match segments.last_mut().filter(|segment| {
|
||||
segment.is_chip == is_chip && segment.is_selected == is_selected && segment.mark == mark
|
||||
}) {
|
||||
Some(segment) => segment.text.push_str(&cell.text),
|
||||
None => {
|
||||
segments.push(VisualSegment { text: cell.text.to_string(), is_chip, is_selected, mark })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn point_for_offset(points: &[CursorPoint], offset: usize) -> Option<CursorPoint> {
|
||||
points.iter().find(|point| point.offset == offset).copied()
|
||||
}
|
||||
|
||||
impl Editor {
|
||||
/// Updates the width used by vertical cursor navigation.
|
||||
pub fn set_viewport_width(&mut self, width: u16) {
|
||||
self.viewport_width = width.max(1);
|
||||
}
|
||||
|
||||
/// Soft-wrapped display lines at `width`. The composer reads its rows off a [`TextLayout`]
|
||||
/// instead; this is how the wrap's own invariants are checked.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn visual_lines(&self, width: u16) -> Vec<String> {
|
||||
self.layout(width).lines
|
||||
}
|
||||
|
||||
/// Moves the cursor to a visual cell and starts a selection there (mouse press).
|
||||
pub fn begin_selection_at_visual(&mut self, row: usize, column: usize) {
|
||||
self.place_cursor_at_visual(row, column);
|
||||
self.begin_selection();
|
||||
}
|
||||
|
||||
/// Selects the word at a visual cell (a double-click), or just places the cursor there when the
|
||||
/// cell holds no word.
|
||||
pub fn select_word_at_visual(&mut self, row: usize, column: usize) {
|
||||
self.place_cursor_at_visual(row, column);
|
||||
match crate::selection::word_bytes(&self.buffer, self.cursor) {
|
||||
Some(word) => {
|
||||
self.selection_anchor = Some(word.start);
|
||||
self.cursor = word.end;
|
||||
}
|
||||
None => self.begin_selection(),
|
||||
}
|
||||
self.preferred_column = None;
|
||||
}
|
||||
|
||||
/// Selects a whole visual (wrapped) row — a triple-click.
|
||||
///
|
||||
/// The *visual* row rather than the logical line, because the grid is what the reader can see,
|
||||
/// and it is the rule the transcript's own triple-click follows.
|
||||
pub fn select_visual_line(&mut self, row: usize) {
|
||||
let layout = self.layout(self.viewport_width);
|
||||
let Some(max_row) = layout.points.iter().map(|point| point.row).max() else {
|
||||
return;
|
||||
};
|
||||
let target = row.min(max_row);
|
||||
let mut offsets =
|
||||
layout.points.iter().filter(|point| point.row == target).map(|point| point.offset);
|
||||
let Some(first) = offsets.next() else {
|
||||
return;
|
||||
};
|
||||
self.selection_anchor = Some(first);
|
||||
self.cursor = offsets.next_back().unwrap_or(first);
|
||||
self.preferred_column = None;
|
||||
}
|
||||
|
||||
/// Extends the active selection to a visual cell (mouse drag), starting one if needed.
|
||||
pub fn extend_selection_to_visual(&mut self, row: usize, column: usize) {
|
||||
let anchor = self.selection_anchor.unwrap_or(self.cursor);
|
||||
self.place_cursor_at_visual(row, column);
|
||||
self.selection_anchor = Some(anchor);
|
||||
}
|
||||
|
||||
/// Places the cursor at a visual (wrapped) row/column, snapping to the nearest character on
|
||||
/// that row — the inverse of `visual_cursor`, used by a mouse click in the composer. A row past
|
||||
/// the end clamps to the last visual row; laid out at the current viewport width.
|
||||
pub fn place_cursor_at_visual(&mut self, row: usize, column: usize) {
|
||||
let layout = self.layout(self.viewport_width);
|
||||
let Some(max_row) = layout.points.iter().map(|point| point.row).max() else {
|
||||
return;
|
||||
};
|
||||
let target_row = row.min(max_row);
|
||||
if let Some(point) = layout
|
||||
.points
|
||||
.iter()
|
||||
.filter(|point| point.row == target_row)
|
||||
.min_by_key(|point| point.column.abs_diff(column))
|
||||
{
|
||||
self.cursor = self.snap_out_of_part(point.offset, point.column >= column);
|
||||
}
|
||||
self.preferred_column = None;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn visual_segments(&self, width: u16) -> Vec<Vec<VisualSegment>> {
|
||||
self.layout(width).segments
|
||||
}
|
||||
|
||||
/// Returns the cursor's visual row and terminal-cell column.
|
||||
pub fn visual_cursor(&self, width: u16) -> VisualCursor {
|
||||
self.cursor_in(&self.layout(width))
|
||||
}
|
||||
|
||||
/// The cursor's row and column within a wrap already computed for this frame.
|
||||
pub(crate) fn cursor_in(&self, layout: &TextLayout) -> VisualCursor {
|
||||
let point = point_for_offset(&layout.points, self.cursor).unwrap_or(CursorPoint {
|
||||
offset: 0,
|
||||
row: 0,
|
||||
column: 0,
|
||||
});
|
||||
VisualCursor { row: point.row, column: point.column }
|
||||
}
|
||||
|
||||
/// Visual rows the draft needs at `width`. Same note as [`Self::visual_lines`].
|
||||
#[cfg(test)]
|
||||
pub(crate) fn visual_line_count(&self, width: u16) -> usize {
|
||||
self.layout(width).row_count()
|
||||
}
|
||||
|
||||
/// Wraps the draft to `width`. One call answers everything the composer draws itself from.
|
||||
pub(crate) fn layout(&self, width: u16) -> TextLayout {
|
||||
layout_text(&self.buffer, width, &self.parts, self.selection(), &[])
|
||||
}
|
||||
|
||||
/// [`Self::layout`], with stretches of the draft marked for the composer to light: a slash
|
||||
/// command and the words of its that the draft spells out ([`crate::slash_args::marks`]).
|
||||
/// Marks change only how a run is drawn, never where the draft wraps.
|
||||
pub(crate) fn layout_marked(
|
||||
&self,
|
||||
width: u16,
|
||||
marks: &[(std::ops::Range<usize>, crate::slash_args::Mark)],
|
||||
) -> TextLayout {
|
||||
layout_text(&self.buffer, width, &self.parts, self.selection(), marks)
|
||||
}
|
||||
|
||||
/// Whether the cursor sits on the draft's first visual row, so `↑` has no line above to reach.
|
||||
pub(crate) fn cursor_on_first_row(&self) -> bool {
|
||||
let layout = self.layout(self.viewport_width);
|
||||
point_for_offset(&layout.points, self.cursor).is_none_or(|point| point.row == 0)
|
||||
}
|
||||
|
||||
/// Whether the cursor sits on the draft's last visual row, so `↓` has no line below to reach.
|
||||
pub(crate) fn cursor_on_last_row(&self) -> bool {
|
||||
let layout = self.layout(self.viewport_width);
|
||||
point_for_offset(&layout.points, self.cursor)
|
||||
.is_none_or(|point| point.row + 1 >= layout.lines.len())
|
||||
}
|
||||
|
||||
pub(super) fn move_up(&mut self) {
|
||||
let layout = self.layout(self.viewport_width);
|
||||
let Some(current) = point_for_offset(&layout.points, self.cursor) else {
|
||||
return;
|
||||
};
|
||||
if current.row > 0 {
|
||||
self.move_to_visual_row(&layout, current.row - 1, current.column);
|
||||
} else if self.cursor == 0 {
|
||||
self.history_previous();
|
||||
} else {
|
||||
self.cursor = 0;
|
||||
self.preferred_column = None;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn move_down(&mut self) {
|
||||
let layout = self.layout(self.viewport_width);
|
||||
let Some(current) = point_for_offset(&layout.points, self.cursor) else {
|
||||
return;
|
||||
};
|
||||
if current.row + 1 < layout.lines.len() {
|
||||
self.move_to_visual_row(&layout, current.row + 1, current.column);
|
||||
} else if self.cursor == self.buffer.len() {
|
||||
self.history_next();
|
||||
} else {
|
||||
self.cursor = self.buffer.len();
|
||||
self.preferred_column = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn move_to_visual_row(&mut self, layout: &TextLayout, row: usize, current_column: usize) {
|
||||
let target_column = self.preferred_column.unwrap_or(current_column);
|
||||
self.preferred_column = Some(target_column);
|
||||
if let Some(point) = layout
|
||||
.points
|
||||
.iter()
|
||||
.filter(|point| point.row == row)
|
||||
.min_by_key(|point| point.column.abs_diff(target_column))
|
||||
{
|
||||
self.cursor = self.snap_out_of_part(point.offset, point.column >= target_column);
|
||||
}
|
||||
}
|
||||
}
|
||||
190
crates/luxe-tui/src/editor/motion.rs
Normal file
190
crates/luxe-tui/src/editor/motion.rs
Normal file
@@ -0,0 +1,190 @@
|
||||
//! Motion — word and line jumps, and the deletions across them, in every encoding a terminal
|
||||
//! sends.
|
||||
|
||||
use super::Editor;
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
|
||||
/// A word or line jump, or a deletion across one, as every text field's keyboard expects.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) struct TextCommand {
|
||||
reach: Reach,
|
||||
delete: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Reach {
|
||||
WordBefore,
|
||||
WordAfter,
|
||||
LineStart,
|
||||
LineEnd,
|
||||
}
|
||||
|
||||
/// The jump or deletion a key asks for, in every encoding a terminal sends it in.
|
||||
///
|
||||
/// On macOS, ghostty (like Terminal.app and iTerm's "natural text editing") sends Option+←/→ as
|
||||
/// readline's `Esc b`/`Esc f`, and Cmd+←/→/⌫ as `Ctrl+A`/`Ctrl+E`/`Ctrl+U`; elsewhere the same keys
|
||||
/// arrive as modified arrows. Alt+D and Ctrl+K are taken by the dock and the palette, so the
|
||||
/// forward deletions are Ctrl/Alt+Delete only.
|
||||
pub(super) fn text_command(key: &KeyEvent) -> Option<TextCommand> {
|
||||
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
|
||||
let alt = key.modifiers.contains(KeyModifiers::ALT);
|
||||
let command = key.modifiers.contains(KeyModifiers::SUPER);
|
||||
let jump = |reach| Some(TextCommand { reach, delete: false });
|
||||
let delete = |reach| Some(TextCommand { reach, delete: true });
|
||||
match key.code {
|
||||
KeyCode::Left if command => jump(Reach::LineStart),
|
||||
KeyCode::Right if command => jump(Reach::LineEnd),
|
||||
KeyCode::Left if ctrl || alt => jump(Reach::WordBefore),
|
||||
KeyCode::Right if ctrl || alt => jump(Reach::WordAfter),
|
||||
KeyCode::Char('b') if alt && !ctrl => jump(Reach::WordBefore),
|
||||
KeyCode::Char('f') if alt && !ctrl => jump(Reach::WordAfter),
|
||||
KeyCode::Char('a') if ctrl && !alt => jump(Reach::LineStart),
|
||||
KeyCode::Char('e') if ctrl && !alt => jump(Reach::LineEnd),
|
||||
KeyCode::Backspace if command => delete(Reach::LineStart),
|
||||
KeyCode::Backspace if ctrl || alt => delete(Reach::WordBefore),
|
||||
KeyCode::Char('u') if ctrl && !alt => delete(Reach::LineStart),
|
||||
KeyCode::Delete if ctrl || alt => delete(Reach::WordAfter),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
enum CharClass {
|
||||
Word,
|
||||
Punctuation,
|
||||
Space,
|
||||
}
|
||||
|
||||
fn char_class(character: char) -> CharClass {
|
||||
if character.is_alphanumeric() || character == '_' {
|
||||
CharClass::Word
|
||||
} else if character.is_whitespace() {
|
||||
CharClass::Space
|
||||
} else {
|
||||
CharClass::Punctuation
|
||||
}
|
||||
}
|
||||
|
||||
impl Editor {
|
||||
pub(super) fn move_left(&mut self) {
|
||||
if let Some(part) = self.parts.iter().find(|part| part.end == self.cursor) {
|
||||
self.cursor = part.start;
|
||||
} else if let Some((start, _)) = self.buffer[..self.cursor].char_indices().next_back() {
|
||||
self.cursor = self.snap_out_of_part(start, false);
|
||||
}
|
||||
self.preferred_column = None;
|
||||
}
|
||||
|
||||
pub(super) fn move_right(&mut self) {
|
||||
if let Some(part) = self.parts.iter().find(|part| part.start == self.cursor) {
|
||||
self.cursor = part.end;
|
||||
} else if let Some(character) = self.buffer[self.cursor..].chars().next() {
|
||||
self.cursor = self.snap_out_of_part(self.cursor + character.len_utf8(), true);
|
||||
}
|
||||
self.preferred_column = None;
|
||||
}
|
||||
|
||||
pub(super) fn move_to_logical_line_start(&mut self) {
|
||||
self.cursor = self.line_start(self.cursor);
|
||||
self.preferred_column = None;
|
||||
}
|
||||
|
||||
pub(super) fn move_to_logical_line_end(&mut self) {
|
||||
self.cursor = self.line_end(self.cursor);
|
||||
self.preferred_column = None;
|
||||
}
|
||||
|
||||
fn line_start(&self, offset: usize) -> usize {
|
||||
let start = self.buffer[..offset].rfind('\n').map_or(0, |index| index + 1);
|
||||
self.snap_out_of_part(start, false)
|
||||
}
|
||||
|
||||
fn line_end(&self, offset: usize) -> usize {
|
||||
let end =
|
||||
self.buffer[offset..].find('\n').map_or(self.buffer.len(), |index| offset + index);
|
||||
self.snap_out_of_part(end, true)
|
||||
}
|
||||
|
||||
/// A word jump or deletion. Shift extends the selection with a jump; a deletion takes the
|
||||
/// selection instead when there is one.
|
||||
pub(super) fn run_text_command(&mut self, command: TextCommand, extending: bool) {
|
||||
let target = match command.reach {
|
||||
Reach::WordBefore => self.word_start_before(self.cursor),
|
||||
Reach::WordAfter => self.word_end_after(self.cursor),
|
||||
Reach::LineStart => self.line_start(self.cursor),
|
||||
Reach::LineEnd => self.line_end(self.cursor),
|
||||
};
|
||||
if command.delete {
|
||||
if self.delete_selection() {
|
||||
return;
|
||||
}
|
||||
self.selection_anchor = None;
|
||||
match command.reach {
|
||||
// Already at the start of a line: join it to the one above, as Backspace would
|
||||
Reach::LineStart if target == self.cursor => self.backspace(),
|
||||
_ => self.replace_range(target.min(self.cursor)..target.max(self.cursor), ""),
|
||||
}
|
||||
return;
|
||||
}
|
||||
if extending {
|
||||
self.selection_anchor.get_or_insert(self.cursor);
|
||||
} else {
|
||||
self.selection_anchor = None;
|
||||
}
|
||||
self.cursor = target;
|
||||
self.preferred_column = None;
|
||||
}
|
||||
|
||||
/// Where the word before `offset` starts: past any whitespace (line breaks included), then a
|
||||
/// run of word characters or a run of punctuation. A paste placeholder is one word.
|
||||
fn word_start_before(&self, offset: usize) -> usize {
|
||||
let part_ending = |at: usize| self.parts.iter().find(|part| part.end == at);
|
||||
let before = |at: usize| self.buffer[..at].chars().next_back();
|
||||
let mut at = offset;
|
||||
while let Some(character) = before(at) {
|
||||
if part_ending(at).is_some() || !character.is_whitespace() {
|
||||
break;
|
||||
}
|
||||
at -= character.len_utf8();
|
||||
}
|
||||
if let Some(part) = part_ending(at) {
|
||||
return part.start;
|
||||
}
|
||||
let Some(class) = before(at).map(char_class) else {
|
||||
return at;
|
||||
};
|
||||
while let Some(character) = before(at) {
|
||||
if part_ending(at).is_some() || char_class(character) != class {
|
||||
break;
|
||||
}
|
||||
at -= character.len_utf8();
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
/// Where the word after `offset` ends, the mirror of [`Self::word_start_before`].
|
||||
fn word_end_after(&self, offset: usize) -> usize {
|
||||
let part_starting = |at: usize| self.parts.iter().find(|part| part.start == at);
|
||||
let after = |at: usize| self.buffer[at..].chars().next();
|
||||
let mut at = offset;
|
||||
while let Some(character) = after(at) {
|
||||
if part_starting(at).is_some() || !character.is_whitespace() {
|
||||
break;
|
||||
}
|
||||
at += character.len_utf8();
|
||||
}
|
||||
if let Some(part) = part_starting(at) {
|
||||
return part.end;
|
||||
}
|
||||
let Some(class) = after(at).map(char_class) else {
|
||||
return at;
|
||||
};
|
||||
while let Some(character) = after(at) {
|
||||
if part_starting(at).is_some() || char_class(character) != class {
|
||||
break;
|
||||
}
|
||||
at += character.len_utf8();
|
||||
}
|
||||
at
|
||||
}
|
||||
}
|
||||
204
crates/luxe-tui/src/editor/parts.rs
Normal file
204
crates/luxe-tui/src/editor/parts.rs
Normal file
@@ -0,0 +1,204 @@
|
||||
//! Parts — the atomic tokens a draft holds: compacted pastes, images and `@` references.
|
||||
|
||||
use super::Editor;
|
||||
|
||||
/// An image attached to the editor input.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AttachedImage {
|
||||
/// Base64-encoded image data
|
||||
pub data: String,
|
||||
/// MIME type sent to the provider
|
||||
pub mime: String,
|
||||
/// Display filename synthesized for clipboard images
|
||||
pub filename: String,
|
||||
/// Original width in pixels
|
||||
pub width: u32,
|
||||
/// Original height in pixels
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) enum PromptPartKind {
|
||||
PastedText {
|
||||
text: String,
|
||||
},
|
||||
Image {
|
||||
image: AttachedImage,
|
||||
},
|
||||
/// A reference picked from the `@` picker: sent as written, held as one token
|
||||
Reference,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct PromptPart {
|
||||
pub(super) start: usize,
|
||||
pub(super) end: usize,
|
||||
pub(super) kind: PromptPartKind,
|
||||
}
|
||||
|
||||
const PASTE_SUMMARY_MIN_LINES: usize = 3;
|
||||
|
||||
const PASTE_SUMMARY_MIN_BYTES: usize = 150;
|
||||
|
||||
pub(super) fn shift_offset(offset: usize, inserted: usize, removed: usize) -> usize {
|
||||
if inserted >= removed {
|
||||
offset.saturating_add(inserted - removed)
|
||||
} else {
|
||||
offset.saturating_sub(removed - inserted)
|
||||
}
|
||||
}
|
||||
|
||||
impl Editor {
|
||||
/// Inserts terminal-pasted text, compacting large payloads into an atomic token.
|
||||
pub fn paste_text(&mut self, text: &str) {
|
||||
let normalized = text.replace("\r\n", "\n").replace('\r', "\n");
|
||||
let line_count = normalized.chars().filter(|character| *character == '\n').count() + 1;
|
||||
if line_count >= PASTE_SUMMARY_MIN_LINES || normalized.len() > PASTE_SUMMARY_MIN_BYTES {
|
||||
let marker = format!("[Pasted {line_count} lines]");
|
||||
self.insert_part(marker, PromptPartKind::PastedText { text: normalized });
|
||||
} else {
|
||||
self.insert_text(&normalized);
|
||||
}
|
||||
}
|
||||
|
||||
/// Attaches raw clipboard RGBA pixels as a PNG-backed atomic prompt token.
|
||||
///
|
||||
/// Returns `false` when image support is disabled or the pixel buffer is invalid.
|
||||
pub fn attach_image(&mut self, pixels: Vec<u8>, width: u32, height: u32) -> bool {
|
||||
let Some(encoded) = encode_clipboard_png(pixels, width, height) else {
|
||||
return false;
|
||||
};
|
||||
let image_number = self
|
||||
.parts
|
||||
.iter()
|
||||
.filter(|part| matches!(part.kind, PromptPartKind::Image { .. }))
|
||||
.count()
|
||||
+ 1;
|
||||
let filename = if image_number == 1 {
|
||||
"clipboard.png".to_string()
|
||||
} else {
|
||||
format!("clipboard-{image_number}.png")
|
||||
};
|
||||
let marker = "[Pasted Image]".to_string();
|
||||
self.insert_part(
|
||||
marker,
|
||||
PromptPartKind::Image {
|
||||
image: AttachedImage {
|
||||
data: encoded,
|
||||
mime: "image/png".to_string(),
|
||||
filename,
|
||||
width,
|
||||
height,
|
||||
},
|
||||
},
|
||||
);
|
||||
true
|
||||
}
|
||||
|
||||
/// Puts messages back at the head of the draft, each with the images it was sent with.
|
||||
///
|
||||
/// How a waiting submission is taken back for editing: it goes *before* whatever is being typed
|
||||
/// now, because it was typed first, and the cursor lands at the end of the restored text — the
|
||||
/// thing the user came back to change. Images are re-attached as the same atomic tokens a paste
|
||||
/// produces rather than re-encoded, so nothing is lost on the round trip.
|
||||
pub fn prepend_messages(
|
||||
&mut self,
|
||||
messages: impl IntoIterator<Item = (String, Vec<AttachedImage>)>,
|
||||
) {
|
||||
let occupied = !self.buffer.is_empty();
|
||||
self.cursor = 0;
|
||||
let mut restored = false;
|
||||
for (text, images) in messages {
|
||||
if restored {
|
||||
self.insert_text("\n\n");
|
||||
}
|
||||
restored = true;
|
||||
self.insert_text(&text);
|
||||
for image in images {
|
||||
self.insert_part("[Pasted Image]".to_string(), PromptPartKind::Image { image });
|
||||
}
|
||||
}
|
||||
if restored && occupied {
|
||||
let resume = self.cursor;
|
||||
self.insert_text("\n\n");
|
||||
self.cursor = resume;
|
||||
}
|
||||
self.history_index = None;
|
||||
self.selection_anchor = None;
|
||||
}
|
||||
|
||||
/// Inserts a reference — `@[file:src/main.rs]`, `@[github:owner/repo/pull/7]` — at the
|
||||
/// cursor as one token: drawn as a chip, stepped over by the cursor, deleted whole.
|
||||
pub fn insert_reference(&mut self, token: &str) {
|
||||
self.insert_part(token.to_string(), PromptPartKind::Reference);
|
||||
}
|
||||
|
||||
/// Removes the last image attachment and its display token.
|
||||
pub fn remove_last_image(&mut self) {
|
||||
if let Some(index) =
|
||||
self.parts.iter().rposition(|part| matches!(part.kind, PromptPartKind::Image { .. }))
|
||||
{
|
||||
let range = self.parts[index].start..self.parts[index].end;
|
||||
self.replace_range(range, "");
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports whether the draft contains image attachments.
|
||||
pub fn has_images(&self) -> bool {
|
||||
self.parts.iter().any(|part| matches!(part.kind, PromptPartKind::Image { .. }))
|
||||
}
|
||||
|
||||
fn insert_part(&mut self, marker: String, kind: PromptPartKind) {
|
||||
self.clamp_cursor();
|
||||
let start = self.cursor;
|
||||
self.replace_range(start..start, &marker);
|
||||
self.parts.push(PromptPart { start, end: start + marker.len(), kind });
|
||||
self.parts.sort_by_key(|part| part.start);
|
||||
}
|
||||
|
||||
/// The draft's text in `range`, with every part wholly inside it expanded: a paste to what was
|
||||
/// pasted, an image to nothing, and a reference left as written.
|
||||
pub(super) fn expand_parts(&self, range: std::ops::Range<usize>) -> String {
|
||||
let mut text = self.buffer[range.clone()].to_string();
|
||||
let mut parts = self
|
||||
.parts
|
||||
.iter()
|
||||
.filter(|part| part.start >= range.start && part.end <= range.end)
|
||||
.collect::<Vec<_>>();
|
||||
// From the back, so each part's offsets still hold when it is replaced
|
||||
parts.sort_by_key(|part| std::cmp::Reverse(part.start));
|
||||
for part in parts {
|
||||
let replacement = match &part.kind {
|
||||
PromptPartKind::PastedText { text } => text.as_str(),
|
||||
PromptPartKind::Image { .. } => "",
|
||||
PromptPartKind::Reference => continue,
|
||||
};
|
||||
text.replace_range(part.start - range.start..part.end - range.start, replacement);
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
pub(super) fn snap_out_of_part(&self, offset: usize, forward: bool) -> usize {
|
||||
self.parts
|
||||
.iter()
|
||||
.find(|part| offset > part.start && offset < part.end)
|
||||
.map_or(offset, |part| if forward { part.end } else { part.start })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "clipboard-images")]
|
||||
fn encode_clipboard_png(pixels: Vec<u8>, width: u32, height: u32) -> Option<String> {
|
||||
use base64::Engine;
|
||||
use image::{DynamicImage, ImageFormat, RgbaImage};
|
||||
use std::io::Cursor;
|
||||
|
||||
let image = RgbaImage::from_raw(width, height, pixels)?;
|
||||
let mut encoded = Cursor::new(Vec::new());
|
||||
DynamicImage::ImageRgba8(image).write_to(&mut encoded, ImageFormat::Png).ok()?;
|
||||
Some(base64::engine::general_purpose::STANDARD.encode(encoded.into_inner()))
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "clipboard-images"))]
|
||||
fn encode_clipboard_png(_pixels: Vec<u8>, _width: u32, _height: u32) -> Option<String> {
|
||||
None
|
||||
}
|
||||
607
crates/luxe-tui/src/editor/tests.rs
Normal file
607
crates/luxe-tui/src/editor/tests.rs
Normal file
@@ -0,0 +1,607 @@
|
||||
use super::*;
|
||||
|
||||
fn key(code: KeyCode) -> KeyEvent {
|
||||
KeyEvent::new(code, KeyModifiers::NONE)
|
||||
}
|
||||
|
||||
/// Whitespace is nothing to send, and stays where it was typed.
|
||||
#[test]
|
||||
fn a_blank_draft_submits_nothing() {
|
||||
let mut editor = Editor::new();
|
||||
editor.insert_text(" \n\t ");
|
||||
assert!(editor.submit().is_none());
|
||||
assert_eq!(editor.current_input(), " \n\t ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn submit_expands_large_paste_and_clears_the_draft() {
|
||||
let mut editor = Editor::new();
|
||||
editor.insert_text("before ");
|
||||
editor.paste_text("alpha\nbeta\ngamma");
|
||||
editor.insert_text(" after");
|
||||
|
||||
assert_eq!(editor.current_input(), "before [Pasted 3 lines] after");
|
||||
let (submitted, images) = editor.submit().unwrap();
|
||||
assert_eq!(submitted, "before alpha\nbeta\ngamma after");
|
||||
assert!(images.is_empty());
|
||||
assert!(editor.current_input().is_empty());
|
||||
}
|
||||
|
||||
/// A one-line field is the shape an API key arrives in, and the newline a console copy brings
|
||||
/// with it must not survive to be typed, echoed, or sent.
|
||||
#[test]
|
||||
fn a_one_line_field_takes_a_paste_without_its_line_breaks() {
|
||||
assert_eq!(single_line_paste("sk-ant-abc\n"), "sk-ant-abc");
|
||||
assert_eq!(single_line_paste(" sk-ant-abc "), "sk-ant-abc");
|
||||
assert_eq!(single_line_paste("sk-ant\r\n-abc"), "sk-ant-abc", "a wrapped key is one key");
|
||||
assert_eq!(single_line_paste("a\tb"), "ab", "a tab would move focus, not type");
|
||||
assert_eq!(single_line_paste("\n\n"), "", "and a paste of nothing types nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_paste_stays_editable_inline() {
|
||||
let mut editor = Editor::new();
|
||||
editor.paste_text("alpha\nbeta");
|
||||
assert_eq!(editor.current_input(), "alpha\nbeta");
|
||||
assert_eq!(editor.expanded_input(), "alpha\nbeta");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracked_ranges_expand_only_their_own_duplicate_marker() {
|
||||
let mut editor = Editor::new();
|
||||
editor.insert_text("literal [Pasted 3 lines] ");
|
||||
editor.paste_text("one\ntwo\nthree");
|
||||
assert_eq!(editor.expanded_input(), "literal [Pasted 3 lines] one\ntwo\nthree");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasted_ranges_stay_exact_after_wide_characters() {
|
||||
let mut editor = Editor::new();
|
||||
editor.insert_text("你好 ");
|
||||
editor.paste_text("one\ntwo\nthree");
|
||||
editor.insert_text(" 结束");
|
||||
|
||||
assert_eq!(editor.expanded_input(), "你好 one\ntwo\nthree 结束");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_tokens_are_atomic_for_movement_and_deletion() {
|
||||
let mut editor = Editor::new();
|
||||
editor.paste_text("one\ntwo\nthree");
|
||||
let end = editor.cursor;
|
||||
|
||||
editor.handle_key(key(KeyCode::Left));
|
||||
assert_eq!(editor.cursor, 0);
|
||||
editor.handle_key(key(KeyCode::Right));
|
||||
assert_eq!(editor.cursor, end);
|
||||
editor.handle_key(key(KeyCode::Backspace));
|
||||
assert!(editor.current_input().is_empty());
|
||||
assert!(editor.expanded_input().is_empty());
|
||||
}
|
||||
|
||||
/// A reference is one token like a paste: stepped over, deleted whole, drawn as a chip, and
|
||||
/// sent exactly as written — never expanded into anything else.
|
||||
#[test]
|
||||
fn a_reference_is_one_token_sent_as_written() {
|
||||
let mut editor = Editor::new();
|
||||
editor.insert_text("Review ");
|
||||
editor.insert_reference("@[file:docs/plan.md]");
|
||||
editor.insert_text(" today");
|
||||
let token_end = "Review @[file:docs/plan.md]".len();
|
||||
editor.cursor = token_end;
|
||||
editor.handle_key(key(KeyCode::Left));
|
||||
assert_eq!(editor.cursor, "Review ".len(), "stepped over");
|
||||
let layout = editor.layout(80);
|
||||
let chips: Vec<&str> = layout.rows()[0]
|
||||
.iter()
|
||||
.filter(|segment| segment.is_chip)
|
||||
.map(|segment| segment.text.as_str())
|
||||
.collect();
|
||||
assert_eq!(chips, ["@[file:docs/plan.md]"]);
|
||||
assert_eq!(editor.expanded_input(), "Review @[file:docs/plan.md] today");
|
||||
editor.select_all();
|
||||
assert_eq!(editor.selected_text().as_deref(), Some("Review @[file:docs/plan.md] today"));
|
||||
editor.clear_selection();
|
||||
editor.cursor = token_end;
|
||||
editor.handle_key(key(KeyCode::Backspace));
|
||||
assert_eq!(editor.current_input(), "Review today", "deleted whole");
|
||||
assert_eq!(
|
||||
editor.submit().map(|(text, images)| (text, images.len())),
|
||||
Some(("Review today".into(), 0))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrows_navigate_explicit_lines_before_history() {
|
||||
let mut editor = Editor::new();
|
||||
editor.insert_text("alpha\nbeta\ngamma");
|
||||
|
||||
editor.handle_key(key(KeyCode::Up));
|
||||
assert_eq!(editor.cursor, "alpha\nbeta".len());
|
||||
editor.handle_key(key(KeyCode::Up));
|
||||
assert_eq!(editor.cursor, "alpha".len());
|
||||
editor.handle_key(key(KeyCode::Down));
|
||||
assert_eq!(editor.cursor, "alpha\nbeta".len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrows_navigate_soft_wrapped_lines() {
|
||||
let mut editor = Editor::new();
|
||||
editor.set_viewport_width(5);
|
||||
editor.insert_text("abcdefgh");
|
||||
|
||||
editor.handle_key(key(KeyCode::Up));
|
||||
assert_eq!(editor.visual_cursor(5).row, 0);
|
||||
editor.handle_key(key(KeyCode::Down));
|
||||
assert_eq!(editor.visual_cursor(5).row, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_is_only_reached_from_prompt_boundaries() {
|
||||
let mut editor = Editor::new();
|
||||
editor.insert_text("previous");
|
||||
editor.submit();
|
||||
editor.insert_text("draft");
|
||||
|
||||
editor.cursor = 3;
|
||||
editor.handle_key(key(KeyCode::Up));
|
||||
assert_eq!(editor.cursor, 0);
|
||||
assert_eq!(editor.current_input(), "draft");
|
||||
editor.handle_key(key(KeyCode::Up));
|
||||
assert_eq!(editor.current_input(), "previous");
|
||||
editor.handle_key(key(KeyCode::Down));
|
||||
assert_eq!(editor.current_input(), "previous");
|
||||
editor.handle_key(key(KeyCode::Down));
|
||||
assert_eq!(editor.current_input(), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_edits_keep_cursor_on_byte_boundaries() {
|
||||
let mut editor = Editor::new();
|
||||
editor.insert_text("café");
|
||||
editor.handle_key(key(KeyCode::Left));
|
||||
assert_eq!(editor.cursor, 3);
|
||||
editor.handle_key(key(KeyCode::Delete));
|
||||
assert_eq!(editor.buffer, "caf");
|
||||
editor.insert_text("🪨");
|
||||
editor.handle_key(key(KeyCode::Backspace));
|
||||
assert_eq!(editor.buffer, "caf");
|
||||
assert_eq!(editor.cursor, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visual_layout_counts_wide_characters_and_wraps() {
|
||||
let mut editor = Editor::new();
|
||||
editor.insert_text("ab界cd");
|
||||
assert_eq!(editor.visual_lines(4), vec!["ab界", "cd"]);
|
||||
assert_eq!(editor.visual_cursor(4), VisualCursor { row: 1, column: 2 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_segments_preserve_unicode_wrap_boundaries() {
|
||||
let mut editor = Editor::new();
|
||||
editor.insert_text("界 ");
|
||||
editor.paste_text("one\ntwo\nthree");
|
||||
editor.insert_text(" tail");
|
||||
|
||||
assert_eq!(
|
||||
editor.visual_segments(10),
|
||||
vec![
|
||||
vec![
|
||||
VisualSegment {
|
||||
text: "界 ".to_string(),
|
||||
is_chip: false,
|
||||
is_selected: false,
|
||||
mark: None
|
||||
},
|
||||
// The space after the marker's "[Pasted" hangs past the wrap column.
|
||||
VisualSegment {
|
||||
text: "[Pasted ".to_string(),
|
||||
is_chip: true,
|
||||
is_selected: false,
|
||||
mark: None
|
||||
},
|
||||
],
|
||||
vec![
|
||||
VisualSegment {
|
||||
text: "3 lines]".to_string(),
|
||||
is_chip: true,
|
||||
is_selected: false,
|
||||
mark: None
|
||||
},
|
||||
VisualSegment {
|
||||
text: " ".to_string(),
|
||||
is_chip: false,
|
||||
is_selected: false,
|
||||
mark: None
|
||||
},
|
||||
],
|
||||
vec![VisualSegment {
|
||||
text: "tail".to_string(),
|
||||
is_chip: false,
|
||||
is_selected: false,
|
||||
mark: None
|
||||
}],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_covers_a_drag_and_is_replaced_by_typing() {
|
||||
let mut editor = Editor::new();
|
||||
editor.set_viewport_width(40);
|
||||
editor.insert_text("select this text");
|
||||
|
||||
// A drag from column 7 to 11 selects the middle word.
|
||||
editor.begin_selection_at_visual(0, 7);
|
||||
editor.extend_selection_to_visual(0, 11);
|
||||
assert_eq!(editor.selected_text().as_deref(), Some("this"));
|
||||
// The covered cells are marked for rendering.
|
||||
let segments = editor.visual_segments(40).remove(0);
|
||||
assert!(segments.iter().any(|segment| segment.is_selected && segment.text == "this"));
|
||||
|
||||
// Typing replaces it; Shift+arrows extend from the keyboard.
|
||||
editor.handle_key(key(KeyCode::Char('X')));
|
||||
assert_eq!(editor.current_input(), "select X text");
|
||||
assert!(editor.selection().is_none(), "the selection is consumed");
|
||||
|
||||
editor.cursor = 0;
|
||||
for _ in 0..6 {
|
||||
editor.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT));
|
||||
}
|
||||
assert_eq!(editor.selected_text().as_deref(), Some("select"));
|
||||
// Any un-shifted movement drops it.
|
||||
editor.handle_key(key(KeyCode::Right));
|
||||
assert!(editor.selection().is_none());
|
||||
|
||||
editor.select_all();
|
||||
assert_eq!(editor.selected_text().as_deref(), Some("select X text"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selected_paste_token_copies_its_expanded_text() {
|
||||
let mut editor = Editor::new();
|
||||
editor.paste_text("alpha\nbeta\ngamma");
|
||||
editor.select_all();
|
||||
assert_eq!(
|
||||
editor.selected_text().as_deref(),
|
||||
Some("alpha\nbeta\ngamma"),
|
||||
"the clipboard gets the pasted text, not the [Pasted N lines] marker"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrapping_breaks_at_word_boundaries() {
|
||||
let mut editor = Editor::new();
|
||||
editor.insert_text("the quick brown fox jumps");
|
||||
|
||||
// Words move to the next row whole instead of being cut at the column budget.
|
||||
assert_eq!(editor.visual_lines(10), vec!["the quick ", "brown fox ", "jumps"]);
|
||||
assert_eq!(editor.visual_lines(16), vec!["the quick brown ", "fox jumps"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_word_longer_than_the_row_still_hard_splits() {
|
||||
let mut editor = Editor::new();
|
||||
editor.insert_text("hi supercalifragilistic");
|
||||
|
||||
// Nothing to wrap to, so the overlong word is broken at the column budget.
|
||||
assert_eq!(editor.visual_lines(8), vec!["hi ", "supercal", "ifragili", "stic"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrapped_word_keeps_the_cursor_with_its_character() {
|
||||
let mut editor = Editor::new();
|
||||
editor.set_viewport_width(10);
|
||||
editor.insert_text("alpha bravo");
|
||||
|
||||
// "bravo" wraps whole, so the caret after it sits on the second row, not the first.
|
||||
assert_eq!(editor.visual_cursor(10), VisualCursor { row: 1, column: 5 });
|
||||
// The caret between the two words stays at the end of the first row's text.
|
||||
editor.cursor = "alpha".len();
|
||||
assert_eq!(editor.visual_cursor(10), VisualCursor { row: 0, column: 5 });
|
||||
// Moving down from inside the first word lands inside the wrapped word.
|
||||
editor.cursor = 2;
|
||||
editor.handle_key(key(KeyCode::Down));
|
||||
assert_eq!(editor.visual_cursor(10).row, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_row_opens_the_next_one_before_the_word_moves() {
|
||||
let mut editor = Editor::new();
|
||||
editor.insert_text("aaaa bbb");
|
||||
// The row is full, so the caret already belongs on a second row and the box grows now —
|
||||
// not one keystroke later, when the word finally moves down.
|
||||
assert_eq!(editor.visual_line_count(8), 2);
|
||||
assert_eq!(editor.visual_cursor(8), VisualCursor { row: 1, column: 0 });
|
||||
|
||||
// The word moving down reflows the text without changing the height again.
|
||||
editor.insert_text("b");
|
||||
assert_eq!(editor.visual_lines(8), vec!["aaaa ", "bbbb"]);
|
||||
assert_eq!(editor.visual_line_count(8), 2);
|
||||
}
|
||||
|
||||
/// The composer sizes itself from the layout's row count and scrolls to keep the caret in
|
||||
/// view, so a caret row outside that count is exactly the state where the first line
|
||||
/// disappears mid-word. Typing a paragraph one character at a time must never reach it.
|
||||
#[test]
|
||||
fn the_caret_row_always_fits_inside_the_reported_height() {
|
||||
for width in [8u16, 13, 20, 37] {
|
||||
let mut editor = Editor::new();
|
||||
editor.set_viewport_width(width);
|
||||
let mut previous_rows = 1usize;
|
||||
for character in
|
||||
"the quick brown fox jumps over the lazy dog while carrying supercalifragilistic \
|
||||
expialidocious luggage"
|
||||
.chars()
|
||||
{
|
||||
editor.insert_text(&character.to_string());
|
||||
let rows = editor.visual_line_count(width);
|
||||
let caret = editor.visual_cursor(width);
|
||||
assert!(
|
||||
caret.row < rows,
|
||||
"width {width}: caret on row {} with only {rows} rows after {character:?}",
|
||||
caret.row
|
||||
);
|
||||
assert!(
|
||||
caret.column < usize::from(width),
|
||||
"width {width}: caret at column {} past the wrap column after {character:?}",
|
||||
caret.column
|
||||
);
|
||||
// Height only ever climbs by one row at a time while typing forward, so the box
|
||||
// never jumps two lines at once.
|
||||
assert!(
|
||||
rows <= previous_rows + 1,
|
||||
"width {width}: height jumped {previous_rows} -> {rows}"
|
||||
);
|
||||
previous_rows = rows;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "clipboard-images")]
|
||||
#[test]
|
||||
fn image_attachment_uses_a_compact_token_and_valid_png() {
|
||||
use base64::Engine;
|
||||
|
||||
let mut editor = Editor::new();
|
||||
assert!(editor.attach_image(vec![255, 0, 0, 255], 1, 1));
|
||||
assert_eq!(editor.current_input(), "[Pasted Image]");
|
||||
assert_eq!(
|
||||
editor.visual_segments(80),
|
||||
vec![vec![VisualSegment {
|
||||
text: "[Pasted Image]".to_string(),
|
||||
is_chip: true,
|
||||
is_selected: false,
|
||||
mark: None
|
||||
}]]
|
||||
);
|
||||
assert!(editor.has_images());
|
||||
|
||||
let (text, images) = editor.submit().unwrap();
|
||||
assert!(text.is_empty());
|
||||
assert_eq!(images[0].filename, "clipboard.png");
|
||||
let bytes = base64::engine::general_purpose::STANDARD.decode(&images[0].data).unwrap();
|
||||
assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
|
||||
}
|
||||
|
||||
/// Enter is the caller's: the editor leaves the draft alone rather than clearing it.
|
||||
///
|
||||
/// The break this catches: a caller that forgot to intercept Enter lost the draft to history
|
||||
/// without anything being sent.
|
||||
#[test]
|
||||
fn enter_is_left_to_the_caller() {
|
||||
let mut editor = Editor::new();
|
||||
editor.insert_text("half a thought");
|
||||
editor.handle_key(key(KeyCode::Enter));
|
||||
assert_eq!(editor.current_input(), "half a thought");
|
||||
assert!(editor.history.is_empty(), "and nothing went to history");
|
||||
}
|
||||
|
||||
/// Up walks back one message at a time and stops at the oldest; Down walks forward to the draft,
|
||||
/// taking the caret to the end of a recalled message before leaving it.
|
||||
#[test]
|
||||
fn history_walks_both_ways_through_several_messages() {
|
||||
let mut editor = Editor::new();
|
||||
for message in ["one", "two", "three"] {
|
||||
editor.insert_text(message);
|
||||
editor.submit();
|
||||
}
|
||||
for _ in 0..4 {
|
||||
editor.handle_key(key(KeyCode::Up));
|
||||
}
|
||||
assert_eq!(editor.current_input(), "one", "the oldest is as far back as it goes");
|
||||
let mut seen = Vec::new();
|
||||
for _ in 0..4 {
|
||||
editor.handle_key(key(KeyCode::Down));
|
||||
seen.push(editor.current_input().to_string());
|
||||
}
|
||||
assert_eq!(seen, ["one", "two", "three", ""]);
|
||||
}
|
||||
|
||||
/// History keeps the newest 500 messages, so a long session's pastes do not pile up forever.
|
||||
#[test]
|
||||
fn history_keeps_the_newest_five_hundred() {
|
||||
let mut editor = Editor::new();
|
||||
for message in 0..=500 {
|
||||
editor.insert_text(&format!("message {message}"));
|
||||
editor.submit();
|
||||
}
|
||||
assert_eq!(editor.history.len(), 500);
|
||||
assert_eq!(editor.history.first().map(String::as_str), Some("message 1"));
|
||||
editor.handle_key(key(KeyCode::Up));
|
||||
assert_eq!(editor.current_input(), "message 500", "the newest is still one step back");
|
||||
}
|
||||
|
||||
mod text_navigation {
|
||||
use super::*;
|
||||
|
||||
fn with(code: KeyCode, modifiers: KeyModifiers) -> KeyEvent {
|
||||
KeyEvent::new(code, modifiers)
|
||||
}
|
||||
|
||||
fn editor(text: &str, cursor: usize) -> Editor {
|
||||
Editor::with_text(text, cursor)
|
||||
}
|
||||
|
||||
/// Every stop a word jump makes, both ways, across punctuation, runs of spaces and a line
|
||||
/// break: the start of each word going left, the end of each going right.
|
||||
#[test]
|
||||
fn word_jumps_stop_at_each_word_both_ways() {
|
||||
let text = "fix the loop.unwrap()\n next_line héllo";
|
||||
let mut left = editor(text, text.len());
|
||||
let mut stops = Vec::new();
|
||||
while left.cursor > 0 {
|
||||
left.handle_key(with(KeyCode::Left, KeyModifiers::CONTROL));
|
||||
stops.push(&text[left.cursor..]);
|
||||
}
|
||||
assert_eq!(
|
||||
stops,
|
||||
[
|
||||
"héllo",
|
||||
"next_line héllo",
|
||||
"()\n next_line héllo",
|
||||
"unwrap()\n next_line héllo",
|
||||
".unwrap()\n next_line héllo",
|
||||
"loop.unwrap()\n next_line héllo",
|
||||
"the loop.unwrap()\n next_line héllo",
|
||||
text,
|
||||
]
|
||||
);
|
||||
|
||||
let mut right = editor(text, 0);
|
||||
let mut ends = Vec::new();
|
||||
while right.cursor < text.len() {
|
||||
right.handle_key(with(KeyCode::Right, KeyModifiers::CONTROL));
|
||||
ends.push(&text[..right.cursor]);
|
||||
}
|
||||
assert_eq!(ends.len(), 8, "{ends:?}");
|
||||
assert_eq!(ends[0], "fix");
|
||||
assert_eq!(ends[3], "fix the loop.");
|
||||
assert_eq!(ends[6], "fix the loop.unwrap()\n next_line");
|
||||
assert_eq!(ends[7], text);
|
||||
}
|
||||
|
||||
/// The same jump arrives as Ctrl+arrow, Alt+arrow, or — from ghostty and Terminal.app on
|
||||
/// macOS — readline's Alt+B and Alt+F; Cmd+arrows and Ctrl+A/E go to the line's ends.
|
||||
#[test]
|
||||
fn every_encoding_of_a_jump_lands_the_same() {
|
||||
let text = "one two\nthree four";
|
||||
let middle = "one two\nthree fo".len();
|
||||
for (key, expected) in [
|
||||
(with(KeyCode::Left, KeyModifiers::CONTROL), "one two\nthree ".len()),
|
||||
(with(KeyCode::Left, KeyModifiers::ALT), "one two\nthree ".len()),
|
||||
(with(KeyCode::Char('b'), KeyModifiers::ALT), "one two\nthree ".len()),
|
||||
(with(KeyCode::Right, KeyModifiers::CONTROL), text.len()),
|
||||
(with(KeyCode::Right, KeyModifiers::ALT), text.len()),
|
||||
(with(KeyCode::Char('f'), KeyModifiers::ALT), text.len()),
|
||||
(with(KeyCode::Left, KeyModifiers::SUPER), "one two\n".len()),
|
||||
(with(KeyCode::Char('a'), KeyModifiers::CONTROL), "one two\n".len()),
|
||||
(with(KeyCode::Right, KeyModifiers::SUPER), text.len()),
|
||||
(with(KeyCode::Char('e'), KeyModifiers::CONTROL), text.len()),
|
||||
] {
|
||||
let mut field = editor(text, middle);
|
||||
field.handle_key(key);
|
||||
assert_eq!(field.cursor, expected, "{key:?}");
|
||||
assert_eq!(field.current_input(), text, "{key:?} moves, never edits");
|
||||
}
|
||||
// Home and End, unmodified, do the same as Ctrl+A and Ctrl+E
|
||||
let mut field = editor(text, middle);
|
||||
field.handle_key(with(KeyCode::Home, KeyModifiers::NONE));
|
||||
assert_eq!(field.cursor, "one two\n".len());
|
||||
field.handle_key(with(KeyCode::End, KeyModifiers::NONE));
|
||||
assert_eq!(field.cursor, text.len());
|
||||
// Ctrl+E on the first line stops at its end, not the draft's
|
||||
let mut field = editor(text, 1);
|
||||
field.handle_key(with(KeyCode::Char('e'), KeyModifiers::CONTROL));
|
||||
assert_eq!(field.cursor, "one two".len());
|
||||
}
|
||||
|
||||
/// Word and line deletions in every encoding, including at the edges: at a line's start the
|
||||
/// line deletion joins it to the one above, and the forward deletion reaches the word's end.
|
||||
#[test]
|
||||
fn deletions_take_a_word_or_the_line_before_the_cursor() {
|
||||
let text = "one two\nthree four";
|
||||
let end = text.len();
|
||||
for (key, cursor, left) in [
|
||||
(with(KeyCode::Backspace, KeyModifiers::ALT), end, "one two\nthree "),
|
||||
(with(KeyCode::Backspace, KeyModifiers::CONTROL), end, "one two\nthree "),
|
||||
(with(KeyCode::Char('u'), KeyModifiers::CONTROL), end, "one two\n"),
|
||||
(with(KeyCode::Backspace, KeyModifiers::SUPER), end, "one two\n"),
|
||||
(
|
||||
with(KeyCode::Char('u'), KeyModifiers::CONTROL),
|
||||
"one two\n".len(),
|
||||
"one twothree four",
|
||||
),
|
||||
(with(KeyCode::Delete, KeyModifiers::CONTROL), 3, "one\nthree four"),
|
||||
(with(KeyCode::Delete, KeyModifiers::ALT), 0, " two\nthree four"),
|
||||
(with(KeyCode::Backspace, KeyModifiers::ALT), 0, text),
|
||||
(with(KeyCode::Delete, KeyModifiers::CONTROL), end, text),
|
||||
] {
|
||||
let mut field = editor(text, cursor);
|
||||
field.handle_key(key);
|
||||
assert_eq!(field.current_input(), left, "{key:?} at {cursor}");
|
||||
}
|
||||
// Ctrl+W is not a deletion here: Option+Backspace and Ctrl+Backspace are the word keys
|
||||
let mut field = editor(text, end);
|
||||
field.handle_key(with(KeyCode::Char('w'), KeyModifiers::CONTROL));
|
||||
assert_eq!(field.current_input(), text);
|
||||
let mut field = editor("", 0);
|
||||
field.handle_key(with(KeyCode::Char('u'), KeyModifiers::CONTROL));
|
||||
assert_eq!(field.current_input(), "", "nothing before an empty draft");
|
||||
// Unmodified, Backspace and Delete still take one character
|
||||
let mut field = editor(text, "one".len());
|
||||
field.handle_key(with(KeyCode::Backspace, KeyModifiers::NONE));
|
||||
field.handle_key(with(KeyCode::Delete, KeyModifiers::NONE));
|
||||
assert_eq!(field.current_input(), "ontwo\nthree four");
|
||||
}
|
||||
|
||||
/// Shift extends a selection by words; a deletion takes the selection when there is one; a
|
||||
/// plain jump drops it.
|
||||
#[test]
|
||||
fn shift_selects_by_word_and_deletions_take_a_selection() {
|
||||
let text = "alpha beta gamma";
|
||||
let mut field = editor(text, text.len());
|
||||
let back = with(KeyCode::Left, KeyModifiers::CONTROL | KeyModifiers::SHIFT);
|
||||
field.handle_key(back);
|
||||
field.handle_key(back);
|
||||
assert_eq!(field.selected_text().as_deref(), Some("beta gamma"));
|
||||
field.handle_key(with(KeyCode::Backspace, KeyModifiers::ALT));
|
||||
assert_eq!(field.current_input(), "alpha ", "the selection, not one more word");
|
||||
|
||||
let mut field = editor(text, text.len());
|
||||
field.handle_key(back);
|
||||
field.handle_key(with(KeyCode::Left, KeyModifiers::ALT));
|
||||
assert_eq!(field.selection(), None);
|
||||
assert_eq!(field.cursor, "alpha ".len());
|
||||
}
|
||||
|
||||
/// A paste placeholder is one word to a jump or a deletion, and deleting it drops the text it
|
||||
/// stood for.
|
||||
#[test]
|
||||
fn a_paste_placeholder_is_one_word() {
|
||||
let mut field = Editor::new();
|
||||
field.insert_text("see ");
|
||||
field.paste_text("one\ntwo\nthree\nfour");
|
||||
let placeholder_end = field.cursor;
|
||||
field.insert_text(" ok");
|
||||
let end = field.cursor;
|
||||
|
||||
field.handle_key(with(KeyCode::Left, KeyModifiers::CONTROL));
|
||||
assert_eq!(field.cursor, placeholder_end + 1, "the word after it");
|
||||
field.handle_key(with(KeyCode::Left, KeyModifiers::CONTROL));
|
||||
assert_eq!(field.cursor, "see ".len(), "the placeholder, whole");
|
||||
field.handle_key(with(KeyCode::Right, KeyModifiers::CONTROL));
|
||||
assert_eq!(field.cursor, placeholder_end);
|
||||
field.cursor = end;
|
||||
field.handle_key(with(KeyCode::Backspace, KeyModifiers::ALT));
|
||||
field.handle_key(with(KeyCode::Backspace, KeyModifiers::ALT));
|
||||
assert_eq!(field.current_input(), "see ");
|
||||
assert_eq!(field.expanded_input(), "see ", "the pasted text went with it");
|
||||
|
||||
field.paste_text("one\ntwo\nthree\nfour");
|
||||
field.cursor = "see ".len();
|
||||
field.handle_key(with(KeyCode::Delete, KeyModifiers::CONTROL));
|
||||
assert_eq!(field.expanded_input(), "see ");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user