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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ ratatui = "0.30"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
uuid = { version = "1", features = ["v4"] }
unicode-segmentation = "1"
unicode-width = "0.2"

[target.'cfg(unix)'.dependencies]
rustix = { version = "1", features = ["process"] }
Expand Down
229 changes: 206 additions & 23 deletions rust/src/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ use std::time::Duration;

use chrono::{SecondsFormat, Utc};
use ratatui::Frame;
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::crossterm::event::{
self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent,
MouseEventKind,
};
use ratatui::crossterm::execute;
use ratatui::crossterm::style::Print;
use ratatui::layout::{Position, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::Line;
Expand All @@ -14,15 +19,15 @@ use serde_json::Value;
use uuid::Uuid;

use crate::format::{sanitize_terminal_text, wrap_text};
use crate::layout::layout_comment;
use crate::layout::{cursor_at_visual_position, editor_viewport_start, layout_comment};
use crate::paths::state_dir;
use crate::store::{append_annotation, append_annotation_context_first};
use crate::termination::Termination;
use crate::types::{
Annotation, PendingAnnotation, javascript_trim, parse_pending_annotation,
pending_annotation_from_invocation,
};
use crate::width::{char_width, string_width, truncate_to_width};
use crate::width::{graphemes, string_width, truncate_to_width};

#[cfg(test)]
const DEFAULT_COLS: u16 = 86;
Expand All @@ -36,6 +41,7 @@ pub struct EditorApp {
saved_field_order: SavedFieldOrder,
comment: Vec<char>,
cursor: usize,
editor_start: usize,
status: String,
quit: bool,
}
Expand All @@ -58,13 +64,14 @@ impl EditorApp {
saved_field_order,
comment: Vec::new(),
cursor: 0,
editor_start: 0,
status: String::new(),
quit: false,
}
}

/// Draw the same selected-text, comment, and footer regions as the TypeScript editor.
pub fn draw(&self, frame: &mut Frame<'_>) {
pub fn draw(&mut self, frame: &mut Frame<'_>) {
let area = frame.area();
frame.render_widget(Clear, area);
let cols = usize::from(area.width.max(20));
Expand All @@ -79,9 +86,13 @@ impl EditorApp {
);
let selected = wrapped_selection.iter().take(selection_rows);
let editing = layout_comment(&self.comment, self.cursor, inner_width);
let editor_start = editing
.cursor_row
.saturating_sub(editor_rows.saturating_sub(1));
self.editor_start = editor_viewport_start(
self.editor_start,
editing.cursor_row,
editing.lines.len(),
editor_rows,
);
let editor_start = self.editor_start;

render_line(
frame,
Expand Down Expand Up @@ -207,6 +218,7 @@ impl EditorApp {
}
}
KeyCode::Enter => self.insert('\n'),
KeyCode::Tab => self.insert(' '),
KeyCode::Char(character)
if !key
.modifiers
Expand All @@ -219,6 +231,38 @@ impl EditorApp {
false
}

pub fn handle_mouse(&mut self, mouse: MouseEvent, width: u16, height: u16) {
let MouseEventKind::Down(MouseButton::Left) = mouse.kind else {
return;
};
let cols = usize::from(width.max(20));
let rows = usize::from(height.max(10));
let left = 2usize;
let inner_width = cols.saturating_sub(4).max(1);
let selection_rows = ((rows.saturating_sub(6)) / 2).clamp(3, 7);
let editor_rows = rows.saturating_sub(selection_rows + 5).max(1);
let editor_top = 3 + selection_rows;
let x = usize::from(mouse.column);
let y = usize::from(mouse.row);
if x < left || x > left + inner_width || y < editor_top || y >= editor_top + editor_rows {
return;
}
let editing = layout_comment(&self.comment, self.cursor, inner_width);
self.editor_start = editor_viewport_start(
self.editor_start,
editing.cursor_row,
editing.lines.len(),
editor_rows,
);
self.cursor = cursor_at_visual_position(
&self.comment,
self.editor_start + y - editor_top,
x - left,
inner_width,
);
self.status.clear();
}

fn insert(&mut self, character: char) {
self.comment.insert(self.cursor, character);
self.cursor += 1;
Expand All @@ -239,13 +283,13 @@ impl EditorApp {
.map(|line| line.chars().count() + 1)
.sum::<usize>();
let mut used = 0;
for character in lines.get(target_row).copied().unwrap_or_default().chars() {
let width = char_width(character);
for grapheme in graphemes(lines.get(target_row).copied().unwrap_or_default()) {
let width = string_width(grapheme);
if used + width > col {
break;
}
used += width;
next += 1;
next += grapheme.chars().count();
}
self.cursor = next;
}
Expand Down Expand Up @@ -350,6 +394,8 @@ pub fn run() -> Result<(), String> {
let termination = Termination::install();
let mut terminal = ratatui::init();
let result = (|| -> Result<(), String> {
execute!(std::io::stdout(), Print("\x1b[?1000h\x1b[?1006h"))
.map_err(|error| error.to_string())?;
while !app.quit && !termination.requested() {
terminal
.draw(|frame| app.draw(frame))
Expand All @@ -361,22 +407,30 @@ pub fn run() -> Result<(), String> {
if termination.requested() {
break;
}
let event = event::read().map_err(|error| error.to_string())?;
if let Event::Key(key) = event
&& app.handle_key(key)
&& app.save(dir.as_deref())
{
terminal
.draw(|frame| app.draw(frame))
.map_err(|error| error.to_string())?;
std::thread::sleep(Duration::from_millis(250));
app.quit = true;
let Ok(event) = event::read() else {
continue;
};
match event {
Event::Key(key) if app.handle_key(key) && app.save(dir.as_deref()) => {
terminal
.draw(|frame| app.draw(frame))
.map_err(|error| error.to_string())?;
std::thread::sleep(Duration::from_millis(250));
app.quit = true;
}
Event::Mouse(mouse) => {
let size = terminal.size().map_err(|error| error.to_string())?;
app.handle_mouse(mouse, size.width, size.height);
}
_ => {}
}
}
Ok(())
})();
let mouse_cleanup = execute!(std::io::stdout(), Print("\x1b[?1000l\x1b[?1006l"))
.map_err(|error| error.to_string());
ratatui::restore();
result
result.and(mouse_cleanup)
}

#[cfg(test)]
Expand All @@ -402,7 +456,16 @@ mod tests {
})
}

fn draw(app: &EditorApp) -> Vec<String> {
fn mouse(kind: MouseEventKind, column: u16, row: u16) -> MouseEvent {
MouseEvent {
kind,
column,
row,
modifiers: KeyModifiers::NONE,
}
}

fn draw(app: &mut EditorApp) -> Vec<String> {
let mut terminal =
Terminal::new(TestBackend::new(DEFAULT_COLS, DEFAULT_ROWS)).expect("terminal");
terminal.draw(|frame| app.draw(frame)).expect("draw");
Expand All @@ -419,7 +482,7 @@ mod tests {

#[test]
fn headless_frame_contains_selection_editor_and_keys() {
let rows = draw(&app());
let rows = draw(&mut app());
assert!(rows.iter().any(|row| row.contains("Selected text")));
assert!(rows.iter().any(|row| row.contains("first selected line")));
assert!(rows.iter().any(|row| row.contains("Comment")));
Expand All @@ -440,6 +503,13 @@ mod tests {
assert_eq!(empty.status, "Write a comment before saving.");
}

#[test]
fn tab_inserts_a_renderable_space() {
let mut editor = app();
editor.handle_key(KeyEvent::from(KeyCode::Tab));
assert_eq!(editor.comment, [' ']);
}

#[test]
fn escape_and_control_c_quit() {
let mut escape = app();
Expand Down Expand Up @@ -487,4 +557,117 @@ mod tests {
let _ = std::fs::remove_file(&missing);
assert_eq!(remove_pending_file(&missing), Ok(()));
}

#[test]
fn mouse_clicks_map_narrow_and_wide_glyph_cells() {
let mut editor = app();
editor.comment = "a한b".chars().collect();
editor.cursor = editor.comment.len();
editor.handle_mouse(
mouse(MouseEventKind::Down(MouseButton::Left), 2, 10),
86,
22,
);
assert_eq!(editor.cursor, 0);
editor.handle_mouse(
mouse(MouseEventKind::Down(MouseButton::Left), 3, 10),
86,
22,
);
assert_eq!(editor.cursor, 1);
editor.handle_mouse(
mouse(MouseEventKind::Down(MouseButton::Left), 4, 10),
86,
22,
);
assert_eq!(editor.cursor, 2);
editor.handle_mouse(
mouse(MouseEventKind::Down(MouseButton::Left), 6, 10),
86,
22,
);
assert_eq!(editor.cursor, 3);
}

#[test]
fn mouse_clicks_map_wraps_and_preserve_the_pre_click_scroll_offset() {
let mut wrapped = app();
wrapped.comment = format!("{}한", "a".repeat(15)).chars().collect();
wrapped.cursor = wrapped.comment.len();
wrapped.handle_mouse(
mouse(MouseEventKind::Down(MouseButton::Left), 17, 6),
20,
10,
);
assert_eq!(wrapped.cursor, 15);
wrapped.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), 2, 7), 20, 10);
assert_eq!(wrapped.cursor, 15);

let mut scrolled = app();
scrolled.comment = (0..11)
.map(|line| line.to_string())
.collect::<Vec<_>>()
.join("\n")
.chars()
.collect();
scrolled.cursor = scrolled.comment.len();
scrolled.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), 2, 6), 20, 10);
assert_eq!(scrolled.cursor, 18);
assert_eq!(scrolled.editor_start, 9);
}

#[test]
fn mouse_clicks_map_explicit_newlines_and_buffer_end() {
let mut editor = app();
editor.comment = "a\n\nb".chars().collect();
editor.cursor = editor.comment.len();
editor.handle_mouse(
mouse(MouseEventKind::Down(MouseButton::Left), 2, 11),
86,
22,
);
assert_eq!(editor.cursor, 2);
editor.handle_mouse(
mouse(MouseEventKind::Down(MouseButton::Left), 2, 13),
86,
22,
);
assert_eq!(editor.cursor, 4);
}

#[test]
fn mouse_click_reaches_a_full_width_line_end() {
let mut editor = app();
editor.comment = "abcdefghijklmnop".chars().collect();
editor.cursor = 0;
editor.handle_mouse(
mouse(MouseEventKind::Down(MouseButton::Left), 18, 6),
20,
10,
);
assert_eq!(editor.cursor, editor.comment.len());
}

#[test]
fn mouse_releases_other_kinds_and_outside_clicks() {
let mut editor = app();
editor.comment = "abc".chars().collect();
editor.cursor = 1;
for kind in [
MouseEventKind::Up(MouseButton::Left),
MouseEventKind::Drag(MouseButton::Left),
MouseEventKind::Moved,
MouseEventKind::ScrollDown,
MouseEventKind::Down(MouseButton::Right),
] {
editor.handle_mouse(mouse(kind, 2, 10), 86, 22);
}
editor.handle_mouse(
mouse(MouseEventKind::Down(MouseButton::Left), 1, 10),
86,
22,
);
editor.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), 2, 9), 86, 22);
assert_eq!(editor.cursor, 1);
}
}
Loading