1#![forbid(unsafe_code)]
2
3use std::collections::VecDeque;
9
10use ftui_core::event::{Event, ImeEvent, ImePhase, KeyCode, KeyEvent, KeyEventKind, Modifiers};
11use ftui_core::geometry::Rect;
12use ftui_render::cell::{Cell, CellContent};
13use ftui_render::frame::Frame;
14use ftui_style::Style;
15use ftui_text::grapheme_width;
16use unicode_segmentation::UnicodeSegmentation;
17
18use crate::undo_support::{TextEditOperation, TextInputUndoExt, UndoSupport, UndoWidgetId};
19use crate::{Widget, clear_text_area};
20
21#[derive(Debug, Clone, Default)]
23pub struct TextInput {
24 undo_id: UndoWidgetId,
26 value: String,
28 cursor: usize,
30 scroll_cells: std::cell::Cell<usize>,
32 selection_anchor: Option<usize>,
34 ime_composition: Option<String>,
36 placeholder: String,
38 mask_char: Option<char>,
40 max_length: Option<usize>,
42 style: Style,
44 cursor_style: Style,
46 placeholder_style: Style,
48 selection_style: Style,
50 focused: bool,
52 history: Option<InputHistory>,
60}
61
62#[derive(Debug, Clone)]
80pub struct InputHistory {
81 entries: VecDeque<String>,
83 cap: usize,
85 cursor: Option<usize>,
87 draft: Option<String>,
90}
91
92impl InputHistory {
93 #[must_use]
96 pub fn new(capacity: usize) -> Self {
97 Self {
98 entries: VecDeque::new(),
99 cap: capacity.max(1),
100 cursor: None,
101 draft: None,
102 }
103 }
104
105 pub fn push(&mut self, value: String) {
109 if !value.is_empty() && self.entries.back() != Some(&value) {
110 self.entries.push_back(value);
111 while self.entries.len() > self.cap {
112 self.entries.pop_front();
113 }
114 }
115 self.cursor = None;
116 self.draft = None;
117 }
118
119 pub fn recall_older(&mut self, current: &str) -> Option<String> {
123 if self.entries.is_empty() {
124 return None;
125 }
126 match self.cursor {
127 None => {
128 self.draft = Some(current.to_string());
129 self.cursor = Some(self.entries.len() - 1);
130 }
131 Some(0) => {}
132 Some(i) => self.cursor = Some(i - 1),
133 }
134 self.cursor.and_then(|i| self.entries.get(i)).cloned()
135 }
136
137 pub fn recall_newer(&mut self) -> Option<String> {
140 match self.cursor {
141 None => None,
142 Some(i) if i + 1 < self.entries.len() => {
143 self.cursor = Some(i + 1);
144 self.entries.get(i + 1).cloned()
145 }
146 Some(_) => {
147 self.cursor = None;
148 self.draft.take()
149 }
150 }
151 }
152
153 fn note_edit(&mut self) {
156 self.cursor = None;
157 self.draft = None;
158 }
159
160 pub fn entries(&self) -> impl Iterator<Item = &str> {
162 self.entries.iter().map(String::as_str)
163 }
164
165 #[must_use]
167 pub fn len(&self) -> usize {
168 self.entries.len()
169 }
170
171 #[must_use]
173 pub fn is_empty(&self) -> bool {
174 self.entries.is_empty()
175 }
176
177 pub fn clear(&mut self) {
179 self.entries.clear();
180 self.cursor = None;
181 self.draft = None;
182 }
183
184 #[must_use]
186 pub fn capacity(&self) -> usize {
187 self.cap
188 }
189}
190
191impl TextInput {
192 pub fn new() -> Self {
194 Self::default()
195 }
196
197 #[must_use]
201 pub fn with_value(mut self, value: impl Into<String>) -> Self {
202 self.value = value.into();
203 self.cursor = self.value.graphemes(true).count();
204 self.selection_anchor = None;
205 self
206 }
207
208 #[must_use]
210 pub fn with_placeholder(mut self, placeholder: impl Into<String>) -> Self {
211 self.placeholder = placeholder.into();
212 self
213 }
214
215 #[must_use]
217 pub fn with_mask(mut self, mask: char) -> Self {
218 self.mask_char = Some(mask);
219 self
220 }
221
222 #[must_use]
224 pub fn with_max_length(mut self, max: usize) -> Self {
225 self.max_length = Some(max);
226 self
227 }
228
229 #[must_use]
239 pub fn with_history(mut self, capacity: usize) -> Self {
240 self.history = Some(InputHistory::new(capacity));
241 self
242 }
243
244 #[must_use]
246 pub fn with_style(mut self, style: Style) -> Self {
247 self.style = style;
248 self
249 }
250
251 #[must_use]
253 pub fn with_cursor_style(mut self, style: Style) -> Self {
254 self.cursor_style = style;
255 self
256 }
257
258 #[must_use]
260 pub fn with_placeholder_style(mut self, style: Style) -> Self {
261 self.placeholder_style = style;
262 self
263 }
264
265 #[must_use]
267 pub fn with_selection_style(mut self, style: Style) -> Self {
268 self.selection_style = style;
269 self
270 }
271
272 #[must_use]
274 pub fn with_focused(mut self, focused: bool) -> Self {
275 self.focused = focused;
276 self
277 }
278
279 pub fn value(&self) -> &str {
283 &self.value
284 }
285
286 pub fn set_value(&mut self, value: impl Into<String>) {
288 self.value = value.into();
289 let max = self.grapheme_count();
290 self.cursor = self.cursor.min(max);
291 self.scroll_cells.set(0);
292 self.selection_anchor = None;
293 }
294
295 pub fn clear(&mut self) {
297 self.value.clear();
298 self.cursor = 0;
299 self.scroll_cells.set(0);
300 self.selection_anchor = None;
301 }
302
303 #[inline]
305 pub fn cursor(&self) -> usize {
306 self.cursor
307 }
308
309 #[inline]
311 pub fn focused(&self) -> bool {
312 self.focused
313 }
314
315 pub fn set_focused(&mut self, focused: bool) {
317 self.focused = focused;
318 }
319
320 pub fn push_history(&mut self) {
327 let value = self.value.clone();
328 if let Some(history) = self.history.as_mut() {
329 history.push(value);
330 }
331 }
332
333 pub fn history(&self) -> impl Iterator<Item = &str> {
336 self.history.iter().flat_map(InputHistory::entries)
337 }
338
339 pub fn clear_history(&mut self) {
341 if let Some(history) = self.history.as_mut() {
342 history.clear();
343 }
344 }
345
346 #[must_use]
348 pub fn history_capacity(&self) -> Option<usize> {
349 self.history.as_ref().map(InputHistory::capacity)
350 }
351
352 fn recall_history_older(&mut self) -> bool {
356 let current = self.value.clone();
357 match self.history.as_mut().and_then(|h| h.recall_older(¤t)) {
358 Some(recalled) if recalled != current => {
359 self.set_value_from_recall(recalled);
360 true
361 }
362 _ => false,
363 }
364 }
365
366 fn recall_history_newer(&mut self) -> bool {
369 let current = self.value.clone();
370 match self.history.as_mut().and_then(InputHistory::recall_newer) {
371 Some(recalled) if recalled != current => {
372 self.set_value_from_recall(recalled);
373 true
374 }
375 _ => false,
376 }
377 }
378
379 fn set_value_from_recall(&mut self, value: String) {
382 self.value = value;
383 self.cursor = self.grapheme_count();
384 self.scroll_cells.set(0);
385 self.selection_anchor = None;
386 }
387
388 pub fn cursor_position(&self, area: Rect) -> (u16, u16) {
393 let cursor_visual = self.cursor_visual_pos();
394 let effective_scroll = self.effective_scroll(area.width as usize);
395 let rel_x = cursor_visual.saturating_sub(effective_scroll);
396 let x = area
397 .x
398 .saturating_add(rel_x as u16)
399 .min(area.right().saturating_sub(1));
400 (x, area.y)
401 }
402
403 #[must_use]
405 pub fn selected_text(&self) -> Option<&str> {
406 let anchor = self.selection_anchor?;
407 let (start, end) = self.selection_range(anchor);
408 let byte_start = self.grapheme_byte_offset(start);
409 let byte_end = self.grapheme_byte_offset(end);
410 Some(&self.value[byte_start..byte_end])
411 }
412
413 pub fn ime_start_composition(&mut self) {
415 if self.ime_composition.is_none() {
416 self.delete_selection();
417 }
418 self.ime_composition = Some(String::new());
419 #[cfg(feature = "tracing")]
420 self.trace_edit("ime_start");
421 }
422
423 pub fn ime_update_composition(&mut self, preedit: impl Into<String>) {
427 if self.ime_composition.is_none() {
428 self.delete_selection();
429 }
430 self.ime_composition = Some(preedit.into());
431 #[cfg(feature = "tracing")]
432 self.trace_edit("ime_update");
433 }
434
435 pub fn ime_commit_composition(&mut self) -> bool {
439 let Some(preedit) = self.ime_composition.take() else {
440 return false;
441 };
442
443 if !preedit.is_empty() {
444 self.insert_text(&preedit);
445 }
446
447 #[cfg(feature = "tracing")]
448 self.trace_edit("ime_commit");
449
450 true
451 }
452
453 pub fn ime_cancel_composition(&mut self) -> bool {
457 let cancelled = self.ime_composition.take().is_some();
458 #[cfg(feature = "tracing")]
459 if cancelled {
460 self.trace_edit("ime_cancel");
461 }
462 cancelled
463 }
464
465 #[must_use]
467 pub fn ime_composition(&self) -> Option<&str> {
468 self.ime_composition.as_deref()
469 }
470
471 pub fn handle_event(&mut self, event: &Event) -> bool {
477 let changed = match event {
478 Event::Key(key)
479 if key.kind == KeyEventKind::Press || key.kind == KeyEventKind::Repeat =>
480 {
481 self.handle_key(key)
482 }
483 Event::Ime(ime) => self.handle_ime_event(ime),
484 Event::Paste(paste) => {
485 let had_selection = self.selection_anchor.is_some();
486
487 if had_selection {
490 let clean_text = Self::sanitize_input_text(&paste.text);
491 if let Some(max) = self.max_length {
492 let selection_len = if let Some(anchor) = self.selection_anchor {
493 let (start, end) = self.selection_range(anchor);
494 end.saturating_sub(start)
495 } else {
496 0
497 };
498 let available =
499 max.saturating_sub(self.grapheme_count().saturating_sub(selection_len));
500 if clean_text.graphemes(true).count() > available {
501 return false;
502 }
503 }
504 }
505
506 self.delete_selection();
507 self.insert_text(&paste.text);
508 true
509 }
510 _ => false,
511 };
512
513 #[cfg(feature = "tracing")]
514 if changed {
515 self.trace_edit(Self::event_operation_name(event));
516 }
517
518 changed
519 }
520
521 fn handle_ime_event(&mut self, ime: &ImeEvent) -> bool {
522 match ime.phase {
523 ImePhase::Start => {
524 self.ime_start_composition();
525 true
526 }
527 ImePhase::Update => {
528 self.ime_update_composition(&ime.text);
529 true
530 }
531 ImePhase::Commit => {
532 if self.ime_composition.is_some() {
533 self.ime_update_composition(&ime.text);
534 self.ime_commit_composition()
535 } else if !ime.text.is_empty() {
536 self.insert_text(&ime.text);
537 true
538 } else {
539 false
540 }
541 }
542 ImePhase::Cancel => self.ime_cancel_composition(),
543 }
544 }
545
546 fn handle_key(&mut self, key: &KeyEvent) -> bool {
547 let ctrl = key.modifiers.contains(Modifiers::CTRL);
548 let shift = key.modifiers.contains(Modifiers::SHIFT);
549
550 if self.history.is_some() && !ctrl && !shift {
555 match key.code {
556 KeyCode::Up => return self.recall_history_older(),
557 KeyCode::Down => return self.recall_history_newer(),
558 KeyCode::Enter => {
559 self.push_history();
562 return false;
563 }
564 _ => {}
565 }
566 }
567
568 let value_before = if self.history.is_some() {
571 Some(self.value.clone())
572 } else {
573 None
574 };
575
576 let cmd = key.modifiers.contains(Modifiers::SUPER);
580
581 let changed = match key.code {
582 KeyCode::Char(c) if !ctrl && !cmd => {
583 self.insert_char(c);
584 true
585 }
586 KeyCode::Char('a') if ctrl => {
588 self.select_all();
589 true
590 }
591 KeyCode::Char('w') if ctrl => {
593 self.delete_word_back();
594 true
595 }
596 KeyCode::Backspace => {
597 if self.selection_anchor.is_some() {
598 self.delete_selection();
599 } else if ctrl {
600 self.delete_word_back();
601 } else {
602 self.delete_char_back();
603 }
604 true
605 }
606 KeyCode::Delete => {
607 if self.selection_anchor.is_some() {
608 self.delete_selection();
609 } else if ctrl {
610 self.delete_word_forward();
611 } else {
612 self.delete_char_forward();
613 }
614 true
615 }
616 KeyCode::Left => {
617 if ctrl {
618 self.move_cursor_word_left(shift);
619 } else if shift {
620 self.move_cursor_left_select();
621 } else {
622 self.move_cursor_left();
623 }
624 true
625 }
626 KeyCode::Right => {
627 if ctrl {
628 self.move_cursor_word_right(shift);
629 } else if shift {
630 self.move_cursor_right_select();
631 } else {
632 self.move_cursor_right();
633 }
634 true
635 }
636 KeyCode::Home => {
637 if shift {
638 self.ensure_selection_anchor();
639 } else {
640 self.selection_anchor = None;
641 }
642 self.cursor = 0;
643 self.scroll_cells.set(0);
644 true
645 }
646 KeyCode::End => {
647 if shift {
648 self.ensure_selection_anchor();
649 } else {
650 self.selection_anchor = None;
651 }
652 self.cursor = self.grapheme_count();
653 true
654 }
655 _ => false,
656 };
657
658 if let Some(before) = value_before
661 && self.value != before
662 && let Some(history) = self.history.as_mut()
663 {
664 history.note_edit();
665 }
666
667 changed
668 }
669
670 #[cfg(feature = "tracing")]
671 fn trace_edit(&self, operation: &'static str) {
672 let _span = tracing::debug_span!(
673 "input.edit",
674 operation,
675 cursor_position = self.cursor,
676 grapheme_count = self.grapheme_count(),
677 has_selection = self.selection_anchor.is_some()
678 )
679 .entered();
680 }
681
682 #[cfg(feature = "tracing")]
683 fn event_operation_name(event: &Event) -> &'static str {
684 match event {
685 Event::Key(key) => Self::key_operation_name(key),
686 Event::Paste(_) => "paste",
687 Event::Ime(ime) => match ime.phase {
688 ImePhase::Start => "ime_start",
689 ImePhase::Update => "ime_update",
690 ImePhase::Commit => "ime_commit",
691 ImePhase::Cancel => "ime_cancel",
692 },
693 Event::Resize { .. } => "resize",
694 Event::Focus(_) => "focus",
695 Event::Mouse(_) => "mouse",
696 Event::Clipboard(_) => "clipboard",
697 Event::TerminalResponse(_) => "terminal_response",
698 Event::Tick => "tick",
699 }
700 }
701
702 #[cfg(feature = "tracing")]
703 fn key_operation_name(key: &KeyEvent) -> &'static str {
704 let ctrl = key.modifiers.contains(Modifiers::CTRL);
705 let shift = key.modifiers.contains(Modifiers::SHIFT);
706
707 match key.code {
708 KeyCode::Char(_) if !ctrl => "insert_char",
709 KeyCode::Char('a') if ctrl => "select_all",
710 KeyCode::Char('w') if ctrl => "delete_word_back",
711 KeyCode::Backspace if ctrl => "delete_word_back",
712 KeyCode::Backspace => "delete_back",
713 KeyCode::Delete if ctrl => "delete_word_forward",
714 KeyCode::Delete => "delete_forward",
715 KeyCode::Left if ctrl && shift => "move_word_left_select",
716 KeyCode::Left if ctrl => "move_word_left",
717 KeyCode::Left if shift => "move_left_select",
718 KeyCode::Left => "move_left",
719 KeyCode::Right if ctrl && shift => "move_word_right_select",
720 KeyCode::Right if ctrl => "move_word_right",
721 KeyCode::Right if shift => "move_right_select",
722 KeyCode::Right => "move_right",
723 KeyCode::Home if shift => "move_home_select",
724 KeyCode::Home => "move_home",
725 KeyCode::End if shift => "move_end_select",
726 KeyCode::End => "move_end",
727 _ => "key_other",
728 }
729 }
730
731 fn sanitize_input_text(text: &str) -> String {
734 text.chars()
736 .map(|c| {
737 if c == '\n' || c == '\r' || c == '\t' {
738 ' '
739 } else {
740 c
741 }
742 })
743 .filter(|c| !c.is_control())
744 .collect()
745 }
746
747 pub fn insert_text(&mut self, text: &str) {
755 self.delete_selection();
756
757 let clean_text = Self::sanitize_input_text(text);
758
759 if clean_text.is_empty() {
760 return;
761 }
762
763 let current_count = self.grapheme_count();
764 let avail = if let Some(max) = self.max_length {
765 if current_count >= max {
766 1
768 } else {
769 max - current_count
770 }
771 } else {
772 usize::MAX
773 };
774
775 let new_graphemes = clean_text.graphemes(true).count();
777 let to_insert = if new_graphemes > avail {
778 let end_byte = clean_text
780 .grapheme_indices(true)
781 .map(|(i, _)| i)
782 .nth(avail)
783 .unwrap_or(clean_text.len());
784 &clean_text[..end_byte]
785 } else {
786 clean_text.as_str()
787 };
788
789 if to_insert.is_empty() {
790 return;
791 }
792
793 let byte_offset = self.grapheme_byte_offset(self.cursor);
794 self.value.insert_str(byte_offset, to_insert);
795
796 let new_total = self.grapheme_count();
798 if let Some(max) = self.max_length
799 && new_total > max
800 {
801 self.value.drain(byte_offset..byte_offset + to_insert.len());
803 return;
804 }
805
806 self.cursor = self
807 .value
808 .grapheme_indices(true)
809 .take_while(|(i, _)| *i < byte_offset + to_insert.len())
810 .count();
811 }
812
813 fn insert_char(&mut self, c: char) {
814 if c.is_control() {
816 return;
817 }
818
819 self.delete_selection();
820
821 let byte_offset = self.grapheme_byte_offset(self.cursor);
822 self.value.insert(byte_offset, c);
823
824 let new_count = self.grapheme_count();
825
826 if let Some(max) = self.max_length
828 && new_count > max
829 {
830 let char_len = c.len_utf8();
832 self.value.drain(byte_offset..byte_offset + char_len);
833 return;
834 }
835
836 let char_len = c.len_utf8();
837 self.cursor = self
838 .value
839 .grapheme_indices(true)
840 .take_while(|(i, _)| *i < byte_offset + char_len)
841 .count();
842 }
843
844 fn delete_char_back(&mut self) {
845 if self.cursor > 0 {
846 let byte_start = self.grapheme_byte_offset(self.cursor - 1);
847 let byte_end = self.grapheme_byte_offset(self.cursor);
848 self.value.drain(byte_start..byte_end);
849 self.cursor -= 1;
850 let gc = self.grapheme_count();
851 if self.cursor > gc {
852 self.cursor = gc;
853 }
854 }
855 }
856
857 fn delete_char_forward(&mut self) {
858 let count = self.grapheme_count();
859 if self.cursor < count {
860 let byte_start = self.grapheme_byte_offset(self.cursor);
861 let byte_end = self.grapheme_byte_offset(self.cursor + 1);
862 self.value.drain(byte_start..byte_end);
863 let gc = self.grapheme_count();
864 if self.cursor > gc {
865 self.cursor = gc;
866 }
867 }
868 }
869
870 fn delete_word_back(&mut self) {
871 if self.cursor == 0 {
872 return;
873 }
874
875 let old_cursor = self.cursor;
876 self.move_cursor_word_left(false);
878 let new_cursor = self.cursor;
879
880 if new_cursor < old_cursor {
881 let byte_start = self.grapheme_byte_offset(new_cursor);
882 let byte_end = self.grapheme_byte_offset(old_cursor);
883 self.value.drain(byte_start..byte_end);
884 self.cursor = new_cursor;
885 let gc = self.grapheme_count();
886 if self.cursor > gc {
887 self.cursor = gc;
888 }
889 }
890 }
891
892 fn delete_word_forward(&mut self) {
893 let old_cursor = self.cursor;
894 self.move_cursor_word_right(false);
896 let new_cursor = self.cursor;
897 self.cursor = old_cursor;
899
900 if new_cursor > old_cursor {
901 let byte_start = self.grapheme_byte_offset(old_cursor);
902 let byte_end = self.grapheme_byte_offset(new_cursor);
903 self.value.drain(byte_start..byte_end);
904 let gc = self.grapheme_count();
905 if self.cursor > gc {
906 self.cursor = gc;
907 }
908 }
909 }
910
911 pub fn select_all(&mut self) {
915 self.selection_anchor = Some(0);
916 self.cursor = self.grapheme_count();
917 }
918
919 fn delete_selection(&mut self) {
921 if let Some(anchor) = self.selection_anchor.take() {
922 let (start, end) = self.selection_range(anchor);
923 let byte_start = self.grapheme_byte_offset(start);
924 let byte_end = self.grapheme_byte_offset(end);
925 self.value.drain(byte_start..byte_end);
926 self.cursor = start;
927 let gc = self.grapheme_count();
928 if self.cursor > gc {
929 self.cursor = gc;
930 }
931 }
932 }
933
934 fn ensure_selection_anchor(&mut self) {
935 if self.selection_anchor.is_none() {
936 self.selection_anchor = Some(self.cursor);
937 }
938 }
939
940 fn selection_range(&self, anchor: usize) -> (usize, usize) {
941 if anchor <= self.cursor {
942 (anchor, self.cursor)
943 } else {
944 (self.cursor, anchor)
945 }
946 }
947
948 fn is_in_selection(&self, grapheme_idx: usize) -> bool {
949 if let Some(anchor) = self.selection_anchor {
950 let (start, end) = self.selection_range(anchor);
951 grapheme_idx >= start && grapheme_idx < end
952 } else {
953 false
954 }
955 }
956
957 fn move_cursor_left(&mut self) {
960 if let Some(anchor) = self.selection_anchor.take() {
961 self.cursor = self.cursor.min(anchor);
962 } else if self.cursor > 0 {
963 self.cursor -= 1;
964 }
965 }
966
967 fn move_cursor_right(&mut self) {
968 if let Some(anchor) = self.selection_anchor.take() {
969 self.cursor = self.cursor.max(anchor);
970 } else if self.cursor < self.grapheme_count() {
971 self.cursor += 1;
972 }
973 }
974
975 fn move_cursor_left_select(&mut self) {
976 self.ensure_selection_anchor();
977 if self.cursor > 0 {
978 self.cursor -= 1;
979 }
980 }
981
982 fn move_cursor_right_select(&mut self) {
983 self.ensure_selection_anchor();
984 if self.cursor < self.grapheme_count() {
985 self.cursor += 1;
986 }
987 }
988
989 fn get_grapheme_class(g: &str) -> u8 {
990 if g.chars().all(char::is_whitespace) {
991 0
992 } else if g.chars().any(char::is_alphanumeric) {
993 1
994 } else {
995 2
996 }
997 }
998
999 fn move_cursor_word_left(&mut self, select: bool) {
1000 if select {
1001 self.ensure_selection_anchor();
1002 } else {
1003 self.selection_anchor = None;
1004 }
1005
1006 if self.cursor == 0 {
1007 return;
1008 }
1009
1010 let byte_offset = self.grapheme_byte_offset(self.cursor);
1011 let before_cursor = &self.value[..byte_offset];
1012 let mut pos = self.cursor;
1013
1014 let mut iter = before_cursor.graphemes(true).rev();
1015
1016 while let Some(g) = iter.next() {
1017 if Self::get_grapheme_class(g) == 0 {
1018 pos = pos.saturating_sub(1);
1019 } else {
1020 pos = pos.saturating_sub(1);
1021 let target = Self::get_grapheme_class(g);
1022 for g_next in iter {
1023 if Self::get_grapheme_class(g_next) == target {
1024 pos = pos.saturating_sub(1);
1025 } else {
1026 break;
1027 }
1028 }
1029 break;
1030 }
1031 }
1032
1033 self.cursor = pos;
1034 }
1035
1036 fn move_cursor_word_right(&mut self, select: bool) {
1037 if select {
1038 self.ensure_selection_anchor();
1039 } else {
1040 self.selection_anchor = None;
1041 }
1042
1043 let mut iter = self.value.graphemes(true).peekable();
1044 for _ in 0..self.cursor {
1045 iter.next();
1046 }
1047
1048 let mut pos = self.cursor;
1049
1050 if let Some(&g) = iter.peek() {
1051 let start_class = Self::get_grapheme_class(g);
1052 if start_class != 0 {
1053 while let Some(&next_g) = iter.peek() {
1054 if Self::get_grapheme_class(next_g) == start_class {
1055 iter.next();
1056 pos += 1;
1057 } else {
1058 break;
1059 }
1060 }
1061 }
1062 }
1063
1064 while let Some(&g) = iter.peek() {
1065 if Self::get_grapheme_class(g) == 0 {
1066 iter.next();
1067 pos += 1;
1068 } else {
1069 break;
1070 }
1071 }
1072
1073 self.cursor = pos;
1074 }
1075
1076 fn grapheme_count(&self) -> usize {
1079 self.value.graphemes(true).count()
1080 }
1081
1082 fn grapheme_byte_offset(&self, grapheme_idx: usize) -> usize {
1083 self.value
1084 .grapheme_indices(true)
1085 .nth(grapheme_idx)
1086 .map(|(i, _)| i)
1087 .unwrap_or(self.value.len())
1088 }
1089
1090 fn grapheme_width(&self, g: &str) -> usize {
1091 if let Some(mask) = self.mask_char {
1092 let mut buf = [0u8; 4];
1093 let mask_str = mask.encode_utf8(&mut buf);
1094 grapheme_width(mask_str)
1095 } else {
1096 grapheme_width(g)
1097 }
1098 }
1099
1100 fn prev_grapheme_width(&self) -> usize {
1101 if self.cursor == 0 {
1102 return 0;
1103 }
1104 self.value
1105 .graphemes(true)
1106 .nth(self.cursor - 1)
1107 .map(|g| self.grapheme_width(g))
1108 .unwrap_or(0)
1109 }
1110
1111 fn cursor_visual_pos(&self) -> usize {
1112 let mut pos = 0;
1113 if !self.value.is_empty() {
1114 pos += self
1117 .value
1118 .graphemes(true)
1119 .take(self.cursor)
1120 .map(|g| self.grapheme_width(g))
1121 .sum::<usize>();
1122 }
1123 if let Some(ime) = &self.ime_composition {
1124 pos += ime
1125 .graphemes(true)
1126 .map(|g| self.grapheme_width(g))
1127 .sum::<usize>();
1128 }
1129 pos
1130 }
1131
1132 fn effective_scroll(&self, viewport_width: usize) -> usize {
1133 let cursor_visual = self.cursor_visual_pos();
1134 let mut scroll = self.scroll_cells.get();
1135 if cursor_visual < scroll {
1136 scroll = cursor_visual;
1137 }
1138 if cursor_visual >= scroll + viewport_width {
1139 let candidate_scroll = cursor_visual - viewport_width + 1;
1140 let prev_width = self.prev_grapheme_width();
1143 let max_scroll_for_prev = cursor_visual.saturating_sub(prev_width);
1144
1145 if viewport_width > prev_width {
1148 scroll = candidate_scroll.min(max_scroll_for_prev);
1149 } else {
1150 scroll = candidate_scroll;
1151 }
1152 }
1153
1154 scroll = self.snap_scroll_to_grapheme_boundary(scroll, viewport_width);
1156
1157 self.scroll_cells.set(scroll);
1158 scroll
1159 }
1160
1161 fn snap_scroll_to_grapheme_boundary(&self, scroll: usize, viewport_width: usize) -> usize {
1162 let mut pos = 0;
1163 let cursor_visual = self.cursor_visual_pos();
1164
1165 for g in self.value.graphemes(true) {
1166 let w = self.grapheme_width(g);
1167 let next_pos = pos + w;
1168
1169 if pos < scroll && scroll < next_pos {
1171 if cursor_visual <= pos + viewport_width {
1175 return pos;
1176 } else {
1177 return next_pos;
1179 }
1180 }
1181
1182 if next_pos > scroll {
1183 break;
1185 }
1186 pos = next_pos;
1187 }
1188 scroll
1189 }
1190}
1191
1192impl Widget for TextInput {
1193 fn render(&self, area: Rect, frame: &mut Frame) {
1194 if frame.a11y_enabled() && !area.is_empty() {
1199 frame.push_a11y_nodes(ftui_a11y::Accessible::accessibility_nodes(self, area));
1200 }
1201 #[cfg(feature = "tracing")]
1202 let _span = tracing::debug_span!(
1203 "widget_render",
1204 widget = "TextInput",
1205 x = area.x,
1206 y = area.y,
1207 w = area.width,
1208 h = area.height
1209 )
1210 .entered();
1211
1212 if area.width < 1 || area.height < 1 {
1213 return;
1214 }
1215
1216 let deg = frame.buffer.degradation;
1217
1218 let base_style = if deg.apply_styling() {
1222 self.style
1223 } else {
1224 Style::default()
1225 };
1226 clear_text_area(frame, area, base_style);
1227
1228 let arena = frame.arena;
1230 let graphemes_heap;
1231 let graphemes: &[&str] = if let Some(a) = arena {
1232 a.alloc_iter(self.value.graphemes(true))
1233 } else {
1234 graphemes_heap = self.value.graphemes(true).collect::<Vec<_>>();
1235 &graphemes_heap
1236 };
1237 let show_placeholder =
1238 self.value.is_empty() && self.ime_composition.is_none() && !self.placeholder.is_empty();
1239
1240 let viewport_width = area.width as usize;
1241 let cursor_visual_pos = self.cursor_visual_pos();
1242 let effective_scroll = self.effective_scroll(viewport_width);
1243
1244 let mut visual_x: usize = 0;
1246 let y = area.y;
1247
1248 if show_placeholder {
1249 let placeholder_style = if deg.apply_styling() {
1250 self.placeholder_style
1251 } else {
1252 Style::default()
1253 };
1254 for g in self.placeholder.graphemes(true) {
1255 let w = self.grapheme_width(g);
1256 if w == 0 {
1257 continue;
1258 }
1259
1260 if visual_x + w <= effective_scroll {
1262 visual_x += w;
1263 continue;
1264 }
1265
1266 if visual_x < effective_scroll {
1268 visual_x += w;
1269 continue;
1270 }
1271
1272 let rel_x = visual_x - effective_scroll;
1273
1274 if rel_x >= viewport_width {
1276 break;
1277 }
1278
1279 if rel_x + w > viewport_width {
1281 break;
1282 }
1283
1284 let mut cell = if g.chars().count() > 1 || w > 1 {
1285 let id = frame.intern_with_width(g, w as u8);
1286 Cell::new(CellContent::from_grapheme(id))
1287 } else if let Some(c) = g.chars().next() {
1288 Cell::from_char(c)
1289 } else {
1290 visual_x += w;
1291 continue;
1292 };
1293 crate::apply_style(&mut cell, placeholder_style);
1294
1295 frame
1296 .buffer
1297 .set(area.x.saturating_add(rel_x as u16), y, cell);
1298 visual_x += w;
1299 }
1300 } else {
1301 let mut display_spans: Vec<(&str, Style, bool)> = Vec::new();
1302 for (gi, g) in graphemes.iter().enumerate() {
1303 if gi == self.cursor
1304 && let Some(ime) = &self.ime_composition
1305 {
1306 let ime_style = if deg.apply_styling() {
1307 self.style
1308 } else {
1309 Style::default()
1310 };
1311 for ig in ime.graphemes(true) {
1312 display_spans.push((ig, ime_style, true));
1313 }
1314 }
1315
1316 let cell_style = if !deg.apply_styling() {
1317 Style::default()
1318 } else if self.is_in_selection(gi) {
1319 self.selection_style
1320 } else {
1321 self.style
1322 };
1323 display_spans.push((g, cell_style, false));
1324 }
1325 if self.cursor == graphemes.len()
1326 && let Some(ime) = &self.ime_composition
1327 {
1328 let ime_style = if deg.apply_styling() {
1329 self.style
1330 } else {
1331 Style::default()
1332 };
1333 for ig in ime.graphemes(true) {
1334 display_spans.push((ig, ime_style, true));
1335 }
1336 }
1337
1338 for (g, cell_style, is_ime) in display_spans {
1339 let w = self.grapheme_width(g);
1340 if w == 0 {
1341 continue;
1342 }
1343
1344 if visual_x + w <= effective_scroll {
1346 visual_x += w;
1347 continue;
1348 }
1349
1350 if visual_x < effective_scroll {
1352 visual_x += w;
1353 continue;
1354 }
1355
1356 let rel_x = visual_x - effective_scroll;
1357
1358 if rel_x >= viewport_width {
1360 break;
1361 }
1362
1363 if rel_x + w > viewport_width {
1365 break;
1366 }
1367
1368 let mut cell = if let Some(mask) = self.mask_char {
1369 Cell::from_char(mask)
1370 } else if g.chars().count() > 1 || w > 1 {
1371 let id = frame.intern_with_width(g, w as u8);
1372 Cell::new(CellContent::from_grapheme(id))
1373 } else {
1374 Cell::from_char(g.chars().next().unwrap_or(' '))
1375 };
1376 crate::apply_style(&mut cell, cell_style);
1377
1378 if is_ime && deg.apply_styling() {
1379 use ftui_render::cell::StyleFlags;
1380 let current_flags = cell.attrs.flags();
1381 cell.attrs = cell.attrs.with_flags(current_flags | StyleFlags::UNDERLINE);
1382 }
1383
1384 frame
1385 .buffer
1386 .set(area.x.saturating_add(rel_x as u16), y, cell);
1387 visual_x += w;
1388 }
1389 }
1390
1391 if self.focused {
1392 let cursor_rel_x = cursor_visual_pos.saturating_sub(effective_scroll);
1394 if cursor_rel_x < viewport_width {
1395 let cursor_screen_x = area.x.saturating_add(cursor_rel_x as u16);
1396 if let Some(cell) = frame.buffer.get_mut(cursor_screen_x, y) {
1397 if !deg.apply_styling() {
1398 use ftui_render::cell::StyleFlags;
1400 let current_flags = cell.attrs.flags();
1401 let new_flags = current_flags ^ StyleFlags::REVERSE;
1402 cell.attrs = cell.attrs.with_flags(new_flags);
1403 } else if self.cursor_style.is_empty() {
1404 use ftui_render::cell::StyleFlags;
1406 let current_flags = cell.attrs.flags();
1407 let new_flags = current_flags ^ StyleFlags::REVERSE;
1408 cell.attrs = cell.attrs.with_flags(new_flags);
1409 } else {
1410 crate::apply_style(cell, self.cursor_style);
1411 }
1412 }
1413 }
1414
1415 frame.set_cursor(Some(self.cursor_position(area)));
1416 frame.set_cursor_visible(true);
1417 }
1418 }
1419
1420 fn is_essential(&self) -> bool {
1421 true
1422 }
1423}
1424
1425impl ftui_a11y::Accessible for TextInput {
1430 fn accessibility_nodes(&self, area: Rect) -> Vec<ftui_a11y::node::A11yNodeInfo> {
1431 use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState};
1432
1433 let id = crate::a11y_node_id(area);
1434 let name = if self.value.is_empty() {
1435 self.placeholder.clone()
1436 } else if self.mask_char.is_some() {
1437 String::from("password field")
1439 } else {
1440 self.value.clone()
1441 };
1442
1443 let state = A11yState {
1444 focused: self.focused,
1445 disabled: self.max_length == Some(0),
1446 ..A11yState::default()
1447 };
1448
1449 let mut node = A11yNodeInfo::new(id, A11yRole::TextInput, area).with_state(state);
1450 if !name.is_empty() {
1451 node = node.with_name(name);
1452 }
1453 if self.mask_char.is_some() {
1454 node = node.with_description("password input");
1455 }
1456
1457 vec![node]
1458 }
1459}
1460
1461#[derive(Debug, Clone)]
1473pub struct TextInputSnapshot {
1474 value: String,
1475 cursor: usize,
1476 selection_anchor: Option<usize>,
1477}
1478
1479impl UndoSupport for TextInput {
1480 fn undo_widget_id(&self) -> UndoWidgetId {
1481 self.undo_id
1482 }
1483
1484 fn create_snapshot(&self) -> Box<dyn std::any::Any + Send> {
1485 Box::new(TextInputSnapshot {
1486 value: self.value.clone(),
1487 cursor: self.cursor,
1488 selection_anchor: self.selection_anchor,
1489 })
1490 }
1491
1492 fn restore_snapshot(&mut self, snapshot: &dyn std::any::Any) -> bool {
1493 if let Some(snap) = snapshot.downcast_ref::<TextInputSnapshot>() {
1494 self.value = snap.value.clone();
1495 self.cursor = snap.cursor;
1496 self.selection_anchor = snap.selection_anchor;
1497 self.scroll_cells.set(0); true
1499 } else {
1500 false
1501 }
1502 }
1503}
1504
1505impl TextInputUndoExt for TextInput {
1506 fn text_value(&self) -> &str {
1507 &self.value
1508 }
1509
1510 fn set_text_value(&mut self, value: &str) {
1511 self.value = value.to_string();
1512 let max = self.grapheme_count();
1513 self.cursor = self.cursor.min(max);
1514 self.selection_anchor = None;
1515 }
1516
1517 fn cursor_position(&self) -> usize {
1518 self.cursor
1519 }
1520
1521 fn set_cursor_position(&mut self, pos: usize) {
1522 let max = self.grapheme_count();
1523 self.cursor = pos.min(max);
1524 }
1525
1526 fn insert_text_at(&mut self, position: usize, text: &str) {
1527 let byte_offset = self.grapheme_byte_offset(position);
1528 self.value.insert_str(byte_offset, text);
1529 let inserted_graphemes = text.graphemes(true).count();
1530 if self.cursor >= position {
1531 self.cursor += inserted_graphemes;
1532 }
1533 }
1534
1535 fn delete_text_range(&mut self, start: usize, end: usize) {
1536 if start >= end {
1537 return;
1538 }
1539 let byte_start = self.grapheme_byte_offset(start);
1540 let byte_end = self.grapheme_byte_offset(end);
1541 self.value.drain(byte_start..byte_end);
1542 let deleted_count = end - start;
1543 if self.cursor > end {
1544 self.cursor -= deleted_count;
1545 } else if self.cursor > start {
1546 self.cursor = start;
1547 }
1548 let gc = self.grapheme_count();
1549 if self.cursor > gc {
1550 self.cursor = gc;
1551 }
1552 }
1553}
1554
1555impl TextInput {
1556 #[must_use]
1581 pub fn create_text_edit_command(
1582 &self,
1583 operation: TextEditOperation,
1584 ) -> Option<crate::undo_support::WidgetTextEditCmd> {
1585 Some(crate::undo_support::WidgetTextEditCmd::new(
1586 self.undo_id,
1587 operation,
1588 ))
1589 }
1590
1591 #[must_use]
1595 pub fn undo_id(&self) -> UndoWidgetId {
1596 self.undo_id
1597 }
1598}
1599
1600#[cfg(test)]
1601mod tests {
1602 use super::*;
1603 #[cfg(feature = "tracing")]
1604 use std::sync::{Arc, Mutex};
1605
1606 #[cfg(feature = "tracing")]
1607 use tracing::Subscriber;
1608 #[cfg(feature = "tracing")]
1609 use tracing_subscriber::Layer;
1610 #[cfg(feature = "tracing")]
1611 use tracing_subscriber::layer::{Context, SubscriberExt};
1612
1613 #[allow(dead_code)]
1614 fn cell_at(frame: &Frame, x: u16, y: u16) -> Cell {
1615 frame
1616 .buffer
1617 .get(x, y)
1618 .copied()
1619 .unwrap_or_else(|| panic!("test cell should exist at ({x},{y})"))
1620 }
1621
1622 fn raw_row_text(frame: &Frame, y: u16, width: u16) -> String {
1623 (0..width)
1624 .map(|x| {
1625 frame
1626 .buffer
1627 .get(x, y)
1628 .and_then(|cell| cell.content.as_char())
1629 .unwrap_or(' ')
1630 })
1631 .collect()
1632 }
1633
1634 #[cfg(feature = "tracing")]
1635 #[derive(Debug, Default)]
1636 struct InputTraceState {
1637 span_count: usize,
1638 has_cursor_position_field: bool,
1639 cursor_positions: Vec<usize>,
1640 operations: Vec<String>,
1641 }
1642
1643 #[cfg(feature = "tracing")]
1644 struct InputTraceCapture {
1645 state: Arc<Mutex<InputTraceState>>,
1646 }
1647
1648 #[cfg(feature = "tracing")]
1649 impl<S> Layer<S> for InputTraceCapture
1650 where
1651 S: Subscriber + for<'lookup> tracing_subscriber::registry::LookupSpan<'lookup>,
1652 {
1653 fn on_new_span(
1654 &self,
1655 attrs: &tracing::span::Attributes<'_>,
1656 _id: &tracing::Id,
1657 _ctx: Context<'_, S>,
1658 ) {
1659 if attrs.metadata().name() != "input.edit" {
1660 return;
1661 }
1662
1663 #[derive(Default)]
1664 struct InputEditVisitor {
1665 cursor_position: Option<usize>,
1666 operation: Option<String>,
1667 }
1668
1669 impl tracing::field::Visit for InputEditVisitor {
1670 fn record_i64(&mut self, field: &tracing::field::Field, value: i64) {
1671 if field.name() == "cursor_position" {
1672 self.cursor_position = usize::try_from(value).ok();
1673 }
1674 }
1675
1676 fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
1677 if field.name() == "cursor_position" {
1678 self.cursor_position = usize::try_from(value).ok();
1679 }
1680 }
1681
1682 fn record_debug(
1683 &mut self,
1684 field: &tracing::field::Field,
1685 value: &dyn std::fmt::Debug,
1686 ) {
1687 if field.name() == "operation" {
1688 self.operation = Some(format!("{value:?}").trim_matches('"').to_owned());
1689 }
1690 }
1691
1692 fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
1693 if field.name() == "operation" {
1694 self.operation = Some(value.to_owned());
1695 }
1696 }
1697 }
1698
1699 let fields = attrs.metadata().fields();
1700 let mut visitor = InputEditVisitor::default();
1701 attrs.record(&mut visitor);
1702
1703 let mut state = self.state.lock().expect("trace state lock");
1704 state.span_count += 1;
1705 state.has_cursor_position_field |= fields.field("cursor_position").is_some();
1706 if let Some(cursor) = visitor.cursor_position {
1707 state.cursor_positions.push(cursor);
1708 }
1709 if let Some(operation) = visitor.operation {
1710 state.operations.push(operation);
1711 }
1712 }
1713 }
1714
1715 #[allow(dead_code)]
1716 #[test]
1717 fn test_empty_input() {
1718 let input = TextInput::new();
1719 assert!(input.value().is_empty());
1720 assert_eq!(input.cursor(), 0);
1721 assert!(input.selected_text().is_none());
1722 }
1723
1724 #[test]
1725 fn test_with_value() {
1726 let mut input = TextInput::new().with_value("hello");
1727 input.set_focused(true);
1728 assert_eq!(input.value(), "hello");
1729 assert_eq!(input.cursor(), 5);
1730 }
1731
1732 #[test]
1733 fn test_set_value() {
1734 let mut input = TextInput::new().with_value("hello world");
1735 input.cursor = 11;
1736 input.set_value("hi");
1737 assert_eq!(input.value(), "hi");
1738 assert_eq!(input.cursor(), 2);
1739 }
1740
1741 #[test]
1742 fn test_clear() {
1743 let mut input = TextInput::new().with_value("hello");
1744 input.set_focused(true);
1745 input.clear();
1746 assert!(input.value().is_empty());
1747 assert_eq!(input.cursor(), 0);
1748 }
1749
1750 #[test]
1751 fn test_insert_char() {
1752 let mut input = TextInput::new();
1753 input.insert_char('a');
1754 input.insert_char('b');
1755 input.insert_char('c');
1756 assert_eq!(input.value(), "abc");
1757 assert_eq!(input.cursor(), 3);
1758 }
1759
1760 #[test]
1761 fn test_insert_char_mid() {
1762 let mut input = TextInput::new().with_value("ac");
1763 input.cursor = 1;
1764 input.insert_char('b');
1765 assert_eq!(input.value(), "abc");
1766 assert_eq!(input.cursor(), 2);
1767 }
1768
1769 #[test]
1770 fn test_max_length() {
1771 let mut input = TextInput::new().with_max_length(3);
1772 for c in "abcdef".chars() {
1773 input.insert_char(c);
1774 }
1775 assert_eq!(input.value(), "abc");
1776 assert_eq!(input.cursor(), 3);
1777 }
1778
1779 #[test]
1780 fn test_delete_char_back() {
1781 let mut input = TextInput::new().with_value("hello");
1782 input.delete_char_back();
1783 assert_eq!(input.value(), "hell");
1784 assert_eq!(input.cursor(), 4);
1785 }
1786
1787 #[test]
1788 fn test_delete_char_back_at_start() {
1789 let mut input = TextInput::new().with_value("hello");
1790 input.cursor = 0;
1791 input.delete_char_back();
1792 assert_eq!(input.value(), "hello");
1793 }
1794
1795 #[test]
1796 fn test_delete_char_forward() {
1797 let mut input = TextInput::new().with_value("hello");
1798 input.cursor = 0;
1799 input.delete_char_forward();
1800 assert_eq!(input.value(), "ello");
1801 assert_eq!(input.cursor(), 0);
1802 }
1803
1804 #[test]
1805 fn test_delete_char_forward_at_end() {
1806 let mut input = TextInput::new().with_value("hello");
1807 input.delete_char_forward();
1808 assert_eq!(input.value(), "hello");
1809 }
1810
1811 #[test]
1812 fn test_cursor_left_right() {
1813 let mut input = TextInput::new().with_value("hello");
1814 assert_eq!(input.cursor(), 5);
1815 input.move_cursor_left();
1816 assert_eq!(input.cursor(), 4);
1817 input.move_cursor_left();
1818 assert_eq!(input.cursor(), 3);
1819 input.move_cursor_right();
1820 assert_eq!(input.cursor(), 4);
1821 }
1822
1823 #[test]
1824 fn test_cursor_bounds() {
1825 let mut input = TextInput::new().with_value("hi");
1826 input.cursor = 0;
1827 input.move_cursor_left();
1828 assert_eq!(input.cursor(), 0);
1829 input.cursor = 2;
1830 input.move_cursor_right();
1831 assert_eq!(input.cursor(), 2);
1832 }
1833
1834 #[test]
1835 fn test_word_movement_left() {
1836 let mut input = TextInput::new().with_value("hello world test");
1837 input.move_cursor_word_left(false);
1840 assert_eq!(input.cursor(), 12); input.move_cursor_word_left(false);
1843 assert_eq!(input.cursor(), 6); input.move_cursor_word_left(false);
1846 assert_eq!(input.cursor(), 0); }
1848
1849 #[test]
1850 fn test_word_movement_right() {
1851 let mut input = TextInput::new().with_value("hello world test");
1852 input.cursor = 0;
1853 input.move_cursor_word_right(false);
1856 assert_eq!(input.cursor(), 6); input.move_cursor_word_right(false);
1859 assert_eq!(input.cursor(), 12); input.move_cursor_word_right(false);
1862 assert_eq!(input.cursor(), 16); }
1864
1865 #[test]
1866 fn test_word_movement_skips_punctuation() {
1867 let mut input = TextInput::new().with_value("hello, world");
1868 input.cursor = 0;
1869 input.move_cursor_word_right(false);
1872 assert_eq!(input.cursor(), 5); input.move_cursor_word_right(false);
1875 assert_eq!(input.cursor(), 7); input.move_cursor_word_right(false);
1878 assert_eq!(input.cursor(), 12); input.move_cursor_word_left(false);
1881 assert_eq!(input.cursor(), 7); }
1883
1884 #[test]
1885 fn test_delete_word_back() {
1886 let mut input = TextInput::new().with_value("hello world");
1887 input.delete_word_back();
1889 assert_eq!(input.value(), "hello "); input.delete_word_back();
1893 assert_eq!(input.value(), ""); }
1895
1896 #[test]
1897 fn test_delete_word_forward() {
1898 let mut input = TextInput::new().with_value("hello world");
1899 input.cursor = 0;
1900 input.delete_word_forward();
1902 assert_eq!(input.value(), "world"); input.delete_word_forward();
1905 assert_eq!(input.value(), ""); }
1907
1908 #[test]
1909 fn test_select_all() {
1910 let mut input = TextInput::new().with_value("hello");
1911 input.select_all();
1912 assert_eq!(input.selected_text(), Some("hello"));
1913 }
1914
1915 #[test]
1916 fn test_delete_selection() {
1917 let mut input = TextInput::new().with_value("hello world");
1918 input.selection_anchor = Some(0);
1919 input.cursor = 5;
1920 input.delete_selection();
1921 assert_eq!(input.value(), " world");
1922 assert_eq!(input.cursor(), 0);
1923 }
1924
1925 #[test]
1926 fn test_insert_replaces_selection() {
1927 let mut input = TextInput::new().with_value("hello");
1928 input.select_all();
1929 input.delete_selection();
1930 input.insert_char('x');
1931 assert_eq!(input.value(), "x");
1932 }
1933
1934 #[test]
1935 fn test_unicode_grapheme_handling() {
1936 let mut input = TextInput::new();
1937 input.set_value("café");
1938 assert_eq!(input.grapheme_count(), 4);
1939 input.cursor = 4;
1940 input.delete_char_back();
1941 assert_eq!(input.value(), "caf");
1942 }
1943
1944 #[test]
1945 fn test_multi_codepoint_grapheme_cursor_movement() {
1946 let mut input = TextInput::new().with_value("a👩💻b");
1947 assert_eq!(input.grapheme_count(), 3);
1948 assert_eq!(input.cursor(), 3);
1949
1950 input.move_cursor_left();
1951 assert_eq!(input.cursor(), 2);
1952 input.move_cursor_left();
1953 assert_eq!(input.cursor(), 1);
1954 input.move_cursor_left();
1955 assert_eq!(input.cursor(), 0);
1956
1957 input.move_cursor_right();
1958 assert_eq!(input.cursor(), 1);
1959 input.move_cursor_right();
1960 assert_eq!(input.cursor(), 2);
1961 input.move_cursor_right();
1962 assert_eq!(input.cursor(), 3);
1963 }
1964
1965 #[test]
1966 fn test_delete_back_multi_codepoint_grapheme() {
1967 let mut input = TextInput::new().with_value("a👩💻b");
1968 input.cursor = 2; input.delete_char_back();
1970 assert_eq!(input.value(), "ab");
1971 assert_eq!(input.cursor(), 1);
1972 assert_eq!(input.grapheme_count(), 2);
1973 }
1974
1975 #[test]
1976 fn test_ime_composition_start_update_commit() {
1977 let mut input = TextInput::new().with_value("ab");
1978 input.cursor = 1;
1979
1980 input.ime_start_composition();
1981 assert_eq!(input.ime_composition(), Some(""));
1982
1983 input.ime_update_composition("漢");
1984 assert_eq!(input.ime_composition(), Some("漢"));
1985
1986 assert!(input.ime_commit_composition());
1987 assert_eq!(input.ime_composition(), None);
1988 assert_eq!(input.value(), "a漢b");
1989 assert_eq!(input.cursor(), 2);
1990 }
1991
1992 #[test]
1993 fn test_ime_composition_cancel_keeps_value() {
1994 let mut input = TextInput::new().with_value("hello");
1995 input.ime_start_composition();
1996 input.ime_update_composition("👩💻");
1997 assert_eq!(input.ime_composition(), Some("👩💻"));
1998 assert!(input.ime_cancel_composition());
1999 assert_eq!(input.ime_composition(), None);
2000 assert_eq!(input.value(), "hello");
2001 assert_eq!(input.cursor(), 5);
2002 }
2003
2004 #[test]
2005 fn test_ime_commit_without_session_is_noop() {
2006 let mut input = TextInput::new().with_value("abc");
2007 assert!(!input.ime_commit_composition());
2008 assert_eq!(input.value(), "abc");
2009 assert_eq!(input.cursor(), 3);
2010 }
2011
2012 #[test]
2013 fn test_handle_event_ime_update_and_commit() {
2014 let mut input = TextInput::new().with_value("ab");
2015 input.cursor = 1;
2016
2017 assert!(input.handle_event(&Event::Ime(ImeEvent::start())));
2018 assert!(input.handle_event(&Event::Ime(ImeEvent::update("漢"))));
2019 assert_eq!(input.ime_composition(), Some("漢"));
2020 assert!(input.handle_event(&Event::Ime(ImeEvent::commit("漢"))));
2021 assert_eq!(input.ime_composition(), None);
2022 assert_eq!(input.value(), "a漢b");
2023 assert_eq!(input.cursor(), 2);
2024 }
2025
2026 #[test]
2027 fn test_handle_event_ime_cancel() {
2028 let mut input = TextInput::new().with_value("hello");
2029 input.cursor = 5;
2030 assert!(input.handle_event(&Event::Ime(ImeEvent::start())));
2031 assert!(input.handle_event(&Event::Ime(ImeEvent::update("👩💻"))));
2032 assert!(input.handle_event(&Event::Ime(ImeEvent::cancel())));
2033 assert_eq!(input.ime_composition(), None);
2034 assert_eq!(input.value(), "hello");
2035 assert_eq!(input.cursor(), 5);
2036 }
2037
2038 #[test]
2039 fn test_flag_emoji_grapheme_delete_and_cursor() {
2040 let mut input = TextInput::new().with_value("a🇺🇸b");
2041 assert_eq!(input.grapheme_count(), 3);
2042 input.cursor = 2;
2043 input.delete_char_back();
2044 assert_eq!(input.value(), "ab");
2045 assert_eq!(input.cursor(), 1);
2046 }
2047
2048 #[test]
2049 fn test_combining_grapheme_delete_and_cursor() {
2050 let mut input = TextInput::new().with_value("a\u{0301}b");
2051 assert_eq!(input.grapheme_count(), 2);
2052 input.cursor = 1;
2053 input.delete_char_back();
2054 assert_eq!(input.value(), "b");
2055 assert_eq!(input.cursor(), 0);
2056 }
2057
2058 #[test]
2059 fn test_bidi_logical_cursor_movement_over_graphemes() {
2060 let mut input = TextInput::new().with_value("AאבB");
2061 assert_eq!(input.grapheme_count(), 4);
2062
2063 input.move_cursor_left();
2064 assert_eq!(input.cursor(), 3);
2065 input.move_cursor_left();
2066 assert_eq!(input.cursor(), 2);
2067 input.move_cursor_left();
2068 assert_eq!(input.cursor(), 1);
2069 input.move_cursor_left();
2070 assert_eq!(input.cursor(), 0);
2071
2072 input.move_cursor_right();
2073 assert_eq!(input.cursor(), 1);
2074 input.move_cursor_right();
2075 assert_eq!(input.cursor(), 2);
2076 input.move_cursor_right();
2077 assert_eq!(input.cursor(), 3);
2078 input.move_cursor_right();
2079 assert_eq!(input.cursor(), 4);
2080 }
2081
2082 #[test]
2083 fn test_handle_event_char() {
2084 let mut input = TextInput::new();
2085 let event = Event::Key(KeyEvent::new(KeyCode::Char('a')));
2086 assert!(input.handle_event(&event));
2087 assert_eq!(input.value(), "a");
2088 }
2089
2090 #[test]
2091 fn test_handle_event_backspace() {
2092 let mut input = TextInput::new().with_value("ab");
2093 let event = Event::Key(KeyEvent::new(KeyCode::Backspace));
2094 assert!(input.handle_event(&event));
2095 assert_eq!(input.value(), "a");
2096 }
2097
2098 #[test]
2099 fn test_handle_event_ctrl_a() {
2100 let mut input = TextInput::new().with_value("hello");
2101 let event = Event::Key(KeyEvent::new(KeyCode::Char('a')).with_modifiers(Modifiers::CTRL));
2102 assert!(input.handle_event(&event));
2103 assert_eq!(input.selected_text(), Some("hello"));
2104 }
2105
2106 #[test]
2107 fn test_handle_event_ctrl_backspace() {
2108 let mut input = TextInput::new().with_value("hello world");
2109 let event = Event::Key(KeyEvent::new(KeyCode::Backspace).with_modifiers(Modifiers::CTRL));
2110 assert!(input.handle_event(&event));
2111 assert_eq!(input.value(), "hello ");
2112 }
2113
2114 #[test]
2115 fn test_handle_event_home_end() {
2116 let mut input = TextInput::new().with_value("hello");
2117 input.cursor = 3;
2118 let home = Event::Key(KeyEvent::new(KeyCode::Home));
2119 assert!(input.handle_event(&home));
2120 assert_eq!(input.cursor(), 0);
2121 let end = Event::Key(KeyEvent::new(KeyCode::End));
2122 assert!(input.handle_event(&end));
2123 assert_eq!(input.cursor(), 5);
2124 }
2125
2126 #[test]
2127 fn test_shift_left_creates_selection() {
2128 let mut input = TextInput::new().with_value("hello");
2129 let event = Event::Key(KeyEvent::new(KeyCode::Left).with_modifiers(Modifiers::SHIFT));
2130 assert!(input.handle_event(&event));
2131 assert_eq!(input.cursor(), 4);
2132 assert_eq!(input.selection_anchor, Some(5));
2133 assert_eq!(input.selected_text(), Some("o"));
2134 }
2135
2136 #[test]
2137 fn test_cursor_position() {
2138 let input = TextInput::new().with_value("hello");
2139 let area = Rect::new(10, 5, 20, 1);
2140 let (x, y) = input.cursor_position(area);
2141 assert_eq!(x, 15);
2142 assert_eq!(y, 5);
2143 }
2144
2145 #[test]
2146 fn test_cursor_position_empty() {
2147 let input = TextInput::new();
2148 let area = Rect::new(0, 0, 80, 1);
2149 let (x, y) = input.cursor_position(area);
2150 assert_eq!(x, 0);
2151 assert_eq!(y, 0);
2152 }
2153
2154 #[test]
2155 fn test_password_mask() {
2156 let input = TextInput::new().with_mask('*').with_value("secret");
2157 assert_eq!(input.value(), "secret");
2158 assert_eq!(input.cursor_visual_pos(), 6);
2159 }
2160
2161 #[test]
2162 fn test_render_basic() {
2163 use ftui_render::frame::Frame;
2164 use ftui_render::grapheme_pool::GraphemePool;
2165
2166 let input = TextInput::new().with_value("hi");
2167 let area = Rect::new(0, 0, 10, 1);
2168 let mut pool = GraphemePool::new();
2169 let mut frame = Frame::new(10, 1, &mut pool);
2170 input.render(area, &mut frame);
2171 let cell_h = cell_at(&frame, 0, 0);
2172 assert_eq!(cell_h.content.as_char(), Some('h'));
2173 let cell_i = cell_at(&frame, 1, 0);
2174 assert_eq!(cell_i.content.as_char(), Some('i'));
2175 }
2176
2177 #[test]
2178 fn test_render_sets_cursor_when_focused() {
2179 use ftui_render::frame::Frame;
2180 use ftui_render::grapheme_pool::GraphemePool;
2181
2182 let input = TextInput::new().with_value("hi").with_focused(true);
2183 let area = Rect::new(0, 0, 10, 1);
2184 let mut pool = GraphemePool::new();
2185 let mut frame = Frame::new(10, 1, &mut pool);
2186 input.render(area, &mut frame);
2187
2188 assert_eq!(frame.cursor_position, Some((2, 0)));
2189 assert!(frame.cursor_visible);
2190 }
2191
2192 #[test]
2193 fn test_render_does_not_set_cursor_when_unfocused() {
2194 use ftui_render::frame::Frame;
2195 use ftui_render::grapheme_pool::GraphemePool;
2196
2197 let input = TextInput::new().with_value("hi");
2198 let area = Rect::new(0, 0, 10, 1);
2199 let mut pool = GraphemePool::new();
2200 let mut frame = Frame::new(10, 1, &mut pool);
2201 input.render(area, &mut frame);
2202
2203 assert!(frame.cursor_position.is_none());
2204 }
2205
2206 #[test]
2207 fn test_render_grapheme_uses_pool() {
2208 use ftui_render::frame::Frame;
2209 use ftui_render::grapheme_pool::GraphemePool;
2210
2211 let grapheme = "👩💻";
2212 let input = TextInput::new().with_value(grapheme);
2213 let area = Rect::new(0, 0, 6, 1);
2214 let mut pool = GraphemePool::new();
2215 let mut frame = Frame::new(6, 1, &mut pool);
2216 input.render(area, &mut frame);
2217
2218 let cell = cell_at(&frame, 0, 0);
2219 assert!(cell.content.is_grapheme());
2220 let width = grapheme_width(grapheme);
2221 if width > 1 {
2222 assert!(cell_at(&frame, 1, 0).is_continuation());
2223 }
2224 }
2225
2226 #[test]
2227 fn test_render_shorter_value_clears_stale_suffix_and_owned_rows() {
2228 use ftui_render::frame::Frame;
2229 use ftui_render::grapheme_pool::GraphemePool;
2230
2231 let area = Rect::new(0, 0, 8, 2);
2232 let mut pool = GraphemePool::new();
2233 let mut frame = Frame::new(8, 2, &mut pool);
2234
2235 TextInput::new()
2236 .with_value("abcdef")
2237 .render(area, &mut frame);
2238 TextInput::new().with_value("xy").render(area, &mut frame);
2239
2240 assert_eq!(raw_row_text(&frame, 0, 8), "xy ");
2241 assert_eq!(raw_row_text(&frame, 1, 8), " ");
2242 }
2243
2244 #[test]
2245 fn test_left_collapses_selection() {
2246 let mut input = TextInput::new().with_value("hello");
2247 input.selection_anchor = Some(1);
2248 input.cursor = 4;
2249 input.move_cursor_left();
2250 assert_eq!(input.cursor(), 1);
2251 assert!(input.selection_anchor.is_none());
2252 }
2253
2254 #[test]
2255 fn test_right_collapses_selection() {
2256 let mut input = TextInput::new().with_value("hello");
2257 input.selection_anchor = Some(1);
2258 input.cursor = 4;
2259 input.move_cursor_right();
2260 assert_eq!(input.cursor(), 4);
2261 assert!(input.selection_anchor.is_none());
2262 }
2263
2264 #[test]
2265 fn test_render_sets_frame_cursor() {
2266 use ftui_render::frame::Frame;
2267 use ftui_render::grapheme_pool::GraphemePool;
2268
2269 let input = TextInput::new().with_value("hello").with_focused(true);
2270 let area = Rect::new(5, 3, 20, 1);
2271 let mut pool = GraphemePool::new();
2272 let mut frame = Frame::new(30, 10, &mut pool);
2273 input.render(area, &mut frame);
2274
2275 assert_eq!(frame.cursor_position, Some((10, 3)));
2279 }
2280
2281 #[test]
2282 fn test_render_cursor_mid_text() {
2283 use ftui_render::frame::Frame;
2284 use ftui_render::grapheme_pool::GraphemePool;
2285
2286 let mut input = TextInput::new().with_value("hello").with_focused(true);
2287 input.cursor = 2; let area = Rect::new(0, 0, 20, 1);
2289 let mut pool = GraphemePool::new();
2290 let mut frame = Frame::new(20, 1, &mut pool);
2291 input.render(area, &mut frame);
2292
2293 assert_eq!(frame.cursor_position, Some((2, 0)));
2295 }
2296
2297 #[test]
2302 fn test_undo_widget_id_is_stable() {
2303 let input = TextInput::new();
2304 let id1 = input.undo_id();
2305 let id2 = input.undo_id();
2306 assert_eq!(id1, id2);
2307 }
2308
2309 #[test]
2310 fn test_undo_widget_id_unique_per_instance() {
2311 let input1 = TextInput::new();
2312 let input2 = TextInput::new();
2313 assert_ne!(input1.undo_id(), input2.undo_id());
2314 }
2315
2316 #[test]
2317 fn test_snapshot_and_restore() {
2318 let mut input = TextInput::new().with_value("hello");
2319 input.cursor = 3;
2320 input.selection_anchor = Some(1);
2321
2322 let snapshot = input.create_snapshot();
2323
2324 input.set_value("world");
2326 input.cursor = 5;
2327 input.selection_anchor = None;
2328
2329 assert_eq!(input.value(), "world");
2330 assert_eq!(input.cursor(), 5);
2331
2332 assert!(input.restore_snapshot(snapshot.as_ref()));
2334 assert_eq!(input.value(), "hello");
2335 assert_eq!(input.cursor(), 3);
2336 assert_eq!(input.selection_anchor, Some(1));
2337 }
2338
2339 #[test]
2340 fn test_text_input_undo_ext_insert() {
2341 let mut input = TextInput::new().with_value("hello");
2342 input.cursor = 2;
2343
2344 input.insert_text_at(2, " world");
2345 assert_eq!(input.value(), "he worldllo");
2347 assert_eq!(input.cursor(), 8); }
2349
2350 #[test]
2351 fn test_text_input_undo_ext_delete() {
2352 let mut input = TextInput::new().with_value("hello world");
2353 input.cursor = 8;
2354
2355 input.delete_text_range(5, 11); assert_eq!(input.value(), "hello");
2357 assert_eq!(input.cursor(), 5); }
2359
2360 #[test]
2361 fn test_create_text_edit_command() {
2362 let input = TextInput::new().with_value("hello");
2363 let cmd = input.create_text_edit_command(TextEditOperation::Insert {
2364 position: 0,
2365 text: "hi".to_string(),
2366 });
2367 assert!(cmd.is_some());
2368 let cmd = cmd.expect("test command should exist");
2369 assert_eq!(cmd.widget_id(), input.undo_id());
2370 assert_eq!(cmd.description(), "Insert text");
2371 }
2372
2373 #[test]
2374 fn command_chords_do_not_type_their_letter() {
2375 for ch in ['v', 'c', 'x'] {
2378 let mut input = TextInput::new();
2379 input.handle_event(&Event::Key(
2380 KeyEvent::new(KeyCode::Char(ch)).with_modifiers(Modifiers::SUPER),
2381 ));
2382 assert_eq!(input.value(), "", "Cmd+{ch} typed into the field");
2383 }
2384 let mut input = TextInput::new();
2386 input.handle_event(&Event::Key(KeyEvent::new(KeyCode::Char('v'))));
2387 assert_eq!(input.value(), "v");
2388 }
2389
2390 #[test]
2391 fn test_paste_bulk_insert() {
2392 let mut input = TextInput::new().with_value("hello");
2393 input.cursor = 5;
2394 let event = Event::Paste(ftui_core::event::PasteEvent::bracketed(" world"));
2395 assert!(input.handle_event(&event));
2396 assert_eq!(input.value(), "hello world");
2397 assert_eq!(input.cursor(), 11);
2398 }
2399
2400 #[test]
2401 fn test_paste_multi_grapheme_sequence() {
2402 let mut input = TextInput::new().with_value("hi");
2403 input.cursor = 2;
2404 let event = Event::Paste(ftui_core::event::PasteEvent::new("👩💻🔥", false));
2405 assert!(input.handle_event(&event));
2406 assert_eq!(input.value(), "hi👩💻🔥");
2407 assert_eq!(input.cursor(), 4);
2408 }
2409
2410 #[test]
2411 fn test_paste_max_length() {
2412 let mut input = TextInput::new().with_value("abc").with_max_length(5);
2413 input.cursor = 3;
2414 let event = Event::Paste(ftui_core::event::PasteEvent::bracketed("def"));
2416 assert!(input.handle_event(&event));
2417 assert_eq!(input.value(), "abcde");
2418 assert_eq!(input.cursor(), 5);
2419 }
2420
2421 #[test]
2422 fn test_paste_combining_merge() {
2423 let mut input = TextInput::new().with_value("e");
2424 input.cursor = 1;
2425 let event = Event::Paste(ftui_core::event::PasteEvent::bracketed("\u{0301}"));
2428 assert!(input.handle_event(&event));
2429 assert_eq!(input.value(), "e\u{0301}");
2430 assert_eq!(input.grapheme_count(), 1);
2431 assert_eq!(input.cursor(), 1);
2432 }
2433
2434 #[test]
2435 fn test_paste_combining_merge_mid_string() {
2436 let mut input = TextInput::new().with_value("ab");
2437 input.cursor = 1; let event = Event::Paste(ftui_core::event::PasteEvent::bracketed("\u{0301}"));
2439 assert!(input.handle_event(&event));
2440 assert_eq!(input.value(), "a\u{0301}b");
2441 assert_eq!(input.grapheme_count(), 2);
2442 assert_eq!(input.cursor(), 1);
2443 }
2444
2445 #[test]
2446 fn test_wide_char_scroll_visibility() {
2447 use ftui_render::frame::Frame;
2448 use ftui_render::grapheme_pool::GraphemePool;
2449
2450 let wide_char = "\u{3000}"; let mut input = TextInput::new().with_value(wide_char).with_focused(true);
2452 input.cursor = 1; let area = Rect::new(0, 0, 2, 1);
2460 let mut pool = GraphemePool::new();
2461 let mut frame = Frame::new(2, 1, &mut pool);
2462 input.render(area, &mut frame);
2463
2464 let cell = cell_at(&frame, 0, 0);
2465 assert!(!cell.is_empty(), "Wide char should be visible");
2467 }
2468
2469 #[test]
2470 fn test_wide_char_scroll_snapping() {
2471 let _input = TextInput::new().with_value("a\u{3000}b"); let wide_char = "\u{3000}";
2502 let text = format!("a{wide_char}b");
2503 let mut input = TextInput::new().with_value(&text);
2504
2505 input.cursor = 3; let _area = Rect::new(0, 0, 2, 1); }
2602
2603 #[cfg(feature = "tracing")]
2604 #[test]
2605 fn tracing_input_edit_span_tracks_cursor_positions() {
2606 let state = Arc::new(Mutex::new(InputTraceState::default()));
2607 let _trace_test_guard = crate::tracing_test_support::acquire();
2608 let subscriber = tracing_subscriber::registry().with(InputTraceCapture {
2609 state: Arc::clone(&state),
2610 });
2611 let _guard = tracing::subscriber::set_default(subscriber);
2612 tracing::callsite::rebuild_interest_cache();
2613
2614 let mut input = TextInput::new().with_value("ab");
2615 tracing::callsite::rebuild_interest_cache();
2616 assert!(input.handle_event(&Event::Key(KeyEvent::new(KeyCode::Char('c')))));
2617 tracing::callsite::rebuild_interest_cache();
2618 assert!(input.handle_event(&Event::Key(KeyEvent::new(KeyCode::Left))));
2619 tracing::callsite::rebuild_interest_cache();
2620 assert!(input.handle_event(&Event::Key(KeyEvent::new(KeyCode::Backspace))));
2621
2622 tracing::callsite::rebuild_interest_cache();
2623 let snapshot = state.lock().expect("trace state lock");
2624 assert!(
2625 snapshot.span_count >= 3,
2626 "expected at least 3 input.edit spans, got {}",
2627 snapshot.span_count
2628 );
2629 assert!(
2630 snapshot.has_cursor_position_field,
2631 "input.edit span missing cursor_position field"
2632 );
2633 assert_eq!(
2634 snapshot.cursor_positions,
2635 vec![3, 2, 1],
2636 "expected cursor positions after insert/left/backspace"
2637 );
2638 assert!(
2639 snapshot.operations.starts_with(&[
2640 "insert_char".to_string(),
2641 "move_left".to_string(),
2642 "delete_back".to_string()
2643 ]),
2644 "unexpected operations: {:?}",
2645 snapshot.operations
2646 );
2647 }
2648}
2649
2650#[cfg(test)]
2651mod scroll_edge_tests {
2652 use super::*;
2653 use ftui_render::frame::Frame;
2654 use ftui_render::grapheme_pool::GraphemePool;
2655
2656 #[test]
2657 fn test_scroll_snap_left_cursor_visibility() {
2658 let mut input = TextInput::new().with_value("ABC");
2666 input.cursor = 1; let area = Rect::new(0, 0, 1, 1);
2671 let mut pool = GraphemePool::new();
2672 let mut frame = Frame::new(1, 1, &mut pool);
2673 input.render(area, &mut frame); input.move_cursor_left(); input.render(area, &mut frame);
2680
2681 let cell = frame.buffer.get(0, 0).unwrap();
2683 assert_eq!(cell.content.as_char(), Some('A'));
2684 }
2685
2686 #[test]
2687 fn test_max_length_replacement_failure() {
2688 let mut input = TextInput::new().with_value("abc").with_max_length(3);
2694 input.selection_anchor = Some(1); input.cursor = 2; let event = Event::Paste(ftui_core::event::PasteEvent::new("de", false));
2699 input.handle_event(&event);
2700
2701 assert_eq!(input.value(), "abc");
2703 assert_eq!(input.cursor(), 2);
2704 assert_eq!(input.selection_anchor, Some(1));
2705 }
2706
2707 mod history_tests {
2708 use super::*;
2709 use proptest::prelude::*;
2710
2711 fn key(code: KeyCode) -> Event {
2712 Event::Key(KeyEvent::new(code))
2713 }
2714
2715 fn typ(input: &mut TextInput, s: &str) {
2716 for c in s.chars() {
2717 input.handle_event(&key(KeyCode::Char(c)));
2718 }
2719 }
2720
2721 fn submit_and_clear(input: &mut TextInput) {
2724 input.handle_event(&key(KeyCode::Enter));
2725 input.clear();
2726 }
2727
2728 fn up(input: &mut TextInput) -> bool {
2729 input.handle_event(&key(KeyCode::Up))
2730 }
2731
2732 fn down(input: &mut TextInput) -> bool {
2733 input.handle_event(&key(KeyCode::Down))
2734 }
2735
2736 #[test]
2737 fn up_recalls_previous_entry() {
2738 let mut input = TextInput::new().with_history(10);
2739 typ(&mut input, "one");
2740 submit_and_clear(&mut input);
2741 typ(&mut input, "two");
2742 submit_and_clear(&mut input);
2743
2744 assert!(up(&mut input));
2745 assert_eq!(input.value(), "two");
2746 assert!(up(&mut input));
2747 assert_eq!(input.value(), "one");
2748 assert!(!up(&mut input));
2751 assert_eq!(input.value(), "one");
2752 assert_eq!(input.history().collect::<Vec<_>>(), vec!["one", "two"]);
2753 }
2754
2755 #[test]
2756 fn down_returns_to_draft() {
2757 let mut input = TextInput::new().with_history(10);
2758 typ(&mut input, "one");
2759 submit_and_clear(&mut input);
2760 typ(&mut input, "two");
2761 submit_and_clear(&mut input);
2762 typ(&mut input, "dr");
2764
2765 assert!(up(&mut input));
2766 assert_eq!(input.value(), "two");
2767 assert!(up(&mut input));
2768 assert_eq!(input.value(), "one");
2769 assert!(down(&mut input));
2770 assert_eq!(input.value(), "two");
2771 assert!(down(&mut input));
2772 assert_eq!(
2773 input.value(),
2774 "dr",
2775 "past the newest entry the draft returns"
2776 );
2777 assert!(!down(&mut input));
2779 assert_eq!(input.value(), "dr");
2780 }
2781
2782 #[test]
2783 fn history_dedups_consecutive() {
2784 let mut input = TextInput::new().with_history(10);
2785 for value in ["a", "a", "b", "a"] {
2786 input.set_value(value);
2787 input.push_history();
2788 }
2789 assert_eq!(input.history().collect::<Vec<_>>(), vec!["a", "b", "a"]);
2791 }
2792
2793 #[test]
2794 fn history_caps_at_capacity() {
2795 let mut input = TextInput::new().with_history(3);
2796 for value in ["a", "b", "c", "d", "e"] {
2797 input.set_value(value);
2798 input.push_history();
2799 }
2800 assert_eq!(input.history_capacity(), Some(3));
2801 assert_eq!(input.history().collect::<Vec<_>>(), vec!["c", "d", "e"]);
2802 }
2803
2804 #[test]
2805 fn submit_resets_cursor() {
2806 let mut input = TextInput::new().with_history(10);
2807 typ(&mut input, "aa");
2808 submit_and_clear(&mut input);
2809 typ(&mut input, "bb");
2810 submit_and_clear(&mut input);
2811
2812 assert!(up(&mut input));
2814 assert_eq!(input.value(), "bb");
2815 assert!(up(&mut input));
2816 assert_eq!(input.value(), "aa");
2817
2818 submit_and_clear(&mut input);
2822 assert!(up(&mut input));
2823 assert_eq!(input.value(), "aa", "recall restarts at the newest entry");
2824 assert!(up(&mut input));
2827 assert_eq!(input.value(), "bb");
2828 }
2829
2830 #[test]
2831 fn typing_after_recall_clears_cursor() {
2832 let mut input = TextInput::new().with_history(10);
2833 typ(&mut input, "one");
2834 submit_and_clear(&mut input);
2835 typ(&mut input, "two");
2836 submit_and_clear(&mut input);
2837
2838 assert!(up(&mut input));
2839 assert_eq!(input.value(), "two");
2840 typ(&mut input, "x");
2843 assert_eq!(input.value(), "twox");
2844 assert!(up(&mut input));
2845 assert_eq!(input.value(), "two", "Up restarts recall from the newest");
2846 assert!(down(&mut input));
2847 assert_eq!(
2848 input.value(),
2849 "twox",
2850 "Down past the newest restores the edited draft"
2851 );
2852 }
2853
2854 #[test]
2855 fn empty_submit_not_recorded() {
2856 let mut input = TextInput::new().with_history(10);
2857 input.handle_event(&key(KeyCode::Enter));
2859 typ(&mut input, "x");
2860 submit_and_clear(&mut input);
2861 assert_eq!(input.history().collect::<Vec<_>>(), vec!["x"]);
2862 }
2863
2864 #[test]
2865 fn whitespace_submit_recorded_as_is() {
2866 let mut input = TextInput::new().with_history(10);
2867 input.set_value(" ");
2868 input.push_history();
2869 assert_eq!(input.history().collect::<Vec<_>>(), vec![" "]);
2870 }
2871
2872 #[test]
2873 fn set_value_does_not_touch_history() {
2874 let mut input = TextInput::new().with_history(10);
2875 typ(&mut input, "first");
2876 submit_and_clear(&mut input);
2877 input.set_value("zzz");
2878 assert_eq!(input.history().collect::<Vec<_>>(), vec!["first"]);
2879 assert!(up(&mut input));
2881 assert_eq!(input.value(), "first");
2882 }
2883
2884 #[test]
2885 fn no_history_leaves_updown_unconsumed() {
2886 let mut input = TextInput::new().with_value("hello");
2887 assert!(!input.handle_event(&key(KeyCode::Up)));
2888 assert_eq!(input.value(), "hello");
2889 assert!(!input.handle_event(&key(KeyCode::Down)));
2890 assert_eq!(input.value(), "hello");
2891 assert_eq!(input.history_capacity(), None);
2892 }
2893
2894 #[test]
2895 fn no_history_leaves_arrows_for_the_parent() {
2896 let mut input = TextInput::new();
2899 assert!(!input.handle_event(&key(KeyCode::Up)));
2900 assert!(!input.handle_event(&key(KeyCode::Down)));
2901 assert!(!input.handle_event(&key(KeyCode::Enter)));
2902 assert_eq!(input.history_capacity(), None);
2903 }
2904
2905 proptest! {
2906 #![proptest_config(ProptestConfig::with_cases(512))]
2907
2908 #[test]
2911 fn updown_sequences_never_panic_and_end_in_draft(
2912 entries in prop::collection::vec("[a-c]{1,3}", 0..=10),
2913 draft in "[a-c]{0,3}",
2914 steps in prop::collection::vec(any::<bool>(), 0..50),
2915 ) {
2916 let mut input = TextInput::new().with_history(16);
2917 for entry in &entries {
2918 input.set_value(entry.clone());
2919 input.push_history();
2920 }
2921 input.clear();
2922 input.set_value(draft.clone());
2923
2924 let history_entries: Vec<String> = input.history().map(String::from).collect();
2925
2926 for is_up in steps {
2927 if is_up {
2928 input.handle_event(&key(KeyCode::Up));
2929 } else {
2930 input.handle_event(&key(KeyCode::Down));
2931 }
2932 let current = input.value();
2933 prop_assert!(
2934 current == draft.as_str() || history_entries.iter().any(|e| e == current),
2935 "value {:?} not in history or draft",
2936 current
2937 );
2938 }
2939 for _ in 0..(history_entries.len() + 2) {
2941 input.handle_event(&key(KeyCode::Down));
2942 }
2943 prop_assert_eq!(input.value(), draft.as_str());
2944 }
2945 }
2946
2947 #[test]
2952 fn input_rtl_keys_move_in_logical_order_like_the_renderer() {
2953 let mut input = TextInput::new().with_value("\u{0645}\u{0631}\u{062D}\u{0628}\u{0627}");
2955 input.cursor = 0;
2956
2957 input.handle_event(&key(KeyCode::Right));
2958 assert_eq!(input.cursor, 1);
2959 assert_eq!(input.cursor_visual_pos(), 1);
2960
2961 input.handle_event(&key(KeyCode::Left));
2962 assert_eq!(input.cursor, 0);
2963 assert_eq!(input.cursor_visual_pos(), 0);
2964
2965 input.handle_event(&key(KeyCode::End));
2966 assert_eq!(input.cursor, 5);
2967 assert_eq!(input.cursor_visual_pos(), 5);
2968
2969 input.handle_event(&key(KeyCode::Home));
2970 assert_eq!(input.cursor, 0);
2971 }
2972
2973 #[test]
2974 fn input_mixed_bidi_cluster_caret_matches_logical_render() {
2975 let mut input = TextInput::new().with_value("a\u{0301} \u{05D0}\u{05D1}");
2977 input.cursor = 0;
2978 input.handle_event(&key(KeyCode::Right));
2979 input.handle_event(&key(KeyCode::Right));
2980 assert_eq!(input.cursor, 2);
2981 assert_eq!(input.cursor_visual_pos(), 2);
2982 let mut input = TextInput::new()
2984 .with_value("x\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467} \u{05D0}");
2985 input.cursor = 2;
2986 assert_eq!(input.cursor_visual_pos(), 3);
2987 }
2988 }
2989}