use std::cell::Cell;
use std::ops::Range;
use ratatui::Frame;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::layout::Rect;
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Clear, Paragraph};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr as _};
use crate::keys::{self, Action, Keymap};
use crate::theme::palette;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ComposeAction {
Edited,
Save,
Cancel,
}
#[derive(Debug, Default)]
pub(crate) struct Compose {
chars: Vec<char>,
cursor: usize,
initial: String,
asking: bool,
scroll: Cell<usize>,
}
pub(crate) const TAB_WIDTH: usize = 4;
fn width_of(c: char) -> usize {
if c == '\t' { TAB_WIDTH } else { UnicodeWidthChar::width(c).unwrap_or(0) }
}
fn shown(row: &str) -> String {
row.chars()
.flat_map(|c| match c {
'\t' => vec![' '; TAB_WIDTH],
c if c.is_control() => Vec::new(),
c => vec![c],
})
.collect()
}
impl Compose {
pub(crate) fn with_text(text: &str) -> Self {
let chars: Vec<char> = text.chars().collect();
let cursor = chars.len();
Self { chars, cursor, initial: text.to_owned(), asking: false, scroll: Cell::new(0) }
}
pub(crate) fn value(&self) -> String {
self.chars.iter().collect()
}
pub(crate) fn has_changes(&self) -> bool {
self.value().trim() != self.initial.trim()
}
pub(crate) fn key(&mut self, keymap: &Keymap, key: KeyEvent, wrap_width: usize) -> ComposeAction {
if self.asking {
match keymap.action(&key, keys::CONFIRM_CLEAR) {
Some(Action::Yes) => {
self.asking = false;
return ComposeAction::Cancel;
}
Some(Action::No | Action::Back) => self.asking = false,
_ => {}
}
return ComposeAction::Edited;
}
match self.handle_key(key, wrap_width) {
ComposeAction::Cancel if self.has_changes() => {
self.asking = true;
ComposeAction::Edited
}
action => action,
}
}
pub(crate) fn heading(&self, verb: &str, shift_enter: bool, keymap: &Keymap) -> String {
if !self.asking {
return title(verb, shift_enter);
}
let answers = [(Action::Yes, "discard"), (Action::No, "keep editing")]
.into_iter()
.filter_map(|(action, label)| keymap.labelled(action, label))
.collect::<Vec<_>>()
.join(" \u{b7} ");
format!(" discard {verb}? {answers} ")
}
pub(crate) fn handle_key(&mut self, key: KeyEvent, wrap_width: usize) -> ComposeAction {
let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
let alt = key.modifiers.contains(KeyModifiers::ALT);
match key.code {
KeyCode::Esc => return ComposeAction::Cancel,
KeyCode::Enter if key.modifiers.intersects(KeyModifiers::SHIFT | KeyModifiers::ALT) => {
self.insert('\n');
}
KeyCode::Enter => return ComposeAction::Save,
KeyCode::Char('j' | 'J') if key.modifiers.contains(KeyModifiers::CONTROL) => {
self.insert('\n');
}
KeyCode::Char('a' | 'A') if ctrl => self.cursor = self.line_start(),
KeyCode::Char('e' | 'E') if ctrl => self.cursor = self.line_end(),
KeyCode::Char('u' | 'U') if ctrl => self.delete_to(self.line_start()),
KeyCode::Char('k' | 'K') if ctrl => self.delete_to(self.line_end()),
KeyCode::Char('w' | 'W' | 'h' | 'H') if ctrl => self.delete_to(self.previous_word_start()),
KeyCode::Backspace if ctrl || alt => self.delete_to(self.previous_word_start()),
KeyCode::Char('d' | 'D') if alt => self.delete_to(self.next_word_end()),
KeyCode::Delete if ctrl => self.delete_to(self.next_word_end()),
KeyCode::Char('b' | 'B') if alt => self.cursor = self.previous_word_start(),
KeyCode::Char('f' | 'F') if alt => self.cursor = self.next_word_end(),
KeyCode::Backspace => {
if self.cursor > 0 {
self.cursor -= 1;
self.chars.remove(self.cursor);
}
}
KeyCode::Delete => {
if self.cursor < self.chars.len() {
self.chars.remove(self.cursor);
}
}
KeyCode::Left if ctrl || alt => self.cursor = self.previous_word_start(),
KeyCode::Right if ctrl || alt => self.cursor = self.next_word_end(),
KeyCode::Left => self.cursor = self.cursor.saturating_sub(1),
KeyCode::Right => self.cursor = (self.cursor + 1).min(self.chars.len()),
KeyCode::Up => self.move_vertical(-1, wrap_width),
KeyCode::Down => self.move_vertical(1, wrap_width),
KeyCode::Home => self.cursor = self.line_start(),
KeyCode::End => self.cursor = self.line_end(),
KeyCode::Char(c) if !ctrl && !alt => self.insert(c),
_ => {}
}
ComposeAction::Edited
}
pub(crate) fn insert_text(&mut self, text: &str) {
self.asking = false;
for c in text.replace("\r\n", "\n").replace('\r', "\n").chars() {
self.insert(c);
}
}
fn insert(&mut self, c: char) {
self.chars.insert(self.cursor, c);
self.cursor += 1;
}
fn delete_to(&mut self, index: usize) {
let range = self.cursor.min(index)..self.cursor.max(index);
self.cursor = range.start;
self.chars.drain(range);
}
fn line_start(&self) -> usize {
let mut index = self.cursor;
while index > 0 && self.chars.get(index - 1) != Some(&'\n') {
index -= 1;
}
index
}
fn line_end(&self) -> usize {
let mut index = self.cursor;
while index < self.chars.len() && self.chars.get(index) != Some(&'\n') {
index += 1;
}
index
}
fn is_word_char_at(&self, index: usize) -> bool {
self.chars.get(index).is_some_and(|c| c.is_alphanumeric() || *c == '_')
}
fn previous_word_start(&self) -> usize {
let mut index = self.cursor;
while index > 0 && !self.is_word_char_at(index - 1) {
index -= 1;
}
while index > 0 && self.is_word_char_at(index - 1) {
index -= 1;
}
index
}
fn next_word_end(&self) -> usize {
let mut index = self.cursor;
while index < self.chars.len() && !self.is_word_char_at(index) {
index += 1;
}
while index < self.chars.len() && self.is_word_char_at(index) {
index += 1;
}
index
}
fn move_vertical(&mut self, delta: isize, wrap_width: usize) {
let rows = self.rows(wrap_width);
let (row, col) = self.cursor_position(&rows);
let Some(target_row) = row.checked_add_signed(delta) else { return };
if let Some(cursor) = self.index_at(&rows, target_row, col) {
self.cursor = cursor;
}
}
#[cfg_attr(not(unix), allow(dead_code, reason = "only the code review reads it"))]
pub(crate) fn click(&mut self, row: usize, col: usize, wrap_width: usize) {
if self.asking {
return;
}
let rows = self.rows(wrap_width);
if let Some(cursor) = self.index_at(&rows, row.min(rows.len().saturating_sub(1)), col) {
self.cursor = cursor;
}
}
fn index_at(&self, rows: &[Range<usize>], row: usize, col: usize) -> Option<usize> {
let target = rows.get(row)?;
let mut cursor = target.start;
let mut used = 0;
for &c in self.chars.get(target.clone()).unwrap_or_default() {
let w = width_of(c);
if used + w > col {
break;
}
used += w;
cursor += 1;
}
let wraps = rows.get(row + 1).is_some_and(|next| next.start == target.end);
Some(if wraps && cursor == target.end { cursor.saturating_sub(1) } else { cursor })
}
fn rows(&self, width: usize) -> Vec<Range<usize>> {
let width = width.max(1);
let mut rows = Vec::new();
let (mut start, mut used) = (0, 0);
let mut word_start = None;
for (i, &c) in self.chars.iter().enumerate() {
if c == '\n' {
rows.push(start..i);
start = i + 1;
used = 0;
word_start = None;
continue;
}
let w = width_of(c);
if c.is_whitespace() {
word_start = Some(i + 1);
} else if used + w > width {
let at = word_start.take().unwrap_or(i);
if at > start {
rows.push(start..at);
start = at;
used = self.chars.get(at..i).unwrap_or_default().iter().copied().map(width_of).sum();
}
if used + w > width && i > start {
rows.push(start..i);
start = i;
used = 0;
}
}
used += w;
}
rows.push(start..self.chars.len());
rows
}
fn cursor_position(&self, rows: &[Range<usize>]) -> (usize, usize) {
let row = rows.iter().rposition(|range| range.start <= self.cursor).unwrap_or(0);
let start = rows.get(row).map_or(0, |range| range.start);
let before = self.chars.get(start..self.cursor).unwrap_or_default();
(row, before.iter().copied().map(width_of).sum())
}
pub(crate) fn wrapped(&self, width: usize) -> (Vec<String>, usize, usize) {
let rows = self.rows(width);
let (cursor_row, cursor_col) = self.cursor_position(&rows);
let lines = rows
.iter()
.map(|range| self.chars.get(range.clone()).unwrap_or_default().iter().collect())
.collect();
(lines, cursor_row, cursor_col)
}
}
pub(crate) const CHROME: u16 = 4;
pub(crate) fn title(verb: &str, shift_enter: bool) -> String {
let newline = if shift_enter { "shift+enter new line" } else { "alt+enter new line" };
format!(" {verb} \u{b7} enter saves \u{b7} {newline} \u{b7} esc cancels ")
}
fn split_title(title: &str, width: usize) -> (String, String) {
const SEPARATOR: &str = " \u{b7} ";
let mut first = String::new();
let mut rest: Vec<&str> = Vec::new();
for part in title.trim().split(SEPARATOR) {
let joined = if first.is_empty() { part.to_owned() } else { format!("{first}{SEPARATOR}{part}") };
if first.is_empty() || (rest.is_empty() && joined.width() + 2 <= width) {
first = joined;
} else {
rest.push(part);
}
}
(format!(" {first} "), rest.join(SEPARATOR))
}
fn content_rows(compose: &Compose, wrap_width: usize) -> usize {
compose.wrapped(wrap_width).0.len().clamp(1, 8)
}
pub(crate) fn height(compose: &Compose, wrap_width: usize) -> u16 {
content_rows(compose, wrap_width) as u16 + 2
}
pub(crate) fn draw(frame: &mut Frame, rect: Rect, compose: &Compose, title: &str) -> (Rect, usize) {
let rect = rect.intersection(frame.area());
frame.render_widget(Clear, rect);
let bordered = rect.height >= 3 && rect.width > CHROME;
let text = if bordered {
let title_style = if compose.asking { Style::new().bold() } else { Style::new().dim() };
let (title, title_rest) = split_title(title, usize::from(rect.width.saturating_sub(2)));
let mut boxed = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::new().fg(palette().comment))
.title(Span::styled(title, title_style));
if !title_rest.is_empty() {
boxed = boxed.title_bottom(Span::styled(format!(" {title_rest} "), title_style));
}
let inner = boxed.inner(rect);
frame.render_widget(boxed, rect);
Rect { x: inner.x + 1, width: inner.width.saturating_sub(1), ..inner }
} else {
rect
};
if text.is_empty() {
return (text, compose.scroll.get());
}
let wrap_width = usize::from(text.width.saturating_sub(1)).max(1);
let (lines, cursor_row, cursor_col) = compose.wrapped(wrap_width);
let content_rows = usize::from(text.height);
let last_start = lines.len().saturating_sub(content_rows);
let scroll =
compose.scroll.get().min(last_start).clamp(cursor_row.saturating_sub(content_rows - 1), cursor_row);
compose.scroll.set(scroll);
for (i, line) in lines.iter().skip(scroll).take(content_rows).enumerate() {
let row = Rect { y: text.y + i as u16, height: 1, ..text };
frame.render_widget(Paragraph::new(Line::from(shown(line))), row);
}
let cursor_x = text.x + cursor_col as u16;
let cursor_y = text.y + (cursor_row - scroll) as u16;
frame.set_cursor_position((cursor_x.min(text.right().saturating_sub(1)), cursor_y));
(text, scroll)
}
#[cfg(test)]
mod tests {
use super::*;
const WRAP_WIDTH: usize = 45;
fn press(compose: &mut Compose, code: KeyCode) {
compose.handle_key(KeyEvent::new(code, KeyModifiers::CONTROL), WRAP_WIDTH);
}
#[test]
fn a_word_that_does_not_fit_moves_whole_to_the_next_row() {
let (lines, _, _) = Compose::with_text("the quick brown fox").wrapped(10);
assert_eq!(lines, ["the quick ", "brown fox"]);
}
#[test]
fn a_word_wider_than_a_row_splits() {
let (lines, _, _) = Compose::with_text("hi aaaaaaaaaaaaaaa").wrapped(10);
assert_eq!(lines, ["hi ", "aaaaaaaaaa", "aaaaa"]);
}
#[test]
fn wrapping_keeps_every_character_of_the_buffer() {
let text = "spaces at a break and 日本語の長い行 keep their place";
let (lines, _, _) = Compose::with_text(text).wrapped(7);
assert_eq!(lines.concat(), text);
}
#[test]
fn wide_characters_never_overflow_a_row() {
let (lines, _, _) = Compose::with_text("a 日本語日本語").wrapped(5);
assert_eq!(lines, ["a ", "日本", "語日", "本語"]);
}
#[test]
fn spaces_past_the_edge_stay_on_the_row_they_follow() {
let (lines, row, col) = Compose::with_text("0123456789 ").wrapped(10);
assert_eq!(lines, ["0123456789 "]);
assert_eq!((row, col), (0, 12));
}
#[test]
fn the_cursor_follows_a_word_as_it_wraps() {
let mut compose = Compose::with_text("0123456 ");
compose.insert_text("abcdef");
assert_eq!(compose.wrapped(10), (vec!["0123456 ".to_owned(), "abcdef".to_owned()], 1, 6));
}
#[test]
fn up_and_down_cross_a_word_wrap_without_sticking() {
let mut compose = Compose::with_text("the quick brown fox");
compose.cursor = 0;
compose.handle_key(KeyEvent::from(KeyCode::Down), 10);
assert_eq!(compose.wrapped(10).1, 1);
compose.handle_key(KeyEvent::from(KeyCode::End), 10);
compose.handle_key(KeyEvent::from(KeyCode::Up), 10);
assert_eq!(compose.wrapped(10).1, 0, "the end of the long row maps back onto the first");
}
#[test]
fn ctrl_w_deletes_the_word_before_the_cursor_and_its_trailing_separators() {
let mut compose = Compose::with_text("one two, ");
press(&mut compose, KeyCode::Char('w'));
assert_eq!(compose.value(), "one ");
assert_eq!(compose.cursor, 4);
}
#[test]
fn ctrl_w_keeps_the_text_after_the_cursor() {
let mut compose = Compose::with_text("one two");
compose.cursor = 5;
press(&mut compose, KeyCode::Char('w'));
assert_eq!(compose.value(), "one wo");
assert_eq!(compose.cursor, 4);
}
#[test]
fn ctrl_w_at_the_start_of_the_buffer_changes_nothing() {
let mut compose = Compose::with_text("one");
compose.cursor = 0;
press(&mut compose, KeyCode::Char('w'));
assert_eq!(compose.value(), "one");
assert_eq!(compose.cursor, 0);
}
#[test]
fn ctrl_left_lands_on_each_word_start_and_stops_at_the_buffer_start() {
let mut compose = Compose::with_text("foo_1 bar-baz\nqux");
let mut stops = Vec::new();
for _ in 0..5 {
press(&mut compose, KeyCode::Left);
stops.push(compose.cursor);
}
assert_eq!(stops, [14, 10, 6, 0, 0]);
}
#[test]
fn ctrl_right_lands_on_each_word_end_and_stops_at_the_buffer_end() {
let mut compose = Compose::with_text("foo_1 bar-baz\nqux");
compose.cursor = 0;
let mut stops = Vec::new();
for _ in 0..5 {
press(&mut compose, KeyCode::Right);
stops.push(compose.cursor);
}
assert_eq!(stops, [5, 9, 13, 17, 17]);
}
fn send(compose: &mut Compose, code: KeyCode, modifiers: KeyModifiers) {
compose.handle_key(KeyEvent::new(code, modifiers), WRAP_WIDTH);
}
#[test]
fn ctrl_a_and_ctrl_e_stay_on_the_logical_line() {
let mut compose = Compose::with_text("one\ntwo three\nfour");
compose.cursor = 6;
press(&mut compose, KeyCode::Char('a'));
assert_eq!(compose.cursor, 4);
press(&mut compose, KeyCode::Char('e'));
assert_eq!(compose.cursor, 13);
}
#[test]
fn ctrl_u_and_ctrl_k_delete_to_the_line_edges_and_keep_other_lines() {
let mut compose = Compose::with_text("one\ntwo three\nfour");
compose.cursor = 7;
press(&mut compose, KeyCode::Char('u'));
assert_eq!(compose.value(), "one\n three\nfour");
assert_eq!(compose.cursor, 4);
press(&mut compose, KeyCode::Char('k'));
assert_eq!(compose.value(), "one\n\nfour");
assert_eq!(compose.cursor, 4);
}
#[test]
fn every_previous_word_delete_key_deletes_the_word() {
let keys = [
(KeyCode::Char('w'), KeyModifiers::CONTROL),
(KeyCode::Char('h'), KeyModifiers::CONTROL),
(KeyCode::Backspace, KeyModifiers::ALT),
(KeyCode::Backspace, KeyModifiers::CONTROL),
];
for (code, modifiers) in keys {
let mut compose = Compose::with_text("one two");
send(&mut compose, code, modifiers);
assert_eq!(compose.value(), "one ", "{code:?} {modifiers:?}");
}
}
#[test]
fn every_next_word_delete_key_deletes_the_word() {
let keys = [(KeyCode::Char('d'), KeyModifiers::ALT), (KeyCode::Delete, KeyModifiers::CONTROL)];
for (code, modifiers) in keys {
let mut compose = Compose::with_text("one two three");
compose.cursor = 3;
send(&mut compose, code, modifiers);
assert_eq!(compose.value(), "one three", "{code:?} {modifiers:?}");
assert_eq!(compose.cursor, 3);
}
}
#[test]
fn plain_backspace_and_delete_still_remove_one_character() {
let mut compose = Compose::with_text("one two");
send(&mut compose, KeyCode::Backspace, KeyModifiers::NONE);
assert_eq!(compose.value(), "one tw");
compose.cursor = 0;
send(&mut compose, KeyCode::Delete, KeyModifiers::NONE);
assert_eq!(compose.value(), "ne tw");
}
#[test]
fn alt_keys_jump_by_word_like_ctrl_arrows() {
for (code, modifiers) in [(KeyCode::Left, KeyModifiers::ALT), (KeyCode::Char('b'), KeyModifiers::ALT)]
{
let mut compose = Compose::with_text("one two");
send(&mut compose, code, modifiers);
assert_eq!(compose.cursor, 4, "{code:?}");
}
for (code, modifiers) in
[(KeyCode::Right, KeyModifiers::ALT), (KeyCode::Char('f'), KeyModifiers::ALT)]
{
let mut compose = Compose::with_text("one two");
compose.cursor = 0;
send(&mut compose, code, modifiers);
assert_eq!(compose.cursor, 3, "{code:?}");
}
}
#[test]
fn up_and_down_move_between_wrapped_rows_of_one_line() {
let text = "a".repeat(WRAP_WIDTH * 2 + 10);
let mut compose = Compose::with_text(&text);
compose.cursor = WRAP_WIDTH + 5;
send(&mut compose, KeyCode::Up, KeyModifiers::NONE);
assert_eq!(compose.cursor, 5);
send(&mut compose, KeyCode::Down, KeyModifiers::NONE);
assert_eq!(compose.cursor, WRAP_WIDTH + 5);
send(&mut compose, KeyCode::Down, KeyModifiers::NONE);
assert_eq!(compose.cursor, WRAP_WIDTH * 2 + 5);
}
#[test]
fn up_on_the_first_row_and_down_on_the_last_stay_put() {
let mut compose = Compose::with_text("one\ntwo");
compose.cursor = 1;
send(&mut compose, KeyCode::Up, KeyModifiers::NONE);
assert_eq!(compose.cursor, 1);
compose.cursor = 5;
send(&mut compose, KeyCode::Down, KeyModifiers::NONE);
assert_eq!(compose.cursor, 5);
}
#[test]
fn down_from_column_zero_lands_visibly_on_the_next_wrapped_row() {
let text = "a".repeat(WRAP_WIDTH * 2);
let mut compose = Compose::with_text(&text);
compose.cursor = 0;
send(&mut compose, KeyCode::Down, KeyModifiers::NONE);
let (_, row, col) = compose.wrapped(WRAP_WIDTH);
assert_eq!((row, col), (1, 0));
}
#[test]
fn up_from_past_a_full_row_stays_on_that_row() {
let text = "a".repeat(WRAP_WIDTH * 2);
let mut compose = Compose::with_text(&text);
send(&mut compose, KeyCode::Up, KeyModifiers::NONE);
let (_, row, col) = compose.wrapped(WRAP_WIDTH);
assert_eq!((row, col), (0, WRAP_WIDTH - 1));
}
#[test]
fn vertical_moves_keep_the_display_column_across_wide_characters() {
let mut compose = Compose::with_text("日本語\nabcdef");
compose.cursor = 7;
send(&mut compose, KeyCode::Up, KeyModifiers::NONE);
assert_eq!(compose.cursor, 1);
}
#[test]
fn a_click_puts_the_cursor_at_the_clicked_cell_or_the_end_of_its_row() {
let mut compose = Compose::with_text("the quick brown fox\njumps");
compose.click(0, 4, 10);
assert_eq!(compose.cursor, 4, "on the q");
compose.click(1, 40, 10);
assert_eq!(compose.cursor, 19, "past the end of the second display row: its end");
compose.click(7, 1, 10);
assert_eq!(compose.cursor, 21, "below the text: the last row");
}
fn drawn(compose: &Compose, cols: u16, rows: u16, rect: Rect) -> (Vec<String>, (Rect, usize)) {
let mut terminal =
ratatui::Terminal::new(ratatui::backend::TestBackend::new(cols, rows)).expect("terminal");
let mut at = (Rect::default(), 0);
terminal.draw(|frame| at = draw(frame, rect, compose, " comment ")).expect("draw");
let buffer = terminal.backend().buffer();
let text = (0..rows)
.map(|y| (0..cols).filter_map(|x| buffer.cell((x, y)).map(|c| c.symbol().to_owned())).collect())
.collect();
(text, at)
}
#[test]
fn tabs_draw_as_four_columns_and_stay_tabs_in_the_text() {
let compose = Compose::with_text("\tindented\twith tabs\r");
let (rows, _) = drawn(&compose, 40, 3, Rect::new(0, 0, 40, 3));
assert!(rows.get(1).is_some_and(|r| r.contains(" indented with tabs ")), "{rows:?}");
assert_eq!(compose.value(), "\tindented\twith tabs\r");
}
#[test]
fn a_box_too_short_for_its_borders_draws_its_text_inside_its_rectangle_alone() {
for height in [0, 1, 2] {
let mut compose = Compose::default();
compose.insert_text("some draft text");
let rect = Rect::new(2, 2, 30, height);
let (rows, (text, _)) = drawn(&compose, 40, 6, rect);
for (y, row) in rows.iter().enumerate() {
let inside = (rect.top()..rect.bottom()).contains(&(y as u16));
assert!(inside || row.trim().is_empty(), "height {height}: row {y} is {row:?}");
}
assert!(rect.union(text) == rect || text.is_empty(), "height {height}: {text:?}");
if height > 0 {
assert!(rows.get(2).is_some_and(|r| r.contains("some draft")), "height {height}: {rows:?}");
assert!(!rows.concat().contains('\u{256d}'), "no borders");
}
assert_eq!(compose.value(), "some draft text", "the draft stays");
}
}
#[test]
fn the_text_stays_put_while_the_cursor_moves_inside_the_rows_shown() {
let text: Vec<String> = (0..50).map(|n| format!("line {n}")).collect();
let mut compose = Compose::with_text(&text.join("\n"));
let rect = Rect::new(0, 0, 30, 10);
let (rows, (_, first)) = drawn(&compose, 30, 10, rect);
assert_eq!(first, 42, "the end shows: {rows:?}");
compose.click(45, 0, 26);
let (rows, (_, first)) = drawn(&compose, 30, 10, rect);
assert_eq!(first, 42, "a click on a shown row moves nothing: {rows:?}");
compose.click(first + 1, 0, 26);
compose.insert_text("X");
assert!(compose.value().contains("\nXline 43\n"), "the next click lands on the row clicked");
compose.handle_key(KeyEvent::from(KeyCode::Up), 26);
let (_, (_, first)) = drawn(&compose, 30, 10, rect);
assert_eq!(first, 42, "Up inside the rows shown moves nothing either");
compose.handle_key(KeyEvent::from(KeyCode::Up), 26);
let (_, (_, first)) = drawn(&compose, 30, 10, rect);
assert_eq!(first, 41, "Up past the first row shown scrolls one row");
}
#[test]
fn only_a_real_change_counts_as_unsaved() {
assert!(!Compose::default().has_changes());
assert!(!Compose::with_text("body").has_changes());
let mut blank = Compose::default();
blank.insert_text(" \n ");
assert!(!blank.has_changes(), "whitespace alone would never be saved");
let mut edited = Compose::with_text("body");
edited.insert_text("!");
assert!(edited.has_changes());
send(&mut edited, KeyCode::Backspace, KeyModifiers::NONE);
assert!(!edited.has_changes(), "typing it back to the original loses nothing");
}
#[test]
fn non_ascii_letters_count_as_word_characters() {
let mut compose = Compose::with_text("über größe");
press(&mut compose, KeyCode::Char('w'));
assert_eq!(compose.value(), "über ");
}
}