1use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum InputMode {
5 Normal,
6 Insert,
7}
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum PendingOp {
11 Delete,
12 Replace,
13}
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum InputAction {
17 Consumed,
19 Cancel,
21 Submit,
23 Ignored,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct TextInput {
29 pub value: String,
30 pub cursor: usize, pub mode: InputMode,
32 pub pending_op: Option<PendingOp>,
33}
34
35impl Default for TextInput {
36 fn default() -> Self {
37 Self::new("")
38 }
39}
40
41impl TextInput {
42 pub fn new(initial: impl Into<String>) -> Self {
43 let value = initial.into();
44 let cursor = value.chars().count();
45 Self {
46 value,
47 cursor,
48 mode: InputMode::Insert,
49 pending_op: None,
50 }
51 }
52
53 pub fn char_len(&self) -> usize {
54 self.value.chars().count()
55 }
56
57 fn byte_index(&self, char_idx: usize) -> usize {
58 self.value
59 .char_indices()
60 .nth(char_idx)
61 .map(|(i, _)| i)
62 .unwrap_or(self.value.len())
63 }
64
65 fn clamp_cursor(&mut self) {
66 let len = self.char_len();
67 match self.mode {
68 InputMode::Insert => {
69 if self.cursor > len {
70 self.cursor = len;
71 }
72 }
73 InputMode::Normal => {
74 if len == 0 {
75 self.cursor = 0;
76 } else if self.cursor >= len {
77 self.cursor = len - 1;
78 }
79 }
80 }
81 }
82
83 fn next_word_pos(&self) -> usize {
84 let chars: Vec<char> = self.value.chars().collect();
85 let len = chars.len();
86 if self.cursor >= len {
87 return len;
88 }
89 let mut i = self.cursor;
90 let is_word = |c: char| c.is_alphanumeric() || c == '_';
91 if is_word(chars[i]) {
92 while i < len && is_word(chars[i]) {
93 i += 1;
94 }
95 } else if !chars[i].is_whitespace() {
96 while i < len && !is_word(chars[i]) && !chars[i].is_whitespace() {
97 i += 1;
98 }
99 }
100 while i < len && chars[i].is_whitespace() {
101 i += 1;
102 }
103 i
104 }
105
106 fn prev_word_pos(&self) -> usize {
107 let chars: Vec<char> = self.value.chars().collect();
108 if self.cursor == 0 || chars.is_empty() {
109 return 0;
110 }
111 let mut i = self.cursor.min(chars.len());
112 let is_word = |c: char| c.is_alphanumeric() || c == '_';
113 i = i.saturating_sub(1);
114 while i > 0 && chars[i].is_whitespace() {
115 i -= 1;
116 }
117 if is_word(chars[i]) {
118 while i > 0 && is_word(chars[i - 1]) {
119 i -= 1;
120 }
121 } else if !chars[i].is_whitespace() {
122 while i > 0 && !is_word(chars[i - 1]) && !chars[i - 1].is_whitespace() {
123 i -= 1;
124 }
125 }
126 i
127 }
128
129 fn delete_range(&mut self, start_char: usize, end_char: usize) {
130 if start_char >= end_char {
131 return;
132 }
133 let start_b = self.byte_index(start_char);
134 let end_b = self.byte_index(end_char);
135 self.value.replace_range(start_b..end_b, "");
136 self.cursor = start_char;
137 self.clamp_cursor();
138 }
139
140 pub fn handle_key(&mut self, key: KeyEvent) -> InputAction {
141 if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
142 return InputAction::Cancel;
143 }
144
145 match self.mode {
146 InputMode::Insert => self.handle_insert(key),
147 InputMode::Normal => self.handle_normal(key),
148 }
149 }
150
151 fn handle_insert(&mut self, key: KeyEvent) -> InputAction {
152 match key.code {
153 KeyCode::Esc => {
154 self.mode = InputMode::Normal;
155 self.pending_op = None;
156 self.cursor = self.cursor.saturating_sub(1);
157 self.clamp_cursor();
158 InputAction::Consumed
159 }
160 KeyCode::Enter => InputAction::Submit,
161 KeyCode::Left => {
162 self.cursor = self.cursor.saturating_sub(1);
163 InputAction::Consumed
164 }
165 KeyCode::Right => {
166 let len = self.char_len();
167 if self.cursor < len {
168 self.cursor += 1;
169 }
170 InputAction::Consumed
171 }
172 KeyCode::Home => {
173 self.cursor = 0;
174 InputAction::Consumed
175 }
176 KeyCode::End => {
177 self.cursor = self.char_len();
178 InputAction::Consumed
179 }
180 KeyCode::Backspace => {
181 if self.cursor > 0 {
182 let start = self.byte_index(self.cursor - 1);
183 let end = self.byte_index(self.cursor);
184 self.value.replace_range(start..end, "");
185 self.cursor -= 1;
186 }
187 InputAction::Consumed
188 }
189 KeyCode::Delete => {
190 let len = self.char_len();
191 if self.cursor < len {
192 let start = self.byte_index(self.cursor);
193 let end = self.byte_index(self.cursor + 1);
194 self.value.replace_range(start..end, "");
195 }
196 InputAction::Consumed
197 }
198 KeyCode::Char(c) => {
199 let idx = self.byte_index(self.cursor);
200 self.value.insert(idx, c);
201 self.cursor += 1;
202 InputAction::Consumed
203 }
204 _ => InputAction::Ignored,
205 }
206 }
207
208 fn handle_normal(&mut self, key: KeyEvent) -> InputAction {
209 if let Some(op) = self.pending_op.take() {
210 match op {
211 PendingOp::Replace => {
212 if let KeyCode::Char(c) = key.code {
213 let len = self.char_len();
214 if self.cursor < len {
215 let start = self.byte_index(self.cursor);
216 let end = self.byte_index(self.cursor + 1);
217 let mut buf = [0u8; 4];
218 let s = c.encode_utf8(&mut buf);
219 self.value.replace_range(start..end, s);
220 }
221 return InputAction::Consumed;
222 }
223 return InputAction::Consumed;
224 }
225 PendingOp::Delete => {
226 match key.code {
227 KeyCode::Char('d') => {
228 self.value.clear();
229 self.cursor = 0;
230 }
231 KeyCode::Char('w') => {
232 let end = self.next_word_pos();
233 self.delete_range(self.cursor, end);
234 }
235 KeyCode::Char('b') => {
236 let start = self.prev_word_pos();
237 self.delete_range(start, self.cursor);
238 }
239 KeyCode::Char('$') | KeyCode::End => {
240 let len = self.char_len();
241 self.delete_range(self.cursor, len);
242 }
243 KeyCode::Char('0') | KeyCode::Home => {
244 self.delete_range(0, self.cursor);
245 }
246 _ => {}
247 }
248 return InputAction::Consumed;
249 }
250 }
251 }
252
253 match key.code {
254 KeyCode::Esc => InputAction::Cancel,
255 KeyCode::Enter => InputAction::Submit,
256 KeyCode::Char('i') => {
258 self.mode = InputMode::Insert;
259 InputAction::Consumed
260 }
261 KeyCode::Char('a') => {
262 self.mode = InputMode::Insert;
263 let len = self.char_len();
264 if self.cursor < len {
265 self.cursor += 1;
266 }
267 InputAction::Consumed
268 }
269 KeyCode::Char('I') => {
270 self.mode = InputMode::Insert;
271 self.cursor = 0;
272 InputAction::Consumed
273 }
274 KeyCode::Char('A') => {
275 self.mode = InputMode::Insert;
276 self.cursor = self.char_len();
277 InputAction::Consumed
278 }
279 KeyCode::Char('h') | KeyCode::Left => {
281 self.cursor = self.cursor.saturating_sub(1);
282 InputAction::Consumed
283 }
284 KeyCode::Char('l') | KeyCode::Right => {
285 let len = self.char_len();
286 if len > 0 && self.cursor + 1 < len {
287 self.cursor += 1;
288 }
289 InputAction::Consumed
290 }
291 KeyCode::Char('0') | KeyCode::Home => {
292 self.cursor = 0;
293 InputAction::Consumed
294 }
295 KeyCode::Char('$') | KeyCode::End => {
296 let len = self.char_len();
297 self.cursor = len.saturating_sub(1);
298 InputAction::Consumed
299 }
300 KeyCode::Char('w') => {
301 let next = self.next_word_pos();
302 let len = self.char_len();
303 self.cursor = if len == 0 { 0 } else { next.min(len - 1) };
304 InputAction::Consumed
305 }
306 KeyCode::Char('b') => {
307 self.cursor = self.prev_word_pos();
308 InputAction::Consumed
309 }
310 KeyCode::Char('x') | KeyCode::Delete => {
312 let len = self.char_len();
313 if self.cursor < len {
314 self.delete_range(self.cursor, self.cursor + 1);
315 }
316 InputAction::Consumed
317 }
318 KeyCode::Char('r') => {
319 self.pending_op = Some(PendingOp::Replace);
320 InputAction::Consumed
321 }
322 KeyCode::Char('D') => {
323 let len = self.char_len();
324 self.delete_range(self.cursor, len);
325 InputAction::Consumed
326 }
327 KeyCode::Char('d') => {
328 self.pending_op = Some(PendingOp::Delete);
329 InputAction::Consumed
330 }
331 _ => InputAction::Ignored,
332 }
333 }
334}
335
336#[cfg(test)]
337mod tests {
338 use super::*;
339
340 fn key(code: KeyCode) -> KeyEvent {
341 KeyEvent::new(code, KeyModifiers::NONE)
342 }
343
344 #[test]
345 fn test_insert_and_cursor_navigation() {
346 let mut ti = TextInput::new("helo");
347 assert_eq!(ti.cursor, 4);
348 ti.handle_key(key(KeyCode::Left));
349 ti.handle_key(key(KeyCode::Left));
350 assert_eq!(ti.cursor, 2);
351 ti.handle_key(key(KeyCode::Char('l')));
352 assert_eq!(ti.value, "hello");
353 assert_eq!(ti.cursor, 3);
354 ti.handle_key(key(KeyCode::Home));
355 assert_eq!(ti.cursor, 0);
356 ti.handle_key(key(KeyCode::Delete));
357 assert_eq!(ti.value, "ello");
358 ti.handle_key(key(KeyCode::End));
359 assert_eq!(ti.cursor, 4);
360 ti.handle_key(key(KeyCode::Backspace));
361 assert_eq!(ti.value, "ell");
362 }
363
364 #[test]
365 fn test_vim_modes_and_motions() {
366 let mut ti = TextInput::new("one two three");
367 ti.handle_key(key(KeyCode::Esc));
368 assert_eq!(ti.mode, InputMode::Normal);
369 assert_eq!(ti.cursor, 12);
370
371 ti.handle_key(key(KeyCode::Char('0')));
372 assert_eq!(ti.cursor, 0);
373
374 ti.handle_key(key(KeyCode::Char('w')));
375 assert_eq!(ti.cursor, 4); ti.handle_key(key(KeyCode::Char('w')));
378 assert_eq!(ti.cursor, 8); ti.handle_key(key(KeyCode::Char('b')));
381 assert_eq!(ti.cursor, 4);
382
383 ti.handle_key(key(KeyCode::Char('$')));
384 assert_eq!(ti.cursor, 12);
385
386 ti.handle_key(key(KeyCode::Char('h')));
387 assert_eq!(ti.cursor, 11);
388
389 ti.handle_key(key(KeyCode::Char('l')));
390 assert_eq!(ti.cursor, 12);
391 }
392
393 #[test]
394 fn test_vim_normal_editing() {
395 let mut ti = TextInput::new("alpha beta gamma");
396 ti.handle_key(key(KeyCode::Esc));
397 ti.handle_key(key(KeyCode::Char('0')));
398
399 ti.handle_key(key(KeyCode::Char('x')));
401 assert_eq!(ti.value, "lpha beta gamma");
402
403 ti.handle_key(key(KeyCode::Char('r')));
405 ti.handle_key(key(KeyCode::Char('A')));
406 assert_eq!(ti.value, "Apha beta gamma");
407
408 ti.handle_key(key(KeyCode::Char('d')));
410 ti.handle_key(key(KeyCode::Char('w')));
411 assert_eq!(ti.value, "beta gamma");
412
413 ti.handle_key(key(KeyCode::Char('w'))); ti.handle_key(key(KeyCode::Char('d')));
416 ti.handle_key(key(KeyCode::Char('$')));
417 assert_eq!(ti.value, "beta ");
418
419 ti.handle_key(key(KeyCode::Char('d')));
421 ti.handle_key(key(KeyCode::Char('d')));
422 assert_eq!(ti.value, "");
423 assert_eq!(ti.cursor, 0);
424 }
425
426 #[test]
427 fn test_vim_db_and_d0_and_d() {
428 let mut ti = TextInput::new("one two three");
429 ti.handle_key(key(KeyCode::Esc));
430 ti.handle_key(key(KeyCode::Char('0')));
431 ti.handle_key(key(KeyCode::Char('w'))); ti.handle_key(key(KeyCode::Char('w'))); ti.handle_key(key(KeyCode::Char('d')));
434 ti.handle_key(key(KeyCode::Char('b')));
435 assert_eq!(ti.value, "one three");
436 assert_eq!(ti.cursor, 4);
437
438 ti.handle_key(key(KeyCode::Char('D')));
439 assert_eq!(ti.value, "one ");
440
441 ti.handle_key(key(KeyCode::Char('d')));
442 ti.handle_key(key(KeyCode::Char('0')));
443 assert_eq!(ti.value, " ");
444 }
445}