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::Tick => "tick",
698 }
699 }
700
701 #[cfg(feature = "tracing")]
702 fn key_operation_name(key: &KeyEvent) -> &'static str {
703 let ctrl = key.modifiers.contains(Modifiers::CTRL);
704 let shift = key.modifiers.contains(Modifiers::SHIFT);
705
706 match key.code {
707 KeyCode::Char(_) if !ctrl => "insert_char",
708 KeyCode::Char('a') if ctrl => "select_all",
709 KeyCode::Char('w') if ctrl => "delete_word_back",
710 KeyCode::Backspace if ctrl => "delete_word_back",
711 KeyCode::Backspace => "delete_back",
712 KeyCode::Delete if ctrl => "delete_word_forward",
713 KeyCode::Delete => "delete_forward",
714 KeyCode::Left if ctrl && shift => "move_word_left_select",
715 KeyCode::Left if ctrl => "move_word_left",
716 KeyCode::Left if shift => "move_left_select",
717 KeyCode::Left => "move_left",
718 KeyCode::Right if ctrl && shift => "move_word_right_select",
719 KeyCode::Right if ctrl => "move_word_right",
720 KeyCode::Right if shift => "move_right_select",
721 KeyCode::Right => "move_right",
722 KeyCode::Home if shift => "move_home_select",
723 KeyCode::Home => "move_home",
724 KeyCode::End if shift => "move_end_select",
725 KeyCode::End => "move_end",
726 _ => "key_other",
727 }
728 }
729
730 fn sanitize_input_text(text: &str) -> String {
733 text.chars()
735 .map(|c| {
736 if c == '\n' || c == '\r' || c == '\t' {
737 ' '
738 } else {
739 c
740 }
741 })
742 .filter(|c| !c.is_control())
743 .collect()
744 }
745
746 pub fn insert_text(&mut self, text: &str) {
754 self.delete_selection();
755
756 let clean_text = Self::sanitize_input_text(text);
757
758 if clean_text.is_empty() {
759 return;
760 }
761
762 let current_count = self.grapheme_count();
763 let avail = if let Some(max) = self.max_length {
764 if current_count >= max {
765 1
767 } else {
768 max - current_count
769 }
770 } else {
771 usize::MAX
772 };
773
774 let new_graphemes = clean_text.graphemes(true).count();
776 let to_insert = if new_graphemes > avail {
777 let end_byte = clean_text
779 .grapheme_indices(true)
780 .map(|(i, _)| i)
781 .nth(avail)
782 .unwrap_or(clean_text.len());
783 &clean_text[..end_byte]
784 } else {
785 clean_text.as_str()
786 };
787
788 if to_insert.is_empty() {
789 return;
790 }
791
792 let byte_offset = self.grapheme_byte_offset(self.cursor);
793 self.value.insert_str(byte_offset, to_insert);
794
795 let new_total = self.grapheme_count();
797 if let Some(max) = self.max_length
798 && new_total > max
799 {
800 self.value.drain(byte_offset..byte_offset + to_insert.len());
802 return;
803 }
804
805 self.cursor = self
806 .value
807 .grapheme_indices(true)
808 .take_while(|(i, _)| *i < byte_offset + to_insert.len())
809 .count();
810 }
811
812 fn insert_char(&mut self, c: char) {
813 if c.is_control() {
815 return;
816 }
817
818 self.delete_selection();
819
820 let byte_offset = self.grapheme_byte_offset(self.cursor);
821 self.value.insert(byte_offset, c);
822
823 let new_count = self.grapheme_count();
824
825 if let Some(max) = self.max_length
827 && new_count > max
828 {
829 let char_len = c.len_utf8();
831 self.value.drain(byte_offset..byte_offset + char_len);
832 return;
833 }
834
835 let char_len = c.len_utf8();
836 self.cursor = self
837 .value
838 .grapheme_indices(true)
839 .take_while(|(i, _)| *i < byte_offset + char_len)
840 .count();
841 }
842
843 fn delete_char_back(&mut self) {
844 if self.cursor > 0 {
845 let byte_start = self.grapheme_byte_offset(self.cursor - 1);
846 let byte_end = self.grapheme_byte_offset(self.cursor);
847 self.value.drain(byte_start..byte_end);
848 self.cursor -= 1;
849 let gc = self.grapheme_count();
850 if self.cursor > gc {
851 self.cursor = gc;
852 }
853 }
854 }
855
856 fn delete_char_forward(&mut self) {
857 let count = self.grapheme_count();
858 if self.cursor < count {
859 let byte_start = self.grapheme_byte_offset(self.cursor);
860 let byte_end = self.grapheme_byte_offset(self.cursor + 1);
861 self.value.drain(byte_start..byte_end);
862 let gc = self.grapheme_count();
863 if self.cursor > gc {
864 self.cursor = gc;
865 }
866 }
867 }
868
869 fn delete_word_back(&mut self) {
870 if self.cursor == 0 {
871 return;
872 }
873
874 let old_cursor = self.cursor;
875 self.move_cursor_word_left(false);
877 let new_cursor = self.cursor;
878
879 if new_cursor < old_cursor {
880 let byte_start = self.grapheme_byte_offset(new_cursor);
881 let byte_end = self.grapheme_byte_offset(old_cursor);
882 self.value.drain(byte_start..byte_end);
883 self.cursor = new_cursor;
884 let gc = self.grapheme_count();
885 if self.cursor > gc {
886 self.cursor = gc;
887 }
888 }
889 }
890
891 fn delete_word_forward(&mut self) {
892 let old_cursor = self.cursor;
893 self.move_cursor_word_right(false);
895 let new_cursor = self.cursor;
896 self.cursor = old_cursor;
898
899 if new_cursor > old_cursor {
900 let byte_start = self.grapheme_byte_offset(old_cursor);
901 let byte_end = self.grapheme_byte_offset(new_cursor);
902 self.value.drain(byte_start..byte_end);
903 let gc = self.grapheme_count();
904 if self.cursor > gc {
905 self.cursor = gc;
906 }
907 }
908 }
909
910 pub fn select_all(&mut self) {
914 self.selection_anchor = Some(0);
915 self.cursor = self.grapheme_count();
916 }
917
918 fn delete_selection(&mut self) {
920 if let Some(anchor) = self.selection_anchor.take() {
921 let (start, end) = self.selection_range(anchor);
922 let byte_start = self.grapheme_byte_offset(start);
923 let byte_end = self.grapheme_byte_offset(end);
924 self.value.drain(byte_start..byte_end);
925 self.cursor = start;
926 let gc = self.grapheme_count();
927 if self.cursor > gc {
928 self.cursor = gc;
929 }
930 }
931 }
932
933 fn ensure_selection_anchor(&mut self) {
934 if self.selection_anchor.is_none() {
935 self.selection_anchor = Some(self.cursor);
936 }
937 }
938
939 fn selection_range(&self, anchor: usize) -> (usize, usize) {
940 if anchor <= self.cursor {
941 (anchor, self.cursor)
942 } else {
943 (self.cursor, anchor)
944 }
945 }
946
947 fn is_in_selection(&self, grapheme_idx: usize) -> bool {
948 if let Some(anchor) = self.selection_anchor {
949 let (start, end) = self.selection_range(anchor);
950 grapheme_idx >= start && grapheme_idx < end
951 } else {
952 false
953 }
954 }
955
956 fn move_cursor_left(&mut self) {
959 if let Some(anchor) = self.selection_anchor.take() {
960 self.cursor = self.cursor.min(anchor);
961 } else if self.cursor > 0 {
962 self.cursor -= 1;
963 }
964 }
965
966 fn move_cursor_right(&mut self) {
967 if let Some(anchor) = self.selection_anchor.take() {
968 self.cursor = self.cursor.max(anchor);
969 } else if self.cursor < self.grapheme_count() {
970 self.cursor += 1;
971 }
972 }
973
974 fn move_cursor_left_select(&mut self) {
975 self.ensure_selection_anchor();
976 if self.cursor > 0 {
977 self.cursor -= 1;
978 }
979 }
980
981 fn move_cursor_right_select(&mut self) {
982 self.ensure_selection_anchor();
983 if self.cursor < self.grapheme_count() {
984 self.cursor += 1;
985 }
986 }
987
988 fn get_grapheme_class(g: &str) -> u8 {
989 if g.chars().all(char::is_whitespace) {
990 0
991 } else if g.chars().any(char::is_alphanumeric) {
992 1
993 } else {
994 2
995 }
996 }
997
998 fn move_cursor_word_left(&mut self, select: bool) {
999 if select {
1000 self.ensure_selection_anchor();
1001 } else {
1002 self.selection_anchor = None;
1003 }
1004
1005 if self.cursor == 0 {
1006 return;
1007 }
1008
1009 let byte_offset = self.grapheme_byte_offset(self.cursor);
1010 let before_cursor = &self.value[..byte_offset];
1011 let mut pos = self.cursor;
1012
1013 let mut iter = before_cursor.graphemes(true).rev();
1014
1015 while let Some(g) = iter.next() {
1016 if Self::get_grapheme_class(g) == 0 {
1017 pos = pos.saturating_sub(1);
1018 } else {
1019 pos = pos.saturating_sub(1);
1020 let target = Self::get_grapheme_class(g);
1021 for g_next in iter {
1022 if Self::get_grapheme_class(g_next) == target {
1023 pos = pos.saturating_sub(1);
1024 } else {
1025 break;
1026 }
1027 }
1028 break;
1029 }
1030 }
1031
1032 self.cursor = pos;
1033 }
1034
1035 fn move_cursor_word_right(&mut self, select: bool) {
1036 if select {
1037 self.ensure_selection_anchor();
1038 } else {
1039 self.selection_anchor = None;
1040 }
1041
1042 let mut iter = self.value.graphemes(true).peekable();
1043 for _ in 0..self.cursor {
1044 iter.next();
1045 }
1046
1047 let mut pos = self.cursor;
1048
1049 if let Some(&g) = iter.peek() {
1050 let start_class = Self::get_grapheme_class(g);
1051 if start_class != 0 {
1052 while let Some(&next_g) = iter.peek() {
1053 if Self::get_grapheme_class(next_g) == start_class {
1054 iter.next();
1055 pos += 1;
1056 } else {
1057 break;
1058 }
1059 }
1060 }
1061 }
1062
1063 while let Some(&g) = iter.peek() {
1064 if Self::get_grapheme_class(g) == 0 {
1065 iter.next();
1066 pos += 1;
1067 } else {
1068 break;
1069 }
1070 }
1071
1072 self.cursor = pos;
1073 }
1074
1075 fn grapheme_count(&self) -> usize {
1078 self.value.graphemes(true).count()
1079 }
1080
1081 fn grapheme_byte_offset(&self, grapheme_idx: usize) -> usize {
1082 self.value
1083 .grapheme_indices(true)
1084 .nth(grapheme_idx)
1085 .map(|(i, _)| i)
1086 .unwrap_or(self.value.len())
1087 }
1088
1089 fn grapheme_width(&self, g: &str) -> usize {
1090 if let Some(mask) = self.mask_char {
1091 let mut buf = [0u8; 4];
1092 let mask_str = mask.encode_utf8(&mut buf);
1093 grapheme_width(mask_str)
1094 } else {
1095 grapheme_width(g)
1096 }
1097 }
1098
1099 fn prev_grapheme_width(&self) -> usize {
1100 if self.cursor == 0 {
1101 return 0;
1102 }
1103 self.value
1104 .graphemes(true)
1105 .nth(self.cursor - 1)
1106 .map(|g| self.grapheme_width(g))
1107 .unwrap_or(0)
1108 }
1109
1110 fn cursor_visual_pos(&self) -> usize {
1111 let mut pos = 0;
1112 if !self.value.is_empty() {
1113 pos += self
1116 .value
1117 .graphemes(true)
1118 .take(self.cursor)
1119 .map(|g| self.grapheme_width(g))
1120 .sum::<usize>();
1121 }
1122 if let Some(ime) = &self.ime_composition {
1123 pos += ime
1124 .graphemes(true)
1125 .map(|g| self.grapheme_width(g))
1126 .sum::<usize>();
1127 }
1128 pos
1129 }
1130
1131 fn effective_scroll(&self, viewport_width: usize) -> usize {
1132 let cursor_visual = self.cursor_visual_pos();
1133 let mut scroll = self.scroll_cells.get();
1134 if cursor_visual < scroll {
1135 scroll = cursor_visual;
1136 }
1137 if cursor_visual >= scroll + viewport_width {
1138 let candidate_scroll = cursor_visual - viewport_width + 1;
1139 let prev_width = self.prev_grapheme_width();
1142 let max_scroll_for_prev = cursor_visual.saturating_sub(prev_width);
1143
1144 if viewport_width > prev_width {
1147 scroll = candidate_scroll.min(max_scroll_for_prev);
1148 } else {
1149 scroll = candidate_scroll;
1150 }
1151 }
1152
1153 scroll = self.snap_scroll_to_grapheme_boundary(scroll, viewport_width);
1155
1156 self.scroll_cells.set(scroll);
1157 scroll
1158 }
1159
1160 fn snap_scroll_to_grapheme_boundary(&self, scroll: usize, viewport_width: usize) -> usize {
1161 let mut pos = 0;
1162 let cursor_visual = self.cursor_visual_pos();
1163
1164 for g in self.value.graphemes(true) {
1165 let w = self.grapheme_width(g);
1166 let next_pos = pos + w;
1167
1168 if pos < scroll && scroll < next_pos {
1170 if cursor_visual <= pos + viewport_width {
1174 return pos;
1175 } else {
1176 return next_pos;
1178 }
1179 }
1180
1181 if next_pos > scroll {
1182 break;
1184 }
1185 pos = next_pos;
1186 }
1187 scroll
1188 }
1189}
1190
1191impl Widget for TextInput {
1192 fn render(&self, area: Rect, frame: &mut Frame) {
1193 if frame.a11y_enabled() && !area.is_empty() {
1198 frame.push_a11y_nodes(ftui_a11y::Accessible::accessibility_nodes(self, area));
1199 }
1200 #[cfg(feature = "tracing")]
1201 let _span = tracing::debug_span!(
1202 "widget_render",
1203 widget = "TextInput",
1204 x = area.x,
1205 y = area.y,
1206 w = area.width,
1207 h = area.height
1208 )
1209 .entered();
1210
1211 if area.width < 1 || area.height < 1 {
1212 return;
1213 }
1214
1215 let deg = frame.buffer.degradation;
1216
1217 let base_style = if deg.apply_styling() {
1221 self.style
1222 } else {
1223 Style::default()
1224 };
1225 clear_text_area(frame, area, base_style);
1226
1227 let arena = frame.arena;
1229 let graphemes_heap;
1230 let graphemes: &[&str] = if let Some(a) = arena {
1231 a.alloc_iter(self.value.graphemes(true))
1232 } else {
1233 graphemes_heap = self.value.graphemes(true).collect::<Vec<_>>();
1234 &graphemes_heap
1235 };
1236 let show_placeholder =
1237 self.value.is_empty() && self.ime_composition.is_none() && !self.placeholder.is_empty();
1238
1239 let viewport_width = area.width as usize;
1240 let cursor_visual_pos = self.cursor_visual_pos();
1241 let effective_scroll = self.effective_scroll(viewport_width);
1242
1243 let mut visual_x: usize = 0;
1245 let y = area.y;
1246
1247 if show_placeholder {
1248 let placeholder_style = if deg.apply_styling() {
1249 self.placeholder_style
1250 } else {
1251 Style::default()
1252 };
1253 for g in self.placeholder.graphemes(true) {
1254 let w = self.grapheme_width(g);
1255 if w == 0 {
1256 continue;
1257 }
1258
1259 if visual_x + w <= effective_scroll {
1261 visual_x += w;
1262 continue;
1263 }
1264
1265 if visual_x < effective_scroll {
1267 visual_x += w;
1268 continue;
1269 }
1270
1271 let rel_x = visual_x - effective_scroll;
1272
1273 if rel_x >= viewport_width {
1275 break;
1276 }
1277
1278 if rel_x + w > viewport_width {
1280 break;
1281 }
1282
1283 let mut cell = if g.chars().count() > 1 || w > 1 {
1284 let id = frame.intern_with_width(g, w as u8);
1285 Cell::new(CellContent::from_grapheme(id))
1286 } else if let Some(c) = g.chars().next() {
1287 Cell::from_char(c)
1288 } else {
1289 visual_x += w;
1290 continue;
1291 };
1292 crate::apply_style(&mut cell, placeholder_style);
1293
1294 frame
1295 .buffer
1296 .set(area.x.saturating_add(rel_x as u16), y, cell);
1297 visual_x += w;
1298 }
1299 } else {
1300 let mut display_spans: Vec<(&str, Style, bool)> = Vec::new();
1301 for (gi, g) in graphemes.iter().enumerate() {
1302 if gi == self.cursor
1303 && let Some(ime) = &self.ime_composition
1304 {
1305 let ime_style = if deg.apply_styling() {
1306 self.style
1307 } else {
1308 Style::default()
1309 };
1310 for ig in ime.graphemes(true) {
1311 display_spans.push((ig, ime_style, true));
1312 }
1313 }
1314
1315 let cell_style = if !deg.apply_styling() {
1316 Style::default()
1317 } else if self.is_in_selection(gi) {
1318 self.selection_style
1319 } else {
1320 self.style
1321 };
1322 display_spans.push((g, cell_style, false));
1323 }
1324 if self.cursor == graphemes.len()
1325 && let Some(ime) = &self.ime_composition
1326 {
1327 let ime_style = if deg.apply_styling() {
1328 self.style
1329 } else {
1330 Style::default()
1331 };
1332 for ig in ime.graphemes(true) {
1333 display_spans.push((ig, ime_style, true));
1334 }
1335 }
1336
1337 for (g, cell_style, is_ime) in display_spans {
1338 let w = self.grapheme_width(g);
1339 if w == 0 {
1340 continue;
1341 }
1342
1343 if visual_x + w <= effective_scroll {
1345 visual_x += w;
1346 continue;
1347 }
1348
1349 if visual_x < effective_scroll {
1351 visual_x += w;
1352 continue;
1353 }
1354
1355 let rel_x = visual_x - effective_scroll;
1356
1357 if rel_x >= viewport_width {
1359 break;
1360 }
1361
1362 if rel_x + w > viewport_width {
1364 break;
1365 }
1366
1367 let mut cell = if let Some(mask) = self.mask_char {
1368 Cell::from_char(mask)
1369 } else if g.chars().count() > 1 || w > 1 {
1370 let id = frame.intern_with_width(g, w as u8);
1371 Cell::new(CellContent::from_grapheme(id))
1372 } else {
1373 Cell::from_char(g.chars().next().unwrap_or(' '))
1374 };
1375 crate::apply_style(&mut cell, cell_style);
1376
1377 if is_ime && deg.apply_styling() {
1378 use ftui_render::cell::StyleFlags;
1379 let current_flags = cell.attrs.flags();
1380 cell.attrs = cell.attrs.with_flags(current_flags | StyleFlags::UNDERLINE);
1381 }
1382
1383 frame
1384 .buffer
1385 .set(area.x.saturating_add(rel_x as u16), y, cell);
1386 visual_x += w;
1387 }
1388 }
1389
1390 if self.focused {
1391 let cursor_rel_x = cursor_visual_pos.saturating_sub(effective_scroll);
1393 if cursor_rel_x < viewport_width {
1394 let cursor_screen_x = area.x.saturating_add(cursor_rel_x as u16);
1395 if let Some(cell) = frame.buffer.get_mut(cursor_screen_x, y) {
1396 if !deg.apply_styling() {
1397 use ftui_render::cell::StyleFlags;
1399 let current_flags = cell.attrs.flags();
1400 let new_flags = current_flags ^ StyleFlags::REVERSE;
1401 cell.attrs = cell.attrs.with_flags(new_flags);
1402 } else if self.cursor_style.is_empty() {
1403 use ftui_render::cell::StyleFlags;
1405 let current_flags = cell.attrs.flags();
1406 let new_flags = current_flags ^ StyleFlags::REVERSE;
1407 cell.attrs = cell.attrs.with_flags(new_flags);
1408 } else {
1409 crate::apply_style(cell, self.cursor_style);
1410 }
1411 }
1412 }
1413
1414 frame.set_cursor(Some(self.cursor_position(area)));
1415 frame.set_cursor_visible(true);
1416 }
1417 }
1418
1419 fn is_essential(&self) -> bool {
1420 true
1421 }
1422}
1423
1424impl ftui_a11y::Accessible for TextInput {
1429 fn accessibility_nodes(&self, area: Rect) -> Vec<ftui_a11y::node::A11yNodeInfo> {
1430 use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState};
1431
1432 let id = crate::a11y_node_id(area);
1433 let name = if self.value.is_empty() {
1434 self.placeholder.clone()
1435 } else if self.mask_char.is_some() {
1436 String::from("password field")
1438 } else {
1439 self.value.clone()
1440 };
1441
1442 let state = A11yState {
1443 focused: self.focused,
1444 disabled: self.max_length == Some(0),
1445 ..A11yState::default()
1446 };
1447
1448 let mut node = A11yNodeInfo::new(id, A11yRole::TextInput, area).with_state(state);
1449 if !name.is_empty() {
1450 node = node.with_name(name);
1451 }
1452 if self.mask_char.is_some() {
1453 node = node.with_description("password input");
1454 }
1455
1456 vec![node]
1457 }
1458}
1459
1460#[derive(Debug, Clone)]
1472pub struct TextInputSnapshot {
1473 value: String,
1474 cursor: usize,
1475 selection_anchor: Option<usize>,
1476}
1477
1478impl UndoSupport for TextInput {
1479 fn undo_widget_id(&self) -> UndoWidgetId {
1480 self.undo_id
1481 }
1482
1483 fn create_snapshot(&self) -> Box<dyn std::any::Any + Send> {
1484 Box::new(TextInputSnapshot {
1485 value: self.value.clone(),
1486 cursor: self.cursor,
1487 selection_anchor: self.selection_anchor,
1488 })
1489 }
1490
1491 fn restore_snapshot(&mut self, snapshot: &dyn std::any::Any) -> bool {
1492 if let Some(snap) = snapshot.downcast_ref::<TextInputSnapshot>() {
1493 self.value = snap.value.clone();
1494 self.cursor = snap.cursor;
1495 self.selection_anchor = snap.selection_anchor;
1496 self.scroll_cells.set(0); true
1498 } else {
1499 false
1500 }
1501 }
1502}
1503
1504impl TextInputUndoExt for TextInput {
1505 fn text_value(&self) -> &str {
1506 &self.value
1507 }
1508
1509 fn set_text_value(&mut self, value: &str) {
1510 self.value = value.to_string();
1511 let max = self.grapheme_count();
1512 self.cursor = self.cursor.min(max);
1513 self.selection_anchor = None;
1514 }
1515
1516 fn cursor_position(&self) -> usize {
1517 self.cursor
1518 }
1519
1520 fn set_cursor_position(&mut self, pos: usize) {
1521 let max = self.grapheme_count();
1522 self.cursor = pos.min(max);
1523 }
1524
1525 fn insert_text_at(&mut self, position: usize, text: &str) {
1526 let byte_offset = self.grapheme_byte_offset(position);
1527 self.value.insert_str(byte_offset, text);
1528 let inserted_graphemes = text.graphemes(true).count();
1529 if self.cursor >= position {
1530 self.cursor += inserted_graphemes;
1531 }
1532 }
1533
1534 fn delete_text_range(&mut self, start: usize, end: usize) {
1535 if start >= end {
1536 return;
1537 }
1538 let byte_start = self.grapheme_byte_offset(start);
1539 let byte_end = self.grapheme_byte_offset(end);
1540 self.value.drain(byte_start..byte_end);
1541 let deleted_count = end - start;
1542 if self.cursor > end {
1543 self.cursor -= deleted_count;
1544 } else if self.cursor > start {
1545 self.cursor = start;
1546 }
1547 let gc = self.grapheme_count();
1548 if self.cursor > gc {
1549 self.cursor = gc;
1550 }
1551 }
1552}
1553
1554impl TextInput {
1555 #[must_use]
1580 pub fn create_text_edit_command(
1581 &self,
1582 operation: TextEditOperation,
1583 ) -> Option<crate::undo_support::WidgetTextEditCmd> {
1584 Some(crate::undo_support::WidgetTextEditCmd::new(
1585 self.undo_id,
1586 operation,
1587 ))
1588 }
1589
1590 #[must_use]
1594 pub fn undo_id(&self) -> UndoWidgetId {
1595 self.undo_id
1596 }
1597}
1598
1599#[cfg(test)]
1600mod tests {
1601 use super::*;
1602 #[cfg(feature = "tracing")]
1603 use std::sync::{Arc, Mutex};
1604
1605 #[cfg(feature = "tracing")]
1606 use tracing::Subscriber;
1607 #[cfg(feature = "tracing")]
1608 use tracing_subscriber::Layer;
1609 #[cfg(feature = "tracing")]
1610 use tracing_subscriber::layer::{Context, SubscriberExt};
1611
1612 #[allow(dead_code)]
1613 fn cell_at(frame: &Frame, x: u16, y: u16) -> Cell {
1614 frame
1615 .buffer
1616 .get(x, y)
1617 .copied()
1618 .unwrap_or_else(|| panic!("test cell should exist at ({x},{y})"))
1619 }
1620
1621 fn raw_row_text(frame: &Frame, y: u16, width: u16) -> String {
1622 (0..width)
1623 .map(|x| {
1624 frame
1625 .buffer
1626 .get(x, y)
1627 .and_then(|cell| cell.content.as_char())
1628 .unwrap_or(' ')
1629 })
1630 .collect()
1631 }
1632
1633 #[cfg(feature = "tracing")]
1634 #[derive(Debug, Default)]
1635 struct InputTraceState {
1636 span_count: usize,
1637 has_cursor_position_field: bool,
1638 cursor_positions: Vec<usize>,
1639 operations: Vec<String>,
1640 }
1641
1642 #[cfg(feature = "tracing")]
1643 struct InputTraceCapture {
1644 state: Arc<Mutex<InputTraceState>>,
1645 }
1646
1647 #[cfg(feature = "tracing")]
1648 impl<S> Layer<S> for InputTraceCapture
1649 where
1650 S: Subscriber + for<'lookup> tracing_subscriber::registry::LookupSpan<'lookup>,
1651 {
1652 fn on_new_span(
1653 &self,
1654 attrs: &tracing::span::Attributes<'_>,
1655 _id: &tracing::Id,
1656 _ctx: Context<'_, S>,
1657 ) {
1658 if attrs.metadata().name() != "input.edit" {
1659 return;
1660 }
1661
1662 #[derive(Default)]
1663 struct InputEditVisitor {
1664 cursor_position: Option<usize>,
1665 operation: Option<String>,
1666 }
1667
1668 impl tracing::field::Visit for InputEditVisitor {
1669 fn record_i64(&mut self, field: &tracing::field::Field, value: i64) {
1670 if field.name() == "cursor_position" {
1671 self.cursor_position = usize::try_from(value).ok();
1672 }
1673 }
1674
1675 fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
1676 if field.name() == "cursor_position" {
1677 self.cursor_position = usize::try_from(value).ok();
1678 }
1679 }
1680
1681 fn record_debug(
1682 &mut self,
1683 field: &tracing::field::Field,
1684 value: &dyn std::fmt::Debug,
1685 ) {
1686 if field.name() == "operation" {
1687 self.operation = Some(format!("{value:?}").trim_matches('"').to_owned());
1688 }
1689 }
1690
1691 fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
1692 if field.name() == "operation" {
1693 self.operation = Some(value.to_owned());
1694 }
1695 }
1696 }
1697
1698 let fields = attrs.metadata().fields();
1699 let mut visitor = InputEditVisitor::default();
1700 attrs.record(&mut visitor);
1701
1702 let mut state = self.state.lock().expect("trace state lock");
1703 state.span_count += 1;
1704 state.has_cursor_position_field |= fields.field("cursor_position").is_some();
1705 if let Some(cursor) = visitor.cursor_position {
1706 state.cursor_positions.push(cursor);
1707 }
1708 if let Some(operation) = visitor.operation {
1709 state.operations.push(operation);
1710 }
1711 }
1712 }
1713
1714 #[allow(dead_code)]
1715 #[test]
1716 fn test_empty_input() {
1717 let input = TextInput::new();
1718 assert!(input.value().is_empty());
1719 assert_eq!(input.cursor(), 0);
1720 assert!(input.selected_text().is_none());
1721 }
1722
1723 #[test]
1724 fn test_with_value() {
1725 let mut input = TextInput::new().with_value("hello");
1726 input.set_focused(true);
1727 assert_eq!(input.value(), "hello");
1728 assert_eq!(input.cursor(), 5);
1729 }
1730
1731 #[test]
1732 fn test_set_value() {
1733 let mut input = TextInput::new().with_value("hello world");
1734 input.cursor = 11;
1735 input.set_value("hi");
1736 assert_eq!(input.value(), "hi");
1737 assert_eq!(input.cursor(), 2);
1738 }
1739
1740 #[test]
1741 fn test_clear() {
1742 let mut input = TextInput::new().with_value("hello");
1743 input.set_focused(true);
1744 input.clear();
1745 assert!(input.value().is_empty());
1746 assert_eq!(input.cursor(), 0);
1747 }
1748
1749 #[test]
1750 fn test_insert_char() {
1751 let mut input = TextInput::new();
1752 input.insert_char('a');
1753 input.insert_char('b');
1754 input.insert_char('c');
1755 assert_eq!(input.value(), "abc");
1756 assert_eq!(input.cursor(), 3);
1757 }
1758
1759 #[test]
1760 fn test_insert_char_mid() {
1761 let mut input = TextInput::new().with_value("ac");
1762 input.cursor = 1;
1763 input.insert_char('b');
1764 assert_eq!(input.value(), "abc");
1765 assert_eq!(input.cursor(), 2);
1766 }
1767
1768 #[test]
1769 fn test_max_length() {
1770 let mut input = TextInput::new().with_max_length(3);
1771 for c in "abcdef".chars() {
1772 input.insert_char(c);
1773 }
1774 assert_eq!(input.value(), "abc");
1775 assert_eq!(input.cursor(), 3);
1776 }
1777
1778 #[test]
1779 fn test_delete_char_back() {
1780 let mut input = TextInput::new().with_value("hello");
1781 input.delete_char_back();
1782 assert_eq!(input.value(), "hell");
1783 assert_eq!(input.cursor(), 4);
1784 }
1785
1786 #[test]
1787 fn test_delete_char_back_at_start() {
1788 let mut input = TextInput::new().with_value("hello");
1789 input.cursor = 0;
1790 input.delete_char_back();
1791 assert_eq!(input.value(), "hello");
1792 }
1793
1794 #[test]
1795 fn test_delete_char_forward() {
1796 let mut input = TextInput::new().with_value("hello");
1797 input.cursor = 0;
1798 input.delete_char_forward();
1799 assert_eq!(input.value(), "ello");
1800 assert_eq!(input.cursor(), 0);
1801 }
1802
1803 #[test]
1804 fn test_delete_char_forward_at_end() {
1805 let mut input = TextInput::new().with_value("hello");
1806 input.delete_char_forward();
1807 assert_eq!(input.value(), "hello");
1808 }
1809
1810 #[test]
1811 fn test_cursor_left_right() {
1812 let mut input = TextInput::new().with_value("hello");
1813 assert_eq!(input.cursor(), 5);
1814 input.move_cursor_left();
1815 assert_eq!(input.cursor(), 4);
1816 input.move_cursor_left();
1817 assert_eq!(input.cursor(), 3);
1818 input.move_cursor_right();
1819 assert_eq!(input.cursor(), 4);
1820 }
1821
1822 #[test]
1823 fn test_cursor_bounds() {
1824 let mut input = TextInput::new().with_value("hi");
1825 input.cursor = 0;
1826 input.move_cursor_left();
1827 assert_eq!(input.cursor(), 0);
1828 input.cursor = 2;
1829 input.move_cursor_right();
1830 assert_eq!(input.cursor(), 2);
1831 }
1832
1833 #[test]
1834 fn test_word_movement_left() {
1835 let mut input = TextInput::new().with_value("hello world test");
1836 input.move_cursor_word_left(false);
1839 assert_eq!(input.cursor(), 12); input.move_cursor_word_left(false);
1842 assert_eq!(input.cursor(), 6); input.move_cursor_word_left(false);
1845 assert_eq!(input.cursor(), 0); }
1847
1848 #[test]
1849 fn test_word_movement_right() {
1850 let mut input = TextInput::new().with_value("hello world test");
1851 input.cursor = 0;
1852 input.move_cursor_word_right(false);
1855 assert_eq!(input.cursor(), 6); input.move_cursor_word_right(false);
1858 assert_eq!(input.cursor(), 12); input.move_cursor_word_right(false);
1861 assert_eq!(input.cursor(), 16); }
1863
1864 #[test]
1865 fn test_word_movement_skips_punctuation() {
1866 let mut input = TextInput::new().with_value("hello, world");
1867 input.cursor = 0;
1868 input.move_cursor_word_right(false);
1871 assert_eq!(input.cursor(), 5); input.move_cursor_word_right(false);
1874 assert_eq!(input.cursor(), 7); input.move_cursor_word_right(false);
1877 assert_eq!(input.cursor(), 12); input.move_cursor_word_left(false);
1880 assert_eq!(input.cursor(), 7); }
1882
1883 #[test]
1884 fn test_delete_word_back() {
1885 let mut input = TextInput::new().with_value("hello world");
1886 input.delete_word_back();
1888 assert_eq!(input.value(), "hello "); input.delete_word_back();
1892 assert_eq!(input.value(), ""); }
1894
1895 #[test]
1896 fn test_delete_word_forward() {
1897 let mut input = TextInput::new().with_value("hello world");
1898 input.cursor = 0;
1899 input.delete_word_forward();
1901 assert_eq!(input.value(), "world"); input.delete_word_forward();
1904 assert_eq!(input.value(), ""); }
1906
1907 #[test]
1908 fn test_select_all() {
1909 let mut input = TextInput::new().with_value("hello");
1910 input.select_all();
1911 assert_eq!(input.selected_text(), Some("hello"));
1912 }
1913
1914 #[test]
1915 fn test_delete_selection() {
1916 let mut input = TextInput::new().with_value("hello world");
1917 input.selection_anchor = Some(0);
1918 input.cursor = 5;
1919 input.delete_selection();
1920 assert_eq!(input.value(), " world");
1921 assert_eq!(input.cursor(), 0);
1922 }
1923
1924 #[test]
1925 fn test_insert_replaces_selection() {
1926 let mut input = TextInput::new().with_value("hello");
1927 input.select_all();
1928 input.delete_selection();
1929 input.insert_char('x');
1930 assert_eq!(input.value(), "x");
1931 }
1932
1933 #[test]
1934 fn test_unicode_grapheme_handling() {
1935 let mut input = TextInput::new();
1936 input.set_value("café");
1937 assert_eq!(input.grapheme_count(), 4);
1938 input.cursor = 4;
1939 input.delete_char_back();
1940 assert_eq!(input.value(), "caf");
1941 }
1942
1943 #[test]
1944 fn test_multi_codepoint_grapheme_cursor_movement() {
1945 let mut input = TextInput::new().with_value("a👩💻b");
1946 assert_eq!(input.grapheme_count(), 3);
1947 assert_eq!(input.cursor(), 3);
1948
1949 input.move_cursor_left();
1950 assert_eq!(input.cursor(), 2);
1951 input.move_cursor_left();
1952 assert_eq!(input.cursor(), 1);
1953 input.move_cursor_left();
1954 assert_eq!(input.cursor(), 0);
1955
1956 input.move_cursor_right();
1957 assert_eq!(input.cursor(), 1);
1958 input.move_cursor_right();
1959 assert_eq!(input.cursor(), 2);
1960 input.move_cursor_right();
1961 assert_eq!(input.cursor(), 3);
1962 }
1963
1964 #[test]
1965 fn test_delete_back_multi_codepoint_grapheme() {
1966 let mut input = TextInput::new().with_value("a👩💻b");
1967 input.cursor = 2; input.delete_char_back();
1969 assert_eq!(input.value(), "ab");
1970 assert_eq!(input.cursor(), 1);
1971 assert_eq!(input.grapheme_count(), 2);
1972 }
1973
1974 #[test]
1975 fn test_ime_composition_start_update_commit() {
1976 let mut input = TextInput::new().with_value("ab");
1977 input.cursor = 1;
1978
1979 input.ime_start_composition();
1980 assert_eq!(input.ime_composition(), Some(""));
1981
1982 input.ime_update_composition("漢");
1983 assert_eq!(input.ime_composition(), Some("漢"));
1984
1985 assert!(input.ime_commit_composition());
1986 assert_eq!(input.ime_composition(), None);
1987 assert_eq!(input.value(), "a漢b");
1988 assert_eq!(input.cursor(), 2);
1989 }
1990
1991 #[test]
1992 fn test_ime_composition_cancel_keeps_value() {
1993 let mut input = TextInput::new().with_value("hello");
1994 input.ime_start_composition();
1995 input.ime_update_composition("👩💻");
1996 assert_eq!(input.ime_composition(), Some("👩💻"));
1997 assert!(input.ime_cancel_composition());
1998 assert_eq!(input.ime_composition(), None);
1999 assert_eq!(input.value(), "hello");
2000 assert_eq!(input.cursor(), 5);
2001 }
2002
2003 #[test]
2004 fn test_ime_commit_without_session_is_noop() {
2005 let mut input = TextInput::new().with_value("abc");
2006 assert!(!input.ime_commit_composition());
2007 assert_eq!(input.value(), "abc");
2008 assert_eq!(input.cursor(), 3);
2009 }
2010
2011 #[test]
2012 fn test_handle_event_ime_update_and_commit() {
2013 let mut input = TextInput::new().with_value("ab");
2014 input.cursor = 1;
2015
2016 assert!(input.handle_event(&Event::Ime(ImeEvent::start())));
2017 assert!(input.handle_event(&Event::Ime(ImeEvent::update("漢"))));
2018 assert_eq!(input.ime_composition(), Some("漢"));
2019 assert!(input.handle_event(&Event::Ime(ImeEvent::commit("漢"))));
2020 assert_eq!(input.ime_composition(), None);
2021 assert_eq!(input.value(), "a漢b");
2022 assert_eq!(input.cursor(), 2);
2023 }
2024
2025 #[test]
2026 fn test_handle_event_ime_cancel() {
2027 let mut input = TextInput::new().with_value("hello");
2028 input.cursor = 5;
2029 assert!(input.handle_event(&Event::Ime(ImeEvent::start())));
2030 assert!(input.handle_event(&Event::Ime(ImeEvent::update("👩💻"))));
2031 assert!(input.handle_event(&Event::Ime(ImeEvent::cancel())));
2032 assert_eq!(input.ime_composition(), None);
2033 assert_eq!(input.value(), "hello");
2034 assert_eq!(input.cursor(), 5);
2035 }
2036
2037 #[test]
2038 fn test_flag_emoji_grapheme_delete_and_cursor() {
2039 let mut input = TextInput::new().with_value("a🇺🇸b");
2040 assert_eq!(input.grapheme_count(), 3);
2041 input.cursor = 2;
2042 input.delete_char_back();
2043 assert_eq!(input.value(), "ab");
2044 assert_eq!(input.cursor(), 1);
2045 }
2046
2047 #[test]
2048 fn test_combining_grapheme_delete_and_cursor() {
2049 let mut input = TextInput::new().with_value("a\u{0301}b");
2050 assert_eq!(input.grapheme_count(), 2);
2051 input.cursor = 1;
2052 input.delete_char_back();
2053 assert_eq!(input.value(), "b");
2054 assert_eq!(input.cursor(), 0);
2055 }
2056
2057 #[test]
2058 fn test_bidi_logical_cursor_movement_over_graphemes() {
2059 let mut input = TextInput::new().with_value("AאבB");
2060 assert_eq!(input.grapheme_count(), 4);
2061
2062 input.move_cursor_left();
2063 assert_eq!(input.cursor(), 3);
2064 input.move_cursor_left();
2065 assert_eq!(input.cursor(), 2);
2066 input.move_cursor_left();
2067 assert_eq!(input.cursor(), 1);
2068 input.move_cursor_left();
2069 assert_eq!(input.cursor(), 0);
2070
2071 input.move_cursor_right();
2072 assert_eq!(input.cursor(), 1);
2073 input.move_cursor_right();
2074 assert_eq!(input.cursor(), 2);
2075 input.move_cursor_right();
2076 assert_eq!(input.cursor(), 3);
2077 input.move_cursor_right();
2078 assert_eq!(input.cursor(), 4);
2079 }
2080
2081 #[test]
2082 fn test_handle_event_char() {
2083 let mut input = TextInput::new();
2084 let event = Event::Key(KeyEvent::new(KeyCode::Char('a')));
2085 assert!(input.handle_event(&event));
2086 assert_eq!(input.value(), "a");
2087 }
2088
2089 #[test]
2090 fn test_handle_event_backspace() {
2091 let mut input = TextInput::new().with_value("ab");
2092 let event = Event::Key(KeyEvent::new(KeyCode::Backspace));
2093 assert!(input.handle_event(&event));
2094 assert_eq!(input.value(), "a");
2095 }
2096
2097 #[test]
2098 fn test_handle_event_ctrl_a() {
2099 let mut input = TextInput::new().with_value("hello");
2100 let event = Event::Key(KeyEvent::new(KeyCode::Char('a')).with_modifiers(Modifiers::CTRL));
2101 assert!(input.handle_event(&event));
2102 assert_eq!(input.selected_text(), Some("hello"));
2103 }
2104
2105 #[test]
2106 fn test_handle_event_ctrl_backspace() {
2107 let mut input = TextInput::new().with_value("hello world");
2108 let event = Event::Key(KeyEvent::new(KeyCode::Backspace).with_modifiers(Modifiers::CTRL));
2109 assert!(input.handle_event(&event));
2110 assert_eq!(input.value(), "hello ");
2111 }
2112
2113 #[test]
2114 fn test_handle_event_home_end() {
2115 let mut input = TextInput::new().with_value("hello");
2116 input.cursor = 3;
2117 let home = Event::Key(KeyEvent::new(KeyCode::Home));
2118 assert!(input.handle_event(&home));
2119 assert_eq!(input.cursor(), 0);
2120 let end = Event::Key(KeyEvent::new(KeyCode::End));
2121 assert!(input.handle_event(&end));
2122 assert_eq!(input.cursor(), 5);
2123 }
2124
2125 #[test]
2126 fn test_shift_left_creates_selection() {
2127 let mut input = TextInput::new().with_value("hello");
2128 let event = Event::Key(KeyEvent::new(KeyCode::Left).with_modifiers(Modifiers::SHIFT));
2129 assert!(input.handle_event(&event));
2130 assert_eq!(input.cursor(), 4);
2131 assert_eq!(input.selection_anchor, Some(5));
2132 assert_eq!(input.selected_text(), Some("o"));
2133 }
2134
2135 #[test]
2136 fn test_cursor_position() {
2137 let input = TextInput::new().with_value("hello");
2138 let area = Rect::new(10, 5, 20, 1);
2139 let (x, y) = input.cursor_position(area);
2140 assert_eq!(x, 15);
2141 assert_eq!(y, 5);
2142 }
2143
2144 #[test]
2145 fn test_cursor_position_empty() {
2146 let input = TextInput::new();
2147 let area = Rect::new(0, 0, 80, 1);
2148 let (x, y) = input.cursor_position(area);
2149 assert_eq!(x, 0);
2150 assert_eq!(y, 0);
2151 }
2152
2153 #[test]
2154 fn test_password_mask() {
2155 let input = TextInput::new().with_mask('*').with_value("secret");
2156 assert_eq!(input.value(), "secret");
2157 assert_eq!(input.cursor_visual_pos(), 6);
2158 }
2159
2160 #[test]
2161 fn test_render_basic() {
2162 use ftui_render::frame::Frame;
2163 use ftui_render::grapheme_pool::GraphemePool;
2164
2165 let input = TextInput::new().with_value("hi");
2166 let area = Rect::new(0, 0, 10, 1);
2167 let mut pool = GraphemePool::new();
2168 let mut frame = Frame::new(10, 1, &mut pool);
2169 input.render(area, &mut frame);
2170 let cell_h = cell_at(&frame, 0, 0);
2171 assert_eq!(cell_h.content.as_char(), Some('h'));
2172 let cell_i = cell_at(&frame, 1, 0);
2173 assert_eq!(cell_i.content.as_char(), Some('i'));
2174 }
2175
2176 #[test]
2177 fn test_render_sets_cursor_when_focused() {
2178 use ftui_render::frame::Frame;
2179 use ftui_render::grapheme_pool::GraphemePool;
2180
2181 let input = TextInput::new().with_value("hi").with_focused(true);
2182 let area = Rect::new(0, 0, 10, 1);
2183 let mut pool = GraphemePool::new();
2184 let mut frame = Frame::new(10, 1, &mut pool);
2185 input.render(area, &mut frame);
2186
2187 assert_eq!(frame.cursor_position, Some((2, 0)));
2188 assert!(frame.cursor_visible);
2189 }
2190
2191 #[test]
2192 fn test_render_does_not_set_cursor_when_unfocused() {
2193 use ftui_render::frame::Frame;
2194 use ftui_render::grapheme_pool::GraphemePool;
2195
2196 let input = TextInput::new().with_value("hi");
2197 let area = Rect::new(0, 0, 10, 1);
2198 let mut pool = GraphemePool::new();
2199 let mut frame = Frame::new(10, 1, &mut pool);
2200 input.render(area, &mut frame);
2201
2202 assert!(frame.cursor_position.is_none());
2203 }
2204
2205 #[test]
2206 fn test_render_grapheme_uses_pool() {
2207 use ftui_render::frame::Frame;
2208 use ftui_render::grapheme_pool::GraphemePool;
2209
2210 let grapheme = "👩💻";
2211 let input = TextInput::new().with_value(grapheme);
2212 let area = Rect::new(0, 0, 6, 1);
2213 let mut pool = GraphemePool::new();
2214 let mut frame = Frame::new(6, 1, &mut pool);
2215 input.render(area, &mut frame);
2216
2217 let cell = cell_at(&frame, 0, 0);
2218 assert!(cell.content.is_grapheme());
2219 let width = grapheme_width(grapheme);
2220 if width > 1 {
2221 assert!(cell_at(&frame, 1, 0).is_continuation());
2222 }
2223 }
2224
2225 #[test]
2226 fn test_render_shorter_value_clears_stale_suffix_and_owned_rows() {
2227 use ftui_render::frame::Frame;
2228 use ftui_render::grapheme_pool::GraphemePool;
2229
2230 let area = Rect::new(0, 0, 8, 2);
2231 let mut pool = GraphemePool::new();
2232 let mut frame = Frame::new(8, 2, &mut pool);
2233
2234 TextInput::new()
2235 .with_value("abcdef")
2236 .render(area, &mut frame);
2237 TextInput::new().with_value("xy").render(area, &mut frame);
2238
2239 assert_eq!(raw_row_text(&frame, 0, 8), "xy ");
2240 assert_eq!(raw_row_text(&frame, 1, 8), " ");
2241 }
2242
2243 #[test]
2244 fn test_left_collapses_selection() {
2245 let mut input = TextInput::new().with_value("hello");
2246 input.selection_anchor = Some(1);
2247 input.cursor = 4;
2248 input.move_cursor_left();
2249 assert_eq!(input.cursor(), 1);
2250 assert!(input.selection_anchor.is_none());
2251 }
2252
2253 #[test]
2254 fn test_right_collapses_selection() {
2255 let mut input = TextInput::new().with_value("hello");
2256 input.selection_anchor = Some(1);
2257 input.cursor = 4;
2258 input.move_cursor_right();
2259 assert_eq!(input.cursor(), 4);
2260 assert!(input.selection_anchor.is_none());
2261 }
2262
2263 #[test]
2264 fn test_render_sets_frame_cursor() {
2265 use ftui_render::frame::Frame;
2266 use ftui_render::grapheme_pool::GraphemePool;
2267
2268 let input = TextInput::new().with_value("hello").with_focused(true);
2269 let area = Rect::new(5, 3, 20, 1);
2270 let mut pool = GraphemePool::new();
2271 let mut frame = Frame::new(30, 10, &mut pool);
2272 input.render(area, &mut frame);
2273
2274 assert_eq!(frame.cursor_position, Some((10, 3)));
2278 }
2279
2280 #[test]
2281 fn test_render_cursor_mid_text() {
2282 use ftui_render::frame::Frame;
2283 use ftui_render::grapheme_pool::GraphemePool;
2284
2285 let mut input = TextInput::new().with_value("hello").with_focused(true);
2286 input.cursor = 2; let area = Rect::new(0, 0, 20, 1);
2288 let mut pool = GraphemePool::new();
2289 let mut frame = Frame::new(20, 1, &mut pool);
2290 input.render(area, &mut frame);
2291
2292 assert_eq!(frame.cursor_position, Some((2, 0)));
2294 }
2295
2296 #[test]
2301 fn test_undo_widget_id_is_stable() {
2302 let input = TextInput::new();
2303 let id1 = input.undo_id();
2304 let id2 = input.undo_id();
2305 assert_eq!(id1, id2);
2306 }
2307
2308 #[test]
2309 fn test_undo_widget_id_unique_per_instance() {
2310 let input1 = TextInput::new();
2311 let input2 = TextInput::new();
2312 assert_ne!(input1.undo_id(), input2.undo_id());
2313 }
2314
2315 #[test]
2316 fn test_snapshot_and_restore() {
2317 let mut input = TextInput::new().with_value("hello");
2318 input.cursor = 3;
2319 input.selection_anchor = Some(1);
2320
2321 let snapshot = input.create_snapshot();
2322
2323 input.set_value("world");
2325 input.cursor = 5;
2326 input.selection_anchor = None;
2327
2328 assert_eq!(input.value(), "world");
2329 assert_eq!(input.cursor(), 5);
2330
2331 assert!(input.restore_snapshot(snapshot.as_ref()));
2333 assert_eq!(input.value(), "hello");
2334 assert_eq!(input.cursor(), 3);
2335 assert_eq!(input.selection_anchor, Some(1));
2336 }
2337
2338 #[test]
2339 fn test_text_input_undo_ext_insert() {
2340 let mut input = TextInput::new().with_value("hello");
2341 input.cursor = 2;
2342
2343 input.insert_text_at(2, " world");
2344 assert_eq!(input.value(), "he worldllo");
2346 assert_eq!(input.cursor(), 8); }
2348
2349 #[test]
2350 fn test_text_input_undo_ext_delete() {
2351 let mut input = TextInput::new().with_value("hello world");
2352 input.cursor = 8;
2353
2354 input.delete_text_range(5, 11); assert_eq!(input.value(), "hello");
2356 assert_eq!(input.cursor(), 5); }
2358
2359 #[test]
2360 fn test_create_text_edit_command() {
2361 let input = TextInput::new().with_value("hello");
2362 let cmd = input.create_text_edit_command(TextEditOperation::Insert {
2363 position: 0,
2364 text: "hi".to_string(),
2365 });
2366 assert!(cmd.is_some());
2367 let cmd = cmd.expect("test command should exist");
2368 assert_eq!(cmd.widget_id(), input.undo_id());
2369 assert_eq!(cmd.description(), "Insert text");
2370 }
2371
2372 #[test]
2373 fn command_chords_do_not_type_their_letter() {
2374 for ch in ['v', 'c', 'x'] {
2377 let mut input = TextInput::new();
2378 input.handle_event(&Event::Key(
2379 KeyEvent::new(KeyCode::Char(ch)).with_modifiers(Modifiers::SUPER),
2380 ));
2381 assert_eq!(input.value(), "", "Cmd+{ch} typed into the field");
2382 }
2383 let mut input = TextInput::new();
2385 input.handle_event(&Event::Key(KeyEvent::new(KeyCode::Char('v'))));
2386 assert_eq!(input.value(), "v");
2387 }
2388
2389 #[test]
2390 fn test_paste_bulk_insert() {
2391 let mut input = TextInput::new().with_value("hello");
2392 input.cursor = 5;
2393 let event = Event::Paste(ftui_core::event::PasteEvent::bracketed(" world"));
2394 assert!(input.handle_event(&event));
2395 assert_eq!(input.value(), "hello world");
2396 assert_eq!(input.cursor(), 11);
2397 }
2398
2399 #[test]
2400 fn test_paste_multi_grapheme_sequence() {
2401 let mut input = TextInput::new().with_value("hi");
2402 input.cursor = 2;
2403 let event = Event::Paste(ftui_core::event::PasteEvent::new("👩💻🔥", false));
2404 assert!(input.handle_event(&event));
2405 assert_eq!(input.value(), "hi👩💻🔥");
2406 assert_eq!(input.cursor(), 4);
2407 }
2408
2409 #[test]
2410 fn test_paste_max_length() {
2411 let mut input = TextInput::new().with_value("abc").with_max_length(5);
2412 input.cursor = 3;
2413 let event = Event::Paste(ftui_core::event::PasteEvent::bracketed("def"));
2415 assert!(input.handle_event(&event));
2416 assert_eq!(input.value(), "abcde");
2417 assert_eq!(input.cursor(), 5);
2418 }
2419
2420 #[test]
2421 fn test_paste_combining_merge() {
2422 let mut input = TextInput::new().with_value("e");
2423 input.cursor = 1;
2424 let event = Event::Paste(ftui_core::event::PasteEvent::bracketed("\u{0301}"));
2427 assert!(input.handle_event(&event));
2428 assert_eq!(input.value(), "e\u{0301}");
2429 assert_eq!(input.grapheme_count(), 1);
2430 assert_eq!(input.cursor(), 1);
2431 }
2432
2433 #[test]
2434 fn test_paste_combining_merge_mid_string() {
2435 let mut input = TextInput::new().with_value("ab");
2436 input.cursor = 1; let event = Event::Paste(ftui_core::event::PasteEvent::bracketed("\u{0301}"));
2438 assert!(input.handle_event(&event));
2439 assert_eq!(input.value(), "a\u{0301}b");
2440 assert_eq!(input.grapheme_count(), 2);
2441 assert_eq!(input.cursor(), 1);
2442 }
2443
2444 #[test]
2445 fn test_wide_char_scroll_visibility() {
2446 use ftui_render::frame::Frame;
2447 use ftui_render::grapheme_pool::GraphemePool;
2448
2449 let wide_char = "\u{3000}"; let mut input = TextInput::new().with_value(wide_char).with_focused(true);
2451 input.cursor = 1; let area = Rect::new(0, 0, 2, 1);
2459 let mut pool = GraphemePool::new();
2460 let mut frame = Frame::new(2, 1, &mut pool);
2461 input.render(area, &mut frame);
2462
2463 let cell = cell_at(&frame, 0, 0);
2464 assert!(!cell.is_empty(), "Wide char should be visible");
2466 }
2467
2468 #[test]
2469 fn test_wide_char_scroll_snapping() {
2470 let _input = TextInput::new().with_value("a\u{3000}b"); let wide_char = "\u{3000}";
2501 let text = format!("a{wide_char}b");
2502 let mut input = TextInput::new().with_value(&text);
2503
2504 input.cursor = 3; let _area = Rect::new(0, 0, 2, 1); }
2601
2602 #[cfg(feature = "tracing")]
2603 #[test]
2604 fn tracing_input_edit_span_tracks_cursor_positions() {
2605 let state = Arc::new(Mutex::new(InputTraceState::default()));
2606 let _trace_test_guard = crate::tracing_test_support::acquire();
2607 let subscriber = tracing_subscriber::registry().with(InputTraceCapture {
2608 state: Arc::clone(&state),
2609 });
2610 let _guard = tracing::subscriber::set_default(subscriber);
2611 tracing::callsite::rebuild_interest_cache();
2612
2613 let mut input = TextInput::new().with_value("ab");
2614 tracing::callsite::rebuild_interest_cache();
2615 assert!(input.handle_event(&Event::Key(KeyEvent::new(KeyCode::Char('c')))));
2616 tracing::callsite::rebuild_interest_cache();
2617 assert!(input.handle_event(&Event::Key(KeyEvent::new(KeyCode::Left))));
2618 tracing::callsite::rebuild_interest_cache();
2619 assert!(input.handle_event(&Event::Key(KeyEvent::new(KeyCode::Backspace))));
2620
2621 tracing::callsite::rebuild_interest_cache();
2622 let snapshot = state.lock().expect("trace state lock");
2623 assert!(
2624 snapshot.span_count >= 3,
2625 "expected at least 3 input.edit spans, got {}",
2626 snapshot.span_count
2627 );
2628 assert!(
2629 snapshot.has_cursor_position_field,
2630 "input.edit span missing cursor_position field"
2631 );
2632 assert_eq!(
2633 snapshot.cursor_positions,
2634 vec![3, 2, 1],
2635 "expected cursor positions after insert/left/backspace"
2636 );
2637 assert!(
2638 snapshot.operations.starts_with(&[
2639 "insert_char".to_string(),
2640 "move_left".to_string(),
2641 "delete_back".to_string()
2642 ]),
2643 "unexpected operations: {:?}",
2644 snapshot.operations
2645 );
2646 }
2647}
2648
2649#[cfg(test)]
2650mod scroll_edge_tests {
2651 use super::*;
2652 use ftui_render::frame::Frame;
2653 use ftui_render::grapheme_pool::GraphemePool;
2654
2655 #[test]
2656 fn test_scroll_snap_left_cursor_visibility() {
2657 let mut input = TextInput::new().with_value("ABC");
2665 input.cursor = 1; let area = Rect::new(0, 0, 1, 1);
2670 let mut pool = GraphemePool::new();
2671 let mut frame = Frame::new(1, 1, &mut pool);
2672 input.render(area, &mut frame); input.move_cursor_left(); input.render(area, &mut frame);
2679
2680 let cell = frame.buffer.get(0, 0).unwrap();
2682 assert_eq!(cell.content.as_char(), Some('A'));
2683 }
2684
2685 #[test]
2686 fn test_max_length_replacement_failure() {
2687 let mut input = TextInput::new().with_value("abc").with_max_length(3);
2693 input.selection_anchor = Some(1); input.cursor = 2; let event = Event::Paste(ftui_core::event::PasteEvent::new("de", false));
2698 input.handle_event(&event);
2699
2700 assert_eq!(input.value(), "abc");
2702 assert_eq!(input.cursor(), 2);
2703 assert_eq!(input.selection_anchor, Some(1));
2704 }
2705
2706 mod history_tests {
2707 use super::*;
2708 use proptest::prelude::*;
2709
2710 fn key(code: KeyCode) -> Event {
2711 Event::Key(KeyEvent::new(code))
2712 }
2713
2714 fn typ(input: &mut TextInput, s: &str) {
2715 for c in s.chars() {
2716 input.handle_event(&key(KeyCode::Char(c)));
2717 }
2718 }
2719
2720 fn submit_and_clear(input: &mut TextInput) {
2723 input.handle_event(&key(KeyCode::Enter));
2724 input.clear();
2725 }
2726
2727 fn up(input: &mut TextInput) -> bool {
2728 input.handle_event(&key(KeyCode::Up))
2729 }
2730
2731 fn down(input: &mut TextInput) -> bool {
2732 input.handle_event(&key(KeyCode::Down))
2733 }
2734
2735 #[test]
2736 fn up_recalls_previous_entry() {
2737 let mut input = TextInput::new().with_history(10);
2738 typ(&mut input, "one");
2739 submit_and_clear(&mut input);
2740 typ(&mut input, "two");
2741 submit_and_clear(&mut input);
2742
2743 assert!(up(&mut input));
2744 assert_eq!(input.value(), "two");
2745 assert!(up(&mut input));
2746 assert_eq!(input.value(), "one");
2747 assert!(!up(&mut input));
2750 assert_eq!(input.value(), "one");
2751 assert_eq!(input.history().collect::<Vec<_>>(), vec!["one", "two"]);
2752 }
2753
2754 #[test]
2755 fn down_returns_to_draft() {
2756 let mut input = TextInput::new().with_history(10);
2757 typ(&mut input, "one");
2758 submit_and_clear(&mut input);
2759 typ(&mut input, "two");
2760 submit_and_clear(&mut input);
2761 typ(&mut input, "dr");
2763
2764 assert!(up(&mut input));
2765 assert_eq!(input.value(), "two");
2766 assert!(up(&mut input));
2767 assert_eq!(input.value(), "one");
2768 assert!(down(&mut input));
2769 assert_eq!(input.value(), "two");
2770 assert!(down(&mut input));
2771 assert_eq!(
2772 input.value(),
2773 "dr",
2774 "past the newest entry the draft returns"
2775 );
2776 assert!(!down(&mut input));
2778 assert_eq!(input.value(), "dr");
2779 }
2780
2781 #[test]
2782 fn history_dedups_consecutive() {
2783 let mut input = TextInput::new().with_history(10);
2784 for value in ["a", "a", "b", "a"] {
2785 input.set_value(value);
2786 input.push_history();
2787 }
2788 assert_eq!(input.history().collect::<Vec<_>>(), vec!["a", "b", "a"]);
2790 }
2791
2792 #[test]
2793 fn history_caps_at_capacity() {
2794 let mut input = TextInput::new().with_history(3);
2795 for value in ["a", "b", "c", "d", "e"] {
2796 input.set_value(value);
2797 input.push_history();
2798 }
2799 assert_eq!(input.history_capacity(), Some(3));
2800 assert_eq!(input.history().collect::<Vec<_>>(), vec!["c", "d", "e"]);
2801 }
2802
2803 #[test]
2804 fn submit_resets_cursor() {
2805 let mut input = TextInput::new().with_history(10);
2806 typ(&mut input, "aa");
2807 submit_and_clear(&mut input);
2808 typ(&mut input, "bb");
2809 submit_and_clear(&mut input);
2810
2811 assert!(up(&mut input));
2813 assert_eq!(input.value(), "bb");
2814 assert!(up(&mut input));
2815 assert_eq!(input.value(), "aa");
2816
2817 submit_and_clear(&mut input);
2821 assert!(up(&mut input));
2822 assert_eq!(input.value(), "aa", "recall restarts at the newest entry");
2823 assert!(up(&mut input));
2826 assert_eq!(input.value(), "bb");
2827 }
2828
2829 #[test]
2830 fn typing_after_recall_clears_cursor() {
2831 let mut input = TextInput::new().with_history(10);
2832 typ(&mut input, "one");
2833 submit_and_clear(&mut input);
2834 typ(&mut input, "two");
2835 submit_and_clear(&mut input);
2836
2837 assert!(up(&mut input));
2838 assert_eq!(input.value(), "two");
2839 typ(&mut input, "x");
2842 assert_eq!(input.value(), "twox");
2843 assert!(up(&mut input));
2844 assert_eq!(input.value(), "two", "Up restarts recall from the newest");
2845 assert!(down(&mut input));
2846 assert_eq!(
2847 input.value(),
2848 "twox",
2849 "Down past the newest restores the edited draft"
2850 );
2851 }
2852
2853 #[test]
2854 fn empty_submit_not_recorded() {
2855 let mut input = TextInput::new().with_history(10);
2856 input.handle_event(&key(KeyCode::Enter));
2858 typ(&mut input, "x");
2859 submit_and_clear(&mut input);
2860 assert_eq!(input.history().collect::<Vec<_>>(), vec!["x"]);
2861 }
2862
2863 #[test]
2864 fn whitespace_submit_recorded_as_is() {
2865 let mut input = TextInput::new().with_history(10);
2866 input.set_value(" ");
2867 input.push_history();
2868 assert_eq!(input.history().collect::<Vec<_>>(), vec![" "]);
2869 }
2870
2871 #[test]
2872 fn set_value_does_not_touch_history() {
2873 let mut input = TextInput::new().with_history(10);
2874 typ(&mut input, "first");
2875 submit_and_clear(&mut input);
2876 input.set_value("zzz");
2877 assert_eq!(input.history().collect::<Vec<_>>(), vec!["first"]);
2878 assert!(up(&mut input));
2880 assert_eq!(input.value(), "first");
2881 }
2882
2883 #[test]
2884 fn no_history_leaves_updown_unconsumed() {
2885 let mut input = TextInput::new().with_value("hello");
2886 assert!(!input.handle_event(&key(KeyCode::Up)));
2887 assert_eq!(input.value(), "hello");
2888 assert!(!input.handle_event(&key(KeyCode::Down)));
2889 assert_eq!(input.value(), "hello");
2890 assert_eq!(input.history_capacity(), None);
2891 }
2892
2893 #[test]
2894 fn no_history_leaves_arrows_for_the_parent() {
2895 let mut input = TextInput::new();
2898 assert!(!input.handle_event(&key(KeyCode::Up)));
2899 assert!(!input.handle_event(&key(KeyCode::Down)));
2900 assert!(!input.handle_event(&key(KeyCode::Enter)));
2901 assert_eq!(input.history_capacity(), None);
2902 }
2903
2904 proptest! {
2905 #![proptest_config(ProptestConfig::with_cases(512))]
2906
2907 #[test]
2910 fn updown_sequences_never_panic_and_end_in_draft(
2911 entries in prop::collection::vec("[a-c]{1,3}", 0..=10),
2912 draft in "[a-c]{0,3}",
2913 steps in prop::collection::vec(any::<bool>(), 0..50),
2914 ) {
2915 let mut input = TextInput::new().with_history(16);
2916 for entry in &entries {
2917 input.set_value(entry.clone());
2918 input.push_history();
2919 }
2920 input.clear();
2921 input.set_value(draft.clone());
2922
2923 let history_entries: Vec<String> = input.history().map(String::from).collect();
2924
2925 for is_up in steps {
2926 if is_up {
2927 input.handle_event(&key(KeyCode::Up));
2928 } else {
2929 input.handle_event(&key(KeyCode::Down));
2930 }
2931 let current = input.value();
2932 prop_assert!(
2933 current == draft.as_str() || history_entries.iter().any(|e| e == current),
2934 "value {:?} not in history or draft",
2935 current
2936 );
2937 }
2938 for _ in 0..(history_entries.len() + 2) {
2940 input.handle_event(&key(KeyCode::Down));
2941 }
2942 prop_assert_eq!(input.value(), draft.as_str());
2943 }
2944 }
2945
2946 #[test]
2951 fn input_rtl_keys_move_in_logical_order_like_the_renderer() {
2952 let mut input = TextInput::new().with_value("\u{0645}\u{0631}\u{062D}\u{0628}\u{0627}");
2954 input.cursor = 0;
2955
2956 input.handle_event(&key(KeyCode::Right));
2957 assert_eq!(input.cursor, 1);
2958 assert_eq!(input.cursor_visual_pos(), 1);
2959
2960 input.handle_event(&key(KeyCode::Left));
2961 assert_eq!(input.cursor, 0);
2962 assert_eq!(input.cursor_visual_pos(), 0);
2963
2964 input.handle_event(&key(KeyCode::End));
2965 assert_eq!(input.cursor, 5);
2966 assert_eq!(input.cursor_visual_pos(), 5);
2967
2968 input.handle_event(&key(KeyCode::Home));
2969 assert_eq!(input.cursor, 0);
2970 }
2971
2972 #[test]
2973 fn input_mixed_bidi_cluster_caret_matches_logical_render() {
2974 let mut input = TextInput::new().with_value("a\u{0301} \u{05D0}\u{05D1}");
2976 input.cursor = 0;
2977 input.handle_event(&key(KeyCode::Right));
2978 input.handle_event(&key(KeyCode::Right));
2979 assert_eq!(input.cursor, 2);
2980 assert_eq!(input.cursor_visual_pos(), 2);
2981 let mut input = TextInput::new()
2983 .with_value("x\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467} \u{05D0}");
2984 input.cursor = 2;
2985 assert_eq!(input.cursor_visual_pos(), 3);
2986 }
2987 }
2988}