1use crate::component::{Component, KeyResult};
2use ratatui::{
3 buffer::Buffer,
4 crossterm::event::{KeyCode, KeyEvent, KeyModifiers},
5 layout::{Position, Rect},
6 style::Color,
7 widgets::Widget,
8};
9use std::cell::Cell;
10use unicode_width::UnicodeWidthChar;
11
12const PAD_X: u16 = 1;
13const PAD_Y: u16 = 1;
14const BG: Color = Color::Rgb(40, 40, 40);
15const FG: Color = Color::White;
16
17fn char_width(ch: char) -> usize {
25 ch.width().unwrap_or(0)
26}
27
28fn display_width(s: &str) -> usize {
30 s.chars().map(char_width).sum()
31}
32
33fn normalize_line_breaks(s: &str) -> String {
40 let mut out = String::with_capacity(s.len());
41 let mut chars = s.chars().peekable();
42 while let Some(ch) = chars.next() {
43 match ch {
44 '\r' => {
45 if chars.peek() == Some(&'\n') {
47 chars.next();
48 }
49 out.push('\n');
50 }
51 '\x0b' | '\x0c' => out.push('\n'),
52 other => out.push(other),
53 }
54 }
55 out
56}
57
58pub struct TextInput {
60 buf: String,
61 cursor: usize,
63 wrap_width: Cell<u16>,
67}
68
69pub struct RenderResult {
71 pub cursor_position: Position,
73}
74
75impl Default for TextInput {
76 fn default() -> Self {
77 Self::new()
78 }
79}
80
81impl TextInput {
82 pub fn new() -> Self {
83 Self {
84 buf: String::new(),
85 cursor: 0,
86 wrap_width: Cell::new(0),
87 }
88 }
89
90 pub fn insert_char(&mut self, ch: char) {
93 self.buf.insert(self.cursor, ch);
94 self.cursor += ch.len_utf8();
95 }
96
97 pub fn insert_str(&mut self, s: &str) {
102 let s = normalize_line_breaks(s);
103 self.buf.insert_str(self.cursor, &s);
104 self.cursor += s.len();
105 }
106
107 pub fn backspace(&mut self) {
108 if self.cursor > 0 {
109 let prev = self.buf[..self.cursor]
111 .char_indices()
112 .next_back()
113 .map(|(i, _)| i)
114 .unwrap_or(0);
115 self.buf.drain(prev..self.cursor);
116 self.cursor = prev;
117 }
118 }
119
120 pub fn delete(&mut self) {
121 if self.cursor < self.buf.len() {
122 let next = self.cursor
123 + self.buf[self.cursor..]
124 .chars()
125 .next()
126 .expect("bug: cursor within bounds but no char found")
127 .len_utf8();
128 self.buf.drain(self.cursor..next);
129 }
130 }
131
132 pub fn move_left(&mut self) {
133 if self.cursor > 0 {
134 self.cursor = self.buf[..self.cursor]
135 .char_indices()
136 .next_back()
137 .map(|(i, _)| i)
138 .unwrap_or(0);
139 }
140 }
141
142 pub fn move_right(&mut self) {
143 if self.cursor < self.buf.len() {
144 self.cursor += self.buf[self.cursor..]
145 .chars()
146 .next()
147 .expect("bug: cursor within bounds but no char found")
148 .len_utf8();
149 }
150 }
151
152 pub fn move_home(&mut self) {
153 self.cursor = 0;
154 }
155
156 pub fn move_end(&mut self) {
157 self.cursor = self.buf.len();
158 }
159
160 pub fn move_up(&mut self) {
163 let wrap_w = self.wrap_width.get() as usize;
164 if wrap_w == 0 {
165 return;
166 }
167
168 let (row, col) = self.cursor_visual_pos(wrap_w);
169 if row == 0 {
170 self.cursor = 0;
171 } else {
172 self.set_cursor_to_visual_pos(row - 1, col, wrap_w);
173 }
174 }
175
176 pub fn move_down(&mut self) {
179 let wrap_w = self.wrap_width.get() as usize;
180 if wrap_w == 0 {
181 return;
182 }
183
184 let (row, col) = self.cursor_visual_pos(wrap_w);
185 let total_rows = self.visual_line_count(wrap_w);
186
187 if row >= total_rows - 1 {
188 self.cursor = self.buf.len();
189 } else {
190 self.set_cursor_to_visual_pos(row + 1, col, wrap_w);
191 }
192 }
193
194 fn cursor_visual_pos(&self, wrap_w: usize) -> (usize, usize) {
197 let lines = wrap_lines(&self.buf, wrap_w);
198 let buf_start = self.buf.as_ptr() as usize;
199
200 for (row_idx, line) in lines.iter().enumerate() {
201 let line_byte_start = line.as_ptr() as usize - buf_start;
202 let line_byte_end = line_byte_start + line.len();
203
204 if self.cursor >= line_byte_start && self.cursor <= line_byte_end {
205 let offset = self.cursor.saturating_sub(line_byte_start);
206 let col = display_width(&line[..offset.min(line.len())]);
207
208 let line_full = display_width(line) >= wrap_w;
212 if offset == line.len() && line_full {
213 continue;
214 }
215
216 return (row_idx, col);
217 }
218 }
219
220 if let Some(last) = lines.last() {
222 let last_full = display_width(last) >= wrap_w;
223 if last_full && self.cursor == self.buf.len() {
224 return (lines.len(), 0);
225 }
226 return (lines.len().saturating_sub(1), display_width(last));
227 }
228
229 (0, 0)
230 }
231
232 fn visual_line_count(&self, wrap_w: usize) -> usize {
236 let lines = wrap_lines(&self.buf, wrap_w);
237 let extra = lines
238 .last()
239 .map(|l| display_width(l) >= wrap_w && self.cursor == self.buf.len())
240 .unwrap_or(false);
241 lines.len() + extra as usize
242 }
243
244 fn set_cursor_to_visual_pos(&mut self, target_row: usize, target_col: usize, wrap_w: usize) {
247 let new_cursor = {
248 let lines = wrap_lines(&self.buf, wrap_w);
249 let buf_start = self.buf.as_ptr() as usize;
250
251 if target_row >= lines.len() {
252 self.buf.len()
253 } else {
254 let line = lines[target_row];
255 let line_byte_start = line.as_ptr() as usize - buf_start;
256
257 let mut byte_offset = line.len();
260 let mut acc = 0;
261 for (i, ch) in line.char_indices() {
262 if acc >= target_col {
263 byte_offset = i;
264 break;
265 }
266 acc += char_width(ch);
267 }
268
269 line_byte_start + byte_offset
270 }
271 };
272 self.cursor = new_cursor;
273 }
274
275 pub fn move_word_left(&mut self) {
277 let before = &self.buf[..self.cursor];
279 let trimmed = before.trim_end();
280 if trimmed.is_empty() {
281 self.cursor = 0;
282 return;
283 }
284 if let Some((i, _)) = trimmed
286 .char_indices()
287 .rev()
288 .find(|(_, c)| c.is_whitespace())
289 {
290 self.cursor = i + trimmed[i..]
292 .chars()
293 .next()
294 .expect("bug: whitespace char index valid but no char found")
295 .len_utf8();
296 } else {
297 self.cursor = 0;
298 }
299 }
300
301 pub fn move_word_right(&mut self) {
303 let after = &self.buf[self.cursor..];
304 let skip_word = after
306 .char_indices()
307 .find(|(_, c)| c.is_whitespace())
308 .map(|(i, _)| i)
309 .unwrap_or(after.len());
310 let rest = &after[skip_word..];
311 let skip_space = rest
312 .char_indices()
313 .find(|(_, c)| !c.is_whitespace())
314 .map(|(i, _)| i)
315 .unwrap_or(rest.len());
316 self.cursor += skip_word + skip_space;
317 }
318
319 pub fn delete_word_left(&mut self) {
321 let start = self.cursor;
322 self.move_word_left();
323 self.buf.drain(self.cursor..start);
324 }
325
326 pub fn insert_newline(&mut self) {
328 self.insert_char('\n');
329 }
330
331 pub fn handle_keystroke(&mut self, key: KeyEvent) -> KeyResult {
334 let mods = key.modifiers;
335 let ctrl = mods.contains(KeyModifiers::CONTROL);
336 let alt = mods.contains(KeyModifiers::ALT);
337
338 match key.code {
339 KeyCode::Left if alt => {
343 self.move_word_left();
344 KeyResult::Captured
345 }
346 KeyCode::Right if alt => {
347 self.move_word_right();
348 KeyResult::Captured
349 }
350 KeyCode::Char('b') if alt => {
351 self.move_word_left();
352 KeyResult::Captured
353 }
354 KeyCode::Char('f') if alt => {
355 self.move_word_right();
356 KeyResult::Captured
357 }
358
359 KeyCode::Char('a') if ctrl => {
361 self.move_home();
362 KeyResult::Captured
363 }
364 KeyCode::Char('e') if ctrl => {
365 self.move_end();
366 KeyResult::Captured
367 }
368
369 KeyCode::Char('c') if ctrl => {
371 if !self.is_empty() {
372 self.buf.clear();
373 self.cursor = 0;
374 KeyResult::Captured
375 } else {
376 KeyResult::NotCaptured
377 }
378 }
379
380 KeyCode::Char('j') if ctrl => {
384 self.insert_newline();
385 KeyResult::Captured
386 }
387
388 KeyCode::Char(_) if ctrl => KeyResult::NotCaptured,
390
391 KeyCode::Backspace if alt => {
393 self.delete_word_left();
394 KeyResult::Captured
395 }
396
397 KeyCode::Enter if alt => {
399 self.insert_newline();
400 KeyResult::Captured
401 }
402
403 KeyCode::Enter => KeyResult::NotCaptured,
405
406 KeyCode::Backspace => {
408 self.backspace();
409 KeyResult::Captured
410 }
411 KeyCode::Delete => {
412 self.delete();
413 KeyResult::Captured
414 }
415 KeyCode::Left => {
416 self.move_left();
417 KeyResult::Captured
418 }
419 KeyCode::Right => {
420 self.move_right();
421 KeyResult::Captured
422 }
423 KeyCode::Up => {
424 if self.cursor == 0 {
425 KeyResult::NotCaptured
426 } else {
427 self.move_up();
428 KeyResult::Captured
429 }
430 }
431 KeyCode::Down => {
432 self.move_down();
433 KeyResult::Captured
434 }
435 KeyCode::Home => {
436 self.move_home();
437 KeyResult::Captured
438 }
439 KeyCode::End => {
440 self.move_end();
441 KeyResult::Captured
442 }
443 KeyCode::Char(ch) => {
444 self.insert_char(ch);
445 KeyResult::Captured
446 }
447
448 _ => KeyResult::NotCaptured,
449 }
450 }
451
452 pub fn take_text(&mut self) -> String {
454 self.cursor = 0;
455 std::mem::take(&mut self.buf)
456 }
457
458 pub fn text(&self) -> &str {
459 &self.buf
460 }
461
462 pub fn set_text(&mut self, s: &str) {
463 self.buf = s.to_owned();
464 self.cursor = self.buf.len();
465 }
466
467 pub fn is_empty(&self) -> bool {
468 self.buf.trim().is_empty()
469 }
470
471 pub fn preferred_height(&self, outer_width: u16) -> u16 {
476 let inner_w = outer_width.saturating_sub(PAD_X * 2);
477 self.wrap_width.set(inner_w);
478 if inner_w == 0 {
479 return PAD_Y * 2 + 1;
480 }
481 let lines = wrap_lines(&self.buf, inner_w as usize);
482 let mut text_rows = lines.len().max(1) as u16;
483
484 if let Some(last) = lines.last()
487 && display_width(last) >= inner_w as usize
488 && self.cursor == self.buf.len()
489 {
490 text_rows += 1;
491 }
492
493 PAD_Y * 2 + text_rows
494 }
495
496 pub fn render(&self, area: Rect, buf: &mut Buffer) -> RenderResult {
500 for y in area.y..area.bottom() {
502 for x in area.x..area.right() {
503 buf[(x, y)].set_char(' ').set_bg(BG);
504 }
505 }
506
507 let inner = Rect::new(
508 area.x + PAD_X,
509 area.y + PAD_Y,
510 area.width.saturating_sub(PAD_X * 2),
511 area.height.saturating_sub(PAD_Y * 2),
512 );
513
514 self.wrap_width.set(inner.width);
515
516 if inner.width == 0 || inner.height == 0 {
517 return RenderResult {
518 cursor_position: Position::new(area.x + PAD_X, area.y + PAD_Y),
519 };
520 }
521
522 let lines = wrap_lines(&self.buf, inner.width as usize);
523
524 let mut cursor_row: u16 = 0;
527 let mut cursor_col: u16 = 0;
528 let mut found_cursor = false;
529 let buf_start = self.buf.as_ptr() as usize;
530
531 for (row_idx, line) in lines.iter().enumerate() {
532 let line_byte_start = line.as_ptr() as usize - buf_start;
533 let line_byte_end = line_byte_start + line.len();
534 if !found_cursor && self.cursor >= line_byte_start && self.cursor <= line_byte_end {
535 let offset = self.cursor.saturating_sub(line_byte_start);
536 let col = display_width(&line[..offset.min(line.len())]);
537
538 let line_full = display_width(line) >= inner.width as usize;
542 if offset == line.len() && line_full {
543 continue;
546 }
547
548 cursor_row = row_idx as u16;
549 cursor_col = col as u16;
550 found_cursor = true;
551 }
552 }
553
554 if !found_cursor && let Some(last) = lines.last() {
558 let last_full = display_width(last) >= inner.width as usize;
559 if last_full && self.cursor == self.buf.len() {
560 cursor_row = lines.len() as u16;
561 cursor_col = 0;
562 } else {
563 cursor_row = lines.len().saturating_sub(1) as u16;
564 cursor_col = display_width(last) as u16;
565 }
566 }
567
568 for (row_idx, line) in lines.iter().enumerate() {
571 let y = inner.y + row_idx as u16;
572 if y >= inner.bottom() {
573 break;
574 }
575 let mut x = inner.x;
576 for ch in line.chars() {
577 let w = char_width(ch) as u16;
578 if w == 0 {
579 continue;
580 }
581 if x + w > inner.right() {
582 break;
583 }
584 buf[(x, y)].set_char(ch).set_fg(FG).set_bg(BG);
585 x += w;
586 }
587 }
588
589 RenderResult {
590 cursor_position: Position::new(
591 inner.x + cursor_col,
592 (inner.y + cursor_row).min(inner.bottom().saturating_sub(1)),
593 ),
594 }
595 }
596}
597
598fn wrap_lines<'a>(text: &'a str, max_width: usize) -> Vec<&'a str> {
602 if text.is_empty() {
603 return vec![&text[..0]];
606 }
607 if max_width == 0 {
608 return vec![text];
609 }
610
611 let mut lines: Vec<&'a str> = Vec::new();
612
613 for segment in text.split('\n') {
615 if segment.is_empty() {
618 let offset = segment.as_ptr() as usize - text.as_ptr() as usize;
620 lines.push(&text[offset..offset]);
621 continue;
622 }
623
624 let mut remaining = segment;
625 while !remaining.is_empty() {
626 if display_width(remaining) <= max_width {
627 lines.push(remaining);
628 break;
629 }
630
631 let mut break_byte = remaining.len();
634 let mut acc = 0;
635 for (i, ch) in remaining.char_indices() {
636 let w = char_width(ch);
637 if acc + w > max_width {
638 break_byte = i;
639 break;
640 }
641 acc += w;
642 }
643 if break_byte == 0 {
645 break_byte = remaining
646 .chars()
647 .next()
648 .expect("bug: remaining is non-empty")
649 .len_utf8();
650 }
651
652 let seg = &remaining[..break_byte];
654 if let Some(space_pos) = seg.rfind(' ') {
655 lines.push(&remaining[..space_pos]);
656 remaining = &remaining[space_pos + 1..];
658 } else {
659 lines.push(seg);
661 remaining = &remaining[break_byte..];
662 }
663 }
664 }
665
666 lines
667}
668
669impl Component for TextInput {
670 fn handle_keystroke(&mut self, key: KeyEvent) -> KeyResult {
671 TextInput::handle_keystroke(self, key)
672 }
673}
674
675pub struct TextInputWidget<'a> {
678 input: &'a TextInput,
679 cursor_out: &'a mut Option<Position>,
680}
681
682impl<'a> TextInputWidget<'a> {
683 pub fn new(input: &'a TextInput, cursor_out: &'a mut Option<Position>) -> Self {
684 Self { input, cursor_out }
685 }
686}
687
688impl<'a> Widget for TextInputWidget<'a> {
689 fn render(self, area: Rect, buf: &mut Buffer) {
690 let result = self.input.render(area, buf);
691 *self.cursor_out = Some(result.cursor_position);
692 }
693}
694
695#[cfg(test)]
696mod tests {
697 use super::*;
698 use unicode_width::UnicodeWidthStr;
699
700 fn render(input: &TextInput, outer_width: u16) -> (Buffer, Rect, Position) {
703 let height = input.preferred_height(outer_width);
704 let area = Rect::new(0, 0, outer_width, height);
705 let mut buf = Buffer::empty(area);
706 let result = input.render(area, &mut buf);
707 let inner = Rect::new(
708 area.x + PAD_X,
709 area.y + PAD_Y,
710 area.width - PAD_X * 2,
711 area.height - PAD_Y * 2,
712 );
713 (buf, inner, result.cursor_position)
714 }
715
716 fn row_text(buf: &Buffer, inner: Rect, row: u16) -> String {
718 let y = inner.y + row;
719 let s: String = (inner.x..inner.right())
720 .map(|x| buf[(x, y)].symbol().to_owned())
721 .collect();
722 s.trim_end().to_owned()
723 }
724
725 #[test]
730 fn normalize_line_breaks_handles_office_and_windows_endings() {
731 assert_eq!(normalize_line_breaks("a\rb"), "a\nb");
732 assert_eq!(normalize_line_breaks("a\r\nb"), "a\nb");
733 assert_eq!(normalize_line_breaks("a\x0bb"), "a\nb");
734 assert_eq!(normalize_line_breaks("a\x0cb"), "a\nb");
735 assert_eq!(normalize_line_breaks("a\nb"), "a\nb");
737 assert_eq!(normalize_line_breaks("a\r\r\nb"), "a\n\nb");
738 assert_eq!(normalize_line_breaks("a\n\rb"), "a\n\nb");
739 assert_eq!(normalize_line_breaks("a\r"), "a\n");
741 }
742
743 #[test]
744 fn insert_str_normalizes_office_line_breaks() {
745 let mut input = TextInput::new();
746 input.insert_str("Slide title\rFirst point\x0bSecond point\r\nThird point\x0c");
747 assert_eq!(
748 input.text(),
749 "Slide title\nFirst point\nSecond point\nThird point\n"
750 );
751 assert_eq!(input.cursor, input.buf.len());
752 }
753
754 #[test]
758 fn cursor_sits_at_end_of_pasted_powerpoint_text() {
759 let mut input = TextInput::new();
760 input.insert_str("Slide title\rFirst point\x0bSecond point");
761
762 let (buf, inner, cursor) = render(&input, 40);
763 assert_eq!(row_text(&buf, inner, 0), "Slide title");
764 assert_eq!(row_text(&buf, inner, 1), "First point");
765 assert_eq!(row_text(&buf, inner, 2), "Second point");
766 assert_eq!(
767 cursor,
768 Position::new(inner.x + "Second point".width() as u16, inner.y + 2)
769 );
770 }
771
772 #[test]
776 fn cursor_column_matches_drawn_glyphs_with_control_chars() {
777 for ctrl in ['\t', '\x7f', '\x1b', '\x01'] {
778 let mut input = TextInput::new();
779 input.buf = format!("ab{ctrl}cd");
781 input.cursor = input.buf.len();
782
783 let (buf, inner, cursor) = render(&input, 40);
784 let drawn = row_text(&buf, inner, 0);
785 assert_eq!(
786 cursor.x,
787 inner.x + drawn.width() as u16,
788 "cursor desynced from drawn text {drawn:?} for control char {ctrl:?}"
789 );
790 }
791 }
792
793 #[test]
796 fn cursor_column_matches_mid_line_with_control_chars() {
797 let mut input = TextInput::new();
798 input.buf = "ab\x7fcd".to_owned();
799 input.cursor = input.buf.len();
800 input.move_left(); input.move_left(); let (_, inner, cursor) = render(&input, 40);
804 assert_eq!(cursor.x, inner.x + 2, "cursor should sit before 'c'");
805 }
806}