use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputMode {
Normal,
Insert,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PendingOp {
Delete,
Replace,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputAction {
Consumed,
Cancel,
Submit,
Ignored,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextInput {
pub value: String,
pub cursor: usize, pub mode: InputMode,
pub pending_op: Option<PendingOp>,
}
impl Default for TextInput {
fn default() -> Self {
Self::new("")
}
}
impl TextInput {
pub fn new(initial: impl Into<String>) -> Self {
let value = initial.into();
let cursor = value.chars().count();
Self {
value,
cursor,
mode: InputMode::Insert,
pending_op: None,
}
}
pub fn char_len(&self) -> usize {
self.value.chars().count()
}
fn byte_index(&self, char_idx: usize) -> usize {
self.value
.char_indices()
.nth(char_idx)
.map(|(i, _)| i)
.unwrap_or(self.value.len())
}
fn clamp_cursor(&mut self) {
let len = self.char_len();
match self.mode {
InputMode::Insert => {
if self.cursor > len {
self.cursor = len;
}
}
InputMode::Normal => {
if len == 0 {
self.cursor = 0;
} else if self.cursor >= len {
self.cursor = len - 1;
}
}
}
}
fn next_word_pos(&self) -> usize {
let chars: Vec<char> = self.value.chars().collect();
let len = chars.len();
if self.cursor >= len {
return len;
}
let mut i = self.cursor;
let is_word = |c: char| c.is_alphanumeric() || c == '_';
if is_word(chars[i]) {
while i < len && is_word(chars[i]) {
i += 1;
}
} else if !chars[i].is_whitespace() {
while i < len && !is_word(chars[i]) && !chars[i].is_whitespace() {
i += 1;
}
}
while i < len && chars[i].is_whitespace() {
i += 1;
}
i
}
fn prev_word_pos(&self) -> usize {
let chars: Vec<char> = self.value.chars().collect();
if self.cursor == 0 || chars.is_empty() {
return 0;
}
let mut i = self.cursor.min(chars.len());
let is_word = |c: char| c.is_alphanumeric() || c == '_';
i = i.saturating_sub(1);
while i > 0 && chars[i].is_whitespace() {
i -= 1;
}
if is_word(chars[i]) {
while i > 0 && is_word(chars[i - 1]) {
i -= 1;
}
} else if !chars[i].is_whitespace() {
while i > 0 && !is_word(chars[i - 1]) && !chars[i - 1].is_whitespace() {
i -= 1;
}
}
i
}
fn delete_range(&mut self, start_char: usize, end_char: usize) {
if start_char >= end_char {
return;
}
let start_b = self.byte_index(start_char);
let end_b = self.byte_index(end_char);
self.value.replace_range(start_b..end_b, "");
self.cursor = start_char;
self.clamp_cursor();
}
pub fn handle_key(&mut self, key: KeyEvent) -> InputAction {
if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
return InputAction::Cancel;
}
match self.mode {
InputMode::Insert => self.handle_insert(key),
InputMode::Normal => self.handle_normal(key),
}
}
fn handle_insert(&mut self, key: KeyEvent) -> InputAction {
match key.code {
KeyCode::Esc => {
self.mode = InputMode::Normal;
self.pending_op = None;
self.cursor = self.cursor.saturating_sub(1);
self.clamp_cursor();
InputAction::Consumed
}
KeyCode::Enter => InputAction::Submit,
KeyCode::Left => {
self.cursor = self.cursor.saturating_sub(1);
InputAction::Consumed
}
KeyCode::Right => {
let len = self.char_len();
if self.cursor < len {
self.cursor += 1;
}
InputAction::Consumed
}
KeyCode::Home => {
self.cursor = 0;
InputAction::Consumed
}
KeyCode::End => {
self.cursor = self.char_len();
InputAction::Consumed
}
KeyCode::Backspace => {
if self.cursor > 0 {
let start = self.byte_index(self.cursor - 1);
let end = self.byte_index(self.cursor);
self.value.replace_range(start..end, "");
self.cursor -= 1;
}
InputAction::Consumed
}
KeyCode::Delete => {
let len = self.char_len();
if self.cursor < len {
let start = self.byte_index(self.cursor);
let end = self.byte_index(self.cursor + 1);
self.value.replace_range(start..end, "");
}
InputAction::Consumed
}
KeyCode::Char(c) => {
let idx = self.byte_index(self.cursor);
self.value.insert(idx, c);
self.cursor += 1;
InputAction::Consumed
}
_ => InputAction::Ignored,
}
}
fn handle_normal(&mut self, key: KeyEvent) -> InputAction {
if let Some(op) = self.pending_op.take() {
match op {
PendingOp::Replace => {
if let KeyCode::Char(c) = key.code {
let len = self.char_len();
if self.cursor < len {
let start = self.byte_index(self.cursor);
let end = self.byte_index(self.cursor + 1);
let mut buf = [0u8; 4];
let s = c.encode_utf8(&mut buf);
self.value.replace_range(start..end, s);
}
return InputAction::Consumed;
}
return InputAction::Consumed;
}
PendingOp::Delete => {
match key.code {
KeyCode::Char('d') => {
self.value.clear();
self.cursor = 0;
}
KeyCode::Char('w') => {
let end = self.next_word_pos();
self.delete_range(self.cursor, end);
}
KeyCode::Char('b') => {
let start = self.prev_word_pos();
self.delete_range(start, self.cursor);
}
KeyCode::Char('$') | KeyCode::End => {
let len = self.char_len();
self.delete_range(self.cursor, len);
}
KeyCode::Char('0') | KeyCode::Home => {
self.delete_range(0, self.cursor);
}
_ => {}
}
return InputAction::Consumed;
}
}
}
match key.code {
KeyCode::Esc => InputAction::Cancel,
KeyCode::Enter => InputAction::Submit,
KeyCode::Char('i') => {
self.mode = InputMode::Insert;
InputAction::Consumed
}
KeyCode::Char('a') => {
self.mode = InputMode::Insert;
let len = self.char_len();
if self.cursor < len {
self.cursor += 1;
}
InputAction::Consumed
}
KeyCode::Char('I') => {
self.mode = InputMode::Insert;
self.cursor = 0;
InputAction::Consumed
}
KeyCode::Char('A') => {
self.mode = InputMode::Insert;
self.cursor = self.char_len();
InputAction::Consumed
}
KeyCode::Char('h') | KeyCode::Left => {
self.cursor = self.cursor.saturating_sub(1);
InputAction::Consumed
}
KeyCode::Char('l') | KeyCode::Right => {
let len = self.char_len();
if len > 0 && self.cursor + 1 < len {
self.cursor += 1;
}
InputAction::Consumed
}
KeyCode::Char('0') | KeyCode::Home => {
self.cursor = 0;
InputAction::Consumed
}
KeyCode::Char('$') | KeyCode::End => {
let len = self.char_len();
self.cursor = len.saturating_sub(1);
InputAction::Consumed
}
KeyCode::Char('w') => {
let next = self.next_word_pos();
let len = self.char_len();
self.cursor = if len == 0 { 0 } else { next.min(len - 1) };
InputAction::Consumed
}
KeyCode::Char('b') => {
self.cursor = self.prev_word_pos();
InputAction::Consumed
}
KeyCode::Char('x') | KeyCode::Delete => {
let len = self.char_len();
if self.cursor < len {
self.delete_range(self.cursor, self.cursor + 1);
}
InputAction::Consumed
}
KeyCode::Char('r') => {
self.pending_op = Some(PendingOp::Replace);
InputAction::Consumed
}
KeyCode::Char('D') => {
let len = self.char_len();
self.delete_range(self.cursor, len);
InputAction::Consumed
}
KeyCode::Char('d') => {
self.pending_op = Some(PendingOp::Delete);
InputAction::Consumed
}
_ => InputAction::Ignored,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn key(code: KeyCode) -> KeyEvent {
KeyEvent::new(code, KeyModifiers::NONE)
}
#[test]
fn test_insert_and_cursor_navigation() {
let mut ti = TextInput::new("helo");
assert_eq!(ti.cursor, 4);
ti.handle_key(key(KeyCode::Left));
ti.handle_key(key(KeyCode::Left));
assert_eq!(ti.cursor, 2);
ti.handle_key(key(KeyCode::Char('l')));
assert_eq!(ti.value, "hello");
assert_eq!(ti.cursor, 3);
ti.handle_key(key(KeyCode::Home));
assert_eq!(ti.cursor, 0);
ti.handle_key(key(KeyCode::Delete));
assert_eq!(ti.value, "ello");
ti.handle_key(key(KeyCode::End));
assert_eq!(ti.cursor, 4);
ti.handle_key(key(KeyCode::Backspace));
assert_eq!(ti.value, "ell");
}
#[test]
fn test_vim_modes_and_motions() {
let mut ti = TextInput::new("one two three");
ti.handle_key(key(KeyCode::Esc));
assert_eq!(ti.mode, InputMode::Normal);
assert_eq!(ti.cursor, 12);
ti.handle_key(key(KeyCode::Char('0')));
assert_eq!(ti.cursor, 0);
ti.handle_key(key(KeyCode::Char('w')));
assert_eq!(ti.cursor, 4);
ti.handle_key(key(KeyCode::Char('w')));
assert_eq!(ti.cursor, 8);
ti.handle_key(key(KeyCode::Char('b')));
assert_eq!(ti.cursor, 4);
ti.handle_key(key(KeyCode::Char('$')));
assert_eq!(ti.cursor, 12);
ti.handle_key(key(KeyCode::Char('h')));
assert_eq!(ti.cursor, 11);
ti.handle_key(key(KeyCode::Char('l')));
assert_eq!(ti.cursor, 12);
}
#[test]
fn test_vim_normal_editing() {
let mut ti = TextInput::new("alpha beta gamma");
ti.handle_key(key(KeyCode::Esc));
ti.handle_key(key(KeyCode::Char('0')));
ti.handle_key(key(KeyCode::Char('x')));
assert_eq!(ti.value, "lpha beta gamma");
ti.handle_key(key(KeyCode::Char('r')));
ti.handle_key(key(KeyCode::Char('A')));
assert_eq!(ti.value, "Apha beta gamma");
ti.handle_key(key(KeyCode::Char('d')));
ti.handle_key(key(KeyCode::Char('w')));
assert_eq!(ti.value, "beta gamma");
ti.handle_key(key(KeyCode::Char('w'))); ti.handle_key(key(KeyCode::Char('d')));
ti.handle_key(key(KeyCode::Char('$')));
assert_eq!(ti.value, "beta ");
ti.handle_key(key(KeyCode::Char('d')));
ti.handle_key(key(KeyCode::Char('d')));
assert_eq!(ti.value, "");
assert_eq!(ti.cursor, 0);
}
#[test]
fn test_vim_db_and_d0_and_d() {
let mut ti = TextInput::new("one two three");
ti.handle_key(key(KeyCode::Esc));
ti.handle_key(key(KeyCode::Char('0')));
ti.handle_key(key(KeyCode::Char('w'))); ti.handle_key(key(KeyCode::Char('w'))); ti.handle_key(key(KeyCode::Char('d')));
ti.handle_key(key(KeyCode::Char('b')));
assert_eq!(ti.value, "one three");
assert_eq!(ti.cursor, 4);
ti.handle_key(key(KeyCode::Char('D')));
assert_eq!(ti.value, "one ");
ti.handle_key(key(KeyCode::Char('d')));
ti.handle_key(key(KeyCode::Char('0')));
assert_eq!(ti.value, " ");
}
}