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 changed = match key.code {
577 KeyCode::Char(c) if !ctrl => {
578 self.insert_char(c);
579 true
580 }
581 KeyCode::Char('a') if ctrl => {
583 self.select_all();
584 true
585 }
586 KeyCode::Char('w') if ctrl => {
588 self.delete_word_back();
589 true
590 }
591 KeyCode::Backspace => {
592 if self.selection_anchor.is_some() {
593 self.delete_selection();
594 } else if ctrl {
595 self.delete_word_back();
596 } else {
597 self.delete_char_back();
598 }
599 true
600 }
601 KeyCode::Delete => {
602 if self.selection_anchor.is_some() {
603 self.delete_selection();
604 } else if ctrl {
605 self.delete_word_forward();
606 } else {
607 self.delete_char_forward();
608 }
609 true
610 }
611 KeyCode::Left => {
612 if ctrl {
613 self.move_cursor_word_left(shift);
614 } else if shift {
615 self.move_cursor_left_select();
616 } else {
617 self.move_cursor_left();
618 }
619 true
620 }
621 KeyCode::Right => {
622 if ctrl {
623 self.move_cursor_word_right(shift);
624 } else if shift {
625 self.move_cursor_right_select();
626 } else {
627 self.move_cursor_right();
628 }
629 true
630 }
631 KeyCode::Home => {
632 if shift {
633 self.ensure_selection_anchor();
634 } else {
635 self.selection_anchor = None;
636 }
637 self.cursor = 0;
638 self.scroll_cells.set(0);
639 true
640 }
641 KeyCode::End => {
642 if shift {
643 self.ensure_selection_anchor();
644 } else {
645 self.selection_anchor = None;
646 }
647 self.cursor = self.grapheme_count();
648 true
649 }
650 _ => false,
651 };
652
653 if let Some(before) = value_before
656 && self.value != before
657 && let Some(history) = self.history.as_mut()
658 {
659 history.note_edit();
660 }
661
662 changed
663 }
664
665 #[cfg(feature = "tracing")]
666 fn trace_edit(&self, operation: &'static str) {
667 let _span = tracing::debug_span!(
668 "input.edit",
669 operation,
670 cursor_position = self.cursor,
671 grapheme_count = self.grapheme_count(),
672 has_selection = self.selection_anchor.is_some()
673 )
674 .entered();
675 }
676
677 #[cfg(feature = "tracing")]
678 fn event_operation_name(event: &Event) -> &'static str {
679 match event {
680 Event::Key(key) => Self::key_operation_name(key),
681 Event::Paste(_) => "paste",
682 Event::Ime(ime) => match ime.phase {
683 ImePhase::Start => "ime_start",
684 ImePhase::Update => "ime_update",
685 ImePhase::Commit => "ime_commit",
686 ImePhase::Cancel => "ime_cancel",
687 },
688 Event::Resize { .. } => "resize",
689 Event::Focus(_) => "focus",
690 Event::Mouse(_) => "mouse",
691 Event::Clipboard(_) => "clipboard",
692 Event::Tick => "tick",
693 }
694 }
695
696 #[cfg(feature = "tracing")]
697 fn key_operation_name(key: &KeyEvent) -> &'static str {
698 let ctrl = key.modifiers.contains(Modifiers::CTRL);
699 let shift = key.modifiers.contains(Modifiers::SHIFT);
700
701 match key.code {
702 KeyCode::Char(_) if !ctrl => "insert_char",
703 KeyCode::Char('a') if ctrl => "select_all",
704 KeyCode::Char('w') if ctrl => "delete_word_back",
705 KeyCode::Backspace if ctrl => "delete_word_back",
706 KeyCode::Backspace => "delete_back",
707 KeyCode::Delete if ctrl => "delete_word_forward",
708 KeyCode::Delete => "delete_forward",
709 KeyCode::Left if ctrl && shift => "move_word_left_select",
710 KeyCode::Left if ctrl => "move_word_left",
711 KeyCode::Left if shift => "move_left_select",
712 KeyCode::Left => "move_left",
713 KeyCode::Right if ctrl && shift => "move_word_right_select",
714 KeyCode::Right if ctrl => "move_word_right",
715 KeyCode::Right if shift => "move_right_select",
716 KeyCode::Right => "move_right",
717 KeyCode::Home if shift => "move_home_select",
718 KeyCode::Home => "move_home",
719 KeyCode::End if shift => "move_end_select",
720 KeyCode::End => "move_end",
721 _ => "key_other",
722 }
723 }
724
725 fn sanitize_input_text(text: &str) -> String {
728 text.chars()
730 .map(|c| {
731 if c == '\n' || c == '\r' || c == '\t' {
732 ' '
733 } else {
734 c
735 }
736 })
737 .filter(|c| !c.is_control())
738 .collect()
739 }
740
741 pub fn insert_text(&mut self, text: &str) {
749 self.delete_selection();
750
751 let clean_text = Self::sanitize_input_text(text);
752
753 if clean_text.is_empty() {
754 return;
755 }
756
757 let current_count = self.grapheme_count();
758 let avail = if let Some(max) = self.max_length {
759 if current_count >= max {
760 1
762 } else {
763 max - current_count
764 }
765 } else {
766 usize::MAX
767 };
768
769 let new_graphemes = clean_text.graphemes(true).count();
771 let to_insert = if new_graphemes > avail {
772 let end_byte = clean_text
774 .grapheme_indices(true)
775 .map(|(i, _)| i)
776 .nth(avail)
777 .unwrap_or(clean_text.len());
778 &clean_text[..end_byte]
779 } else {
780 clean_text.as_str()
781 };
782
783 if to_insert.is_empty() {
784 return;
785 }
786
787 let byte_offset = self.grapheme_byte_offset(self.cursor);
788 self.value.insert_str(byte_offset, to_insert);
789
790 let new_total = self.grapheme_count();
792 if let Some(max) = self.max_length
793 && new_total > max
794 {
795 self.value.drain(byte_offset..byte_offset + to_insert.len());
797 return;
798 }
799
800 self.cursor = self
801 .value
802 .grapheme_indices(true)
803 .take_while(|(i, _)| *i < byte_offset + to_insert.len())
804 .count();
805 }
806
807 fn insert_char(&mut self, c: char) {
808 if c.is_control() {
810 return;
811 }
812
813 self.delete_selection();
814
815 let byte_offset = self.grapheme_byte_offset(self.cursor);
816 self.value.insert(byte_offset, c);
817
818 let new_count = self.grapheme_count();
819
820 if let Some(max) = self.max_length
822 && new_count > max
823 {
824 let char_len = c.len_utf8();
826 self.value.drain(byte_offset..byte_offset + char_len);
827 return;
828 }
829
830 let char_len = c.len_utf8();
831 self.cursor = self
832 .value
833 .grapheme_indices(true)
834 .take_while(|(i, _)| *i < byte_offset + char_len)
835 .count();
836 }
837
838 fn delete_char_back(&mut self) {
839 if self.cursor > 0 {
840 let byte_start = self.grapheme_byte_offset(self.cursor - 1);
841 let byte_end = self.grapheme_byte_offset(self.cursor);
842 self.value.drain(byte_start..byte_end);
843 self.cursor -= 1;
844 let gc = self.grapheme_count();
845 if self.cursor > gc {
846 self.cursor = gc;
847 }
848 }
849 }
850
851 fn delete_char_forward(&mut self) {
852 let count = self.grapheme_count();
853 if self.cursor < count {
854 let byte_start = self.grapheme_byte_offset(self.cursor);
855 let byte_end = self.grapheme_byte_offset(self.cursor + 1);
856 self.value.drain(byte_start..byte_end);
857 let gc = self.grapheme_count();
858 if self.cursor > gc {
859 self.cursor = gc;
860 }
861 }
862 }
863
864 fn delete_word_back(&mut self) {
865 if self.cursor == 0 {
866 return;
867 }
868
869 let old_cursor = self.cursor;
870 self.move_cursor_word_left(false);
872 let new_cursor = self.cursor;
873
874 if new_cursor < old_cursor {
875 let byte_start = self.grapheme_byte_offset(new_cursor);
876 let byte_end = self.grapheme_byte_offset(old_cursor);
877 self.value.drain(byte_start..byte_end);
878 self.cursor = new_cursor;
879 let gc = self.grapheme_count();
880 if self.cursor > gc {
881 self.cursor = gc;
882 }
883 }
884 }
885
886 fn delete_word_forward(&mut self) {
887 let old_cursor = self.cursor;
888 self.move_cursor_word_right(false);
890 let new_cursor = self.cursor;
891 self.cursor = old_cursor;
893
894 if new_cursor > old_cursor {
895 let byte_start = self.grapheme_byte_offset(old_cursor);
896 let byte_end = self.grapheme_byte_offset(new_cursor);
897 self.value.drain(byte_start..byte_end);
898 let gc = self.grapheme_count();
899 if self.cursor > gc {
900 self.cursor = gc;
901 }
902 }
903 }
904
905 pub fn select_all(&mut self) {
909 self.selection_anchor = Some(0);
910 self.cursor = self.grapheme_count();
911 }
912
913 fn delete_selection(&mut self) {
915 if let Some(anchor) = self.selection_anchor.take() {
916 let (start, end) = self.selection_range(anchor);
917 let byte_start = self.grapheme_byte_offset(start);
918 let byte_end = self.grapheme_byte_offset(end);
919 self.value.drain(byte_start..byte_end);
920 self.cursor = start;
921 let gc = self.grapheme_count();
922 if self.cursor > gc {
923 self.cursor = gc;
924 }
925 }
926 }
927
928 fn ensure_selection_anchor(&mut self) {
929 if self.selection_anchor.is_none() {
930 self.selection_anchor = Some(self.cursor);
931 }
932 }
933
934 fn selection_range(&self, anchor: usize) -> (usize, usize) {
935 if anchor <= self.cursor {
936 (anchor, self.cursor)
937 } else {
938 (self.cursor, anchor)
939 }
940 }
941
942 fn is_in_selection(&self, grapheme_idx: usize) -> bool {
943 if let Some(anchor) = self.selection_anchor {
944 let (start, end) = self.selection_range(anchor);
945 grapheme_idx >= start && grapheme_idx < end
946 } else {
947 false
948 }
949 }
950
951 fn move_cursor_left(&mut self) {
954 if let Some(anchor) = self.selection_anchor.take() {
955 self.cursor = self.cursor.min(anchor);
956 } else if self.cursor > 0 {
957 self.cursor -= 1;
958 }
959 }
960
961 fn move_cursor_right(&mut self) {
962 if let Some(anchor) = self.selection_anchor.take() {
963 self.cursor = self.cursor.max(anchor);
964 } else if self.cursor < self.grapheme_count() {
965 self.cursor += 1;
966 }
967 }
968
969 fn move_cursor_left_select(&mut self) {
970 self.ensure_selection_anchor();
971 if self.cursor > 0 {
972 self.cursor -= 1;
973 }
974 }
975
976 fn move_cursor_right_select(&mut self) {
977 self.ensure_selection_anchor();
978 if self.cursor < self.grapheme_count() {
979 self.cursor += 1;
980 }
981 }
982
983 fn get_grapheme_class(g: &str) -> u8 {
984 if g.chars().all(char::is_whitespace) {
985 0
986 } else if g.chars().any(char::is_alphanumeric) {
987 1
988 } else {
989 2
990 }
991 }
992
993 fn move_cursor_word_left(&mut self, select: bool) {
994 if select {
995 self.ensure_selection_anchor();
996 } else {
997 self.selection_anchor = None;
998 }
999
1000 if self.cursor == 0 {
1001 return;
1002 }
1003
1004 let byte_offset = self.grapheme_byte_offset(self.cursor);
1005 let before_cursor = &self.value[..byte_offset];
1006 let mut pos = self.cursor;
1007
1008 let mut iter = before_cursor.graphemes(true).rev();
1009
1010 while let Some(g) = iter.next() {
1011 if Self::get_grapheme_class(g) == 0 {
1012 pos = pos.saturating_sub(1);
1013 } else {
1014 pos = pos.saturating_sub(1);
1015 let target = Self::get_grapheme_class(g);
1016 for g_next in iter {
1017 if Self::get_grapheme_class(g_next) == target {
1018 pos = pos.saturating_sub(1);
1019 } else {
1020 break;
1021 }
1022 }
1023 break;
1024 }
1025 }
1026
1027 self.cursor = pos;
1028 }
1029
1030 fn move_cursor_word_right(&mut self, select: bool) {
1031 if select {
1032 self.ensure_selection_anchor();
1033 } else {
1034 self.selection_anchor = None;
1035 }
1036
1037 let mut iter = self.value.graphemes(true).peekable();
1038 for _ in 0..self.cursor {
1039 iter.next();
1040 }
1041
1042 let mut pos = self.cursor;
1043
1044 if let Some(&g) = iter.peek() {
1045 let start_class = Self::get_grapheme_class(g);
1046 if start_class != 0 {
1047 while let Some(&next_g) = iter.peek() {
1048 if Self::get_grapheme_class(next_g) == start_class {
1049 iter.next();
1050 pos += 1;
1051 } else {
1052 break;
1053 }
1054 }
1055 }
1056 }
1057
1058 while let Some(&g) = iter.peek() {
1059 if Self::get_grapheme_class(g) == 0 {
1060 iter.next();
1061 pos += 1;
1062 } else {
1063 break;
1064 }
1065 }
1066
1067 self.cursor = pos;
1068 }
1069
1070 fn grapheme_count(&self) -> usize {
1073 self.value.graphemes(true).count()
1074 }
1075
1076 fn grapheme_byte_offset(&self, grapheme_idx: usize) -> usize {
1077 self.value
1078 .grapheme_indices(true)
1079 .nth(grapheme_idx)
1080 .map(|(i, _)| i)
1081 .unwrap_or(self.value.len())
1082 }
1083
1084 fn grapheme_width(&self, g: &str) -> usize {
1085 if let Some(mask) = self.mask_char {
1086 let mut buf = [0u8; 4];
1087 let mask_str = mask.encode_utf8(&mut buf);
1088 grapheme_width(mask_str)
1089 } else {
1090 grapheme_width(g)
1091 }
1092 }
1093
1094 fn prev_grapheme_width(&self) -> usize {
1095 if self.cursor == 0 {
1096 return 0;
1097 }
1098 self.value
1099 .graphemes(true)
1100 .nth(self.cursor - 1)
1101 .map(|g| self.grapheme_width(g))
1102 .unwrap_or(0)
1103 }
1104
1105 fn cursor_visual_pos(&self) -> usize {
1106 let mut pos = 0;
1107 if !self.value.is_empty() {
1108 pos += self
1109 .value
1110 .graphemes(true)
1111 .take(self.cursor)
1112 .map(|g| self.grapheme_width(g))
1113 .sum::<usize>();
1114 }
1115 if let Some(ime) = &self.ime_composition {
1116 pos += ime
1117 .graphemes(true)
1118 .map(|g| self.grapheme_width(g))
1119 .sum::<usize>();
1120 }
1121 pos
1122 }
1123
1124 fn effective_scroll(&self, viewport_width: usize) -> usize {
1125 let cursor_visual = self.cursor_visual_pos();
1126 let mut scroll = self.scroll_cells.get();
1127 if cursor_visual < scroll {
1128 scroll = cursor_visual;
1129 }
1130 if cursor_visual >= scroll + viewport_width {
1131 let candidate_scroll = cursor_visual - viewport_width + 1;
1132 let prev_width = self.prev_grapheme_width();
1135 let max_scroll_for_prev = cursor_visual.saturating_sub(prev_width);
1136
1137 if viewport_width > prev_width {
1140 scroll = candidate_scroll.min(max_scroll_for_prev);
1141 } else {
1142 scroll = candidate_scroll;
1143 }
1144 }
1145
1146 scroll = self.snap_scroll_to_grapheme_boundary(scroll, viewport_width);
1148
1149 self.scroll_cells.set(scroll);
1150 scroll
1151 }
1152
1153 fn snap_scroll_to_grapheme_boundary(&self, scroll: usize, viewport_width: usize) -> usize {
1154 let mut pos = 0;
1155 let cursor_visual = self.cursor_visual_pos();
1156
1157 for g in self.value.graphemes(true) {
1158 let w = self.grapheme_width(g);
1159 let next_pos = pos + w;
1160
1161 if pos < scroll && scroll < next_pos {
1163 if cursor_visual <= pos + viewport_width {
1167 return pos;
1168 } else {
1169 return next_pos;
1171 }
1172 }
1173
1174 if next_pos > scroll {
1175 break;
1177 }
1178 pos = next_pos;
1179 }
1180 scroll
1181 }
1182}
1183
1184impl Widget for TextInput {
1185 fn render(&self, area: Rect, frame: &mut Frame) {
1186 if frame.a11y_enabled() {
1187 frame.push_a11y_nodes(ftui_a11y::Accessible::accessibility_nodes(self, area));
1188 }
1189 #[cfg(feature = "tracing")]
1190 let _span = tracing::debug_span!(
1191 "widget_render",
1192 widget = "TextInput",
1193 x = area.x,
1194 y = area.y,
1195 w = area.width,
1196 h = area.height
1197 )
1198 .entered();
1199
1200 if area.width < 1 || area.height < 1 {
1201 return;
1202 }
1203
1204 let deg = frame.buffer.degradation;
1205
1206 let base_style = if deg.apply_styling() {
1210 self.style
1211 } else {
1212 Style::default()
1213 };
1214 clear_text_area(frame, area, base_style);
1215
1216 let arena = frame.arena;
1218 let graphemes_heap;
1219 let graphemes: &[&str] = if let Some(a) = arena {
1220 a.alloc_iter(self.value.graphemes(true))
1221 } else {
1222 graphemes_heap = self.value.graphemes(true).collect::<Vec<_>>();
1223 &graphemes_heap
1224 };
1225 let show_placeholder =
1226 self.value.is_empty() && self.ime_composition.is_none() && !self.placeholder.is_empty();
1227
1228 let viewport_width = area.width as usize;
1229 let cursor_visual_pos = self.cursor_visual_pos();
1230 let effective_scroll = self.effective_scroll(viewport_width);
1231
1232 let mut visual_x: usize = 0;
1234 let y = area.y;
1235
1236 if show_placeholder {
1237 let placeholder_style = if deg.apply_styling() {
1238 self.placeholder_style
1239 } else {
1240 Style::default()
1241 };
1242 for g in self.placeholder.graphemes(true) {
1243 let w = self.grapheme_width(g);
1244 if w == 0 {
1245 continue;
1246 }
1247
1248 if visual_x + w <= effective_scroll {
1250 visual_x += w;
1251 continue;
1252 }
1253
1254 if visual_x < effective_scroll {
1256 visual_x += w;
1257 continue;
1258 }
1259
1260 let rel_x = visual_x - effective_scroll;
1261
1262 if rel_x >= viewport_width {
1264 break;
1265 }
1266
1267 if rel_x + w > viewport_width {
1269 break;
1270 }
1271
1272 let mut cell = if g.chars().count() > 1 || w > 1 {
1273 let id = frame.intern_with_width(g, w as u8);
1274 Cell::new(CellContent::from_grapheme(id))
1275 } else if let Some(c) = g.chars().next() {
1276 Cell::from_char(c)
1277 } else {
1278 visual_x += w;
1279 continue;
1280 };
1281 crate::apply_style(&mut cell, placeholder_style);
1282
1283 frame
1284 .buffer
1285 .set(area.x.saturating_add(rel_x as u16), y, cell);
1286 visual_x += w;
1287 }
1288 } else {
1289 let mut display_spans: Vec<(&str, Style, bool)> = Vec::new();
1290 for (gi, g) in graphemes.iter().enumerate() {
1291 if gi == self.cursor
1292 && let Some(ime) = &self.ime_composition
1293 {
1294 let ime_style = if deg.apply_styling() {
1295 self.style
1296 } else {
1297 Style::default()
1298 };
1299 for ig in ime.graphemes(true) {
1300 display_spans.push((ig, ime_style, true));
1301 }
1302 }
1303
1304 let cell_style = if !deg.apply_styling() {
1305 Style::default()
1306 } else if self.is_in_selection(gi) {
1307 self.selection_style
1308 } else {
1309 self.style
1310 };
1311 display_spans.push((g, cell_style, false));
1312 }
1313 if self.cursor == graphemes.len()
1314 && let Some(ime) = &self.ime_composition
1315 {
1316 let ime_style = if deg.apply_styling() {
1317 self.style
1318 } else {
1319 Style::default()
1320 };
1321 for ig in ime.graphemes(true) {
1322 display_spans.push((ig, ime_style, true));
1323 }
1324 }
1325
1326 for (g, cell_style, is_ime) in display_spans {
1327 let w = self.grapheme_width(g);
1328 if w == 0 {
1329 continue;
1330 }
1331
1332 if visual_x + w <= effective_scroll {
1334 visual_x += w;
1335 continue;
1336 }
1337
1338 if visual_x < effective_scroll {
1340 visual_x += w;
1341 continue;
1342 }
1343
1344 let rel_x = visual_x - effective_scroll;
1345
1346 if rel_x >= viewport_width {
1348 break;
1349 }
1350
1351 if rel_x + w > viewport_width {
1353 break;
1354 }
1355
1356 let mut cell = if let Some(mask) = self.mask_char {
1357 Cell::from_char(mask)
1358 } else if g.chars().count() > 1 || w > 1 {
1359 let id = frame.intern_with_width(g, w as u8);
1360 Cell::new(CellContent::from_grapheme(id))
1361 } else {
1362 Cell::from_char(g.chars().next().unwrap_or(' '))
1363 };
1364 crate::apply_style(&mut cell, cell_style);
1365
1366 if is_ime && deg.apply_styling() {
1367 use ftui_render::cell::StyleFlags;
1368 let current_flags = cell.attrs.flags();
1369 cell.attrs = cell.attrs.with_flags(current_flags | StyleFlags::UNDERLINE);
1370 }
1371
1372 frame
1373 .buffer
1374 .set(area.x.saturating_add(rel_x as u16), y, cell);
1375 visual_x += w;
1376 }
1377 }
1378
1379 if self.focused {
1380 let cursor_rel_x = cursor_visual_pos.saturating_sub(effective_scroll);
1382 if cursor_rel_x < viewport_width {
1383 let cursor_screen_x = area.x.saturating_add(cursor_rel_x as u16);
1384 if let Some(cell) = frame.buffer.get_mut(cursor_screen_x, y) {
1385 if !deg.apply_styling() {
1386 use ftui_render::cell::StyleFlags;
1388 let current_flags = cell.attrs.flags();
1389 let new_flags = current_flags ^ StyleFlags::REVERSE;
1390 cell.attrs = cell.attrs.with_flags(new_flags);
1391 } else if self.cursor_style.is_empty() {
1392 use ftui_render::cell::StyleFlags;
1394 let current_flags = cell.attrs.flags();
1395 let new_flags = current_flags ^ StyleFlags::REVERSE;
1396 cell.attrs = cell.attrs.with_flags(new_flags);
1397 } else {
1398 crate::apply_style(cell, self.cursor_style);
1399 }
1400 }
1401 }
1402
1403 frame.set_cursor(Some(self.cursor_position(area)));
1404 frame.set_cursor_visible(true);
1405 }
1406 }
1407
1408 fn is_essential(&self) -> bool {
1409 true
1410 }
1411}
1412
1413impl ftui_a11y::Accessible for TextInput {
1418 fn accessibility_nodes(&self, area: Rect) -> Vec<ftui_a11y::node::A11yNodeInfo> {
1419 use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState};
1420
1421 let id = crate::a11y_node_id(area);
1422 let name = if self.value.is_empty() {
1423 self.placeholder.clone()
1424 } else if self.mask_char.is_some() {
1425 String::from("password field")
1427 } else {
1428 self.value.clone()
1429 };
1430
1431 let state = A11yState {
1432 focused: self.focused,
1433 disabled: self.max_length == Some(0),
1434 ..A11yState::default()
1435 };
1436
1437 let mut node = A11yNodeInfo::new(id, A11yRole::TextInput, area).with_state(state);
1438 if !name.is_empty() {
1439 node = node.with_name(name);
1440 }
1441 if self.mask_char.is_some() {
1442 node = node.with_description("password input");
1443 }
1444
1445 vec![node]
1446 }
1447}
1448
1449#[derive(Debug, Clone)]
1461pub struct TextInputSnapshot {
1462 value: String,
1463 cursor: usize,
1464 selection_anchor: Option<usize>,
1465}
1466
1467impl UndoSupport for TextInput {
1468 fn undo_widget_id(&self) -> UndoWidgetId {
1469 self.undo_id
1470 }
1471
1472 fn create_snapshot(&self) -> Box<dyn std::any::Any + Send> {
1473 Box::new(TextInputSnapshot {
1474 value: self.value.clone(),
1475 cursor: self.cursor,
1476 selection_anchor: self.selection_anchor,
1477 })
1478 }
1479
1480 fn restore_snapshot(&mut self, snapshot: &dyn std::any::Any) -> bool {
1481 if let Some(snap) = snapshot.downcast_ref::<TextInputSnapshot>() {
1482 self.value = snap.value.clone();
1483 self.cursor = snap.cursor;
1484 self.selection_anchor = snap.selection_anchor;
1485 self.scroll_cells.set(0); true
1487 } else {
1488 false
1489 }
1490 }
1491}
1492
1493impl TextInputUndoExt for TextInput {
1494 fn text_value(&self) -> &str {
1495 &self.value
1496 }
1497
1498 fn set_text_value(&mut self, value: &str) {
1499 self.value = value.to_string();
1500 let max = self.grapheme_count();
1501 self.cursor = self.cursor.min(max);
1502 self.selection_anchor = None;
1503 }
1504
1505 fn cursor_position(&self) -> usize {
1506 self.cursor
1507 }
1508
1509 fn set_cursor_position(&mut self, pos: usize) {
1510 let max = self.grapheme_count();
1511 self.cursor = pos.min(max);
1512 }
1513
1514 fn insert_text_at(&mut self, position: usize, text: &str) {
1515 let byte_offset = self.grapheme_byte_offset(position);
1516 self.value.insert_str(byte_offset, text);
1517 let inserted_graphemes = text.graphemes(true).count();
1518 if self.cursor >= position {
1519 self.cursor += inserted_graphemes;
1520 }
1521 }
1522
1523 fn delete_text_range(&mut self, start: usize, end: usize) {
1524 if start >= end {
1525 return;
1526 }
1527 let byte_start = self.grapheme_byte_offset(start);
1528 let byte_end = self.grapheme_byte_offset(end);
1529 self.value.drain(byte_start..byte_end);
1530 let deleted_count = end - start;
1531 if self.cursor > end {
1532 self.cursor -= deleted_count;
1533 } else if self.cursor > start {
1534 self.cursor = start;
1535 }
1536 let gc = self.grapheme_count();
1537 if self.cursor > gc {
1538 self.cursor = gc;
1539 }
1540 }
1541}
1542
1543impl TextInput {
1544 #[must_use]
1569 pub fn create_text_edit_command(
1570 &self,
1571 operation: TextEditOperation,
1572 ) -> Option<crate::undo_support::WidgetTextEditCmd> {
1573 Some(crate::undo_support::WidgetTextEditCmd::new(
1574 self.undo_id,
1575 operation,
1576 ))
1577 }
1578
1579 #[must_use]
1583 pub fn undo_id(&self) -> UndoWidgetId {
1584 self.undo_id
1585 }
1586}
1587
1588#[cfg(test)]
1589mod tests {
1590 use super::*;
1591 #[cfg(feature = "tracing")]
1592 use std::sync::{Arc, Mutex};
1593
1594 #[cfg(feature = "tracing")]
1595 use tracing::Subscriber;
1596 #[cfg(feature = "tracing")]
1597 use tracing_subscriber::Layer;
1598 #[cfg(feature = "tracing")]
1599 use tracing_subscriber::layer::{Context, SubscriberExt};
1600
1601 #[allow(dead_code)]
1602 fn cell_at(frame: &Frame, x: u16, y: u16) -> Cell {
1603 frame
1604 .buffer
1605 .get(x, y)
1606 .copied()
1607 .unwrap_or_else(|| panic!("test cell should exist at ({x},{y})"))
1608 }
1609
1610 fn raw_row_text(frame: &Frame, y: u16, width: u16) -> String {
1611 (0..width)
1612 .map(|x| {
1613 frame
1614 .buffer
1615 .get(x, y)
1616 .and_then(|cell| cell.content.as_char())
1617 .unwrap_or(' ')
1618 })
1619 .collect()
1620 }
1621
1622 #[cfg(feature = "tracing")]
1623 #[derive(Debug, Default)]
1624 struct InputTraceState {
1625 span_count: usize,
1626 has_cursor_position_field: bool,
1627 cursor_positions: Vec<usize>,
1628 operations: Vec<String>,
1629 }
1630
1631 #[cfg(feature = "tracing")]
1632 struct InputTraceCapture {
1633 state: Arc<Mutex<InputTraceState>>,
1634 }
1635
1636 #[cfg(feature = "tracing")]
1637 impl<S> Layer<S> for InputTraceCapture
1638 where
1639 S: Subscriber + for<'lookup> tracing_subscriber::registry::LookupSpan<'lookup>,
1640 {
1641 fn on_new_span(
1642 &self,
1643 attrs: &tracing::span::Attributes<'_>,
1644 _id: &tracing::Id,
1645 _ctx: Context<'_, S>,
1646 ) {
1647 if attrs.metadata().name() != "input.edit" {
1648 return;
1649 }
1650
1651 #[derive(Default)]
1652 struct InputEditVisitor {
1653 cursor_position: Option<usize>,
1654 operation: Option<String>,
1655 }
1656
1657 impl tracing::field::Visit for InputEditVisitor {
1658 fn record_i64(&mut self, field: &tracing::field::Field, value: i64) {
1659 if field.name() == "cursor_position" {
1660 self.cursor_position = usize::try_from(value).ok();
1661 }
1662 }
1663
1664 fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
1665 if field.name() == "cursor_position" {
1666 self.cursor_position = usize::try_from(value).ok();
1667 }
1668 }
1669
1670 fn record_debug(
1671 &mut self,
1672 field: &tracing::field::Field,
1673 value: &dyn std::fmt::Debug,
1674 ) {
1675 if field.name() == "operation" {
1676 self.operation = Some(format!("{value:?}").trim_matches('"').to_owned());
1677 }
1678 }
1679
1680 fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
1681 if field.name() == "operation" {
1682 self.operation = Some(value.to_owned());
1683 }
1684 }
1685 }
1686
1687 let fields = attrs.metadata().fields();
1688 let mut visitor = InputEditVisitor::default();
1689 attrs.record(&mut visitor);
1690
1691 let mut state = self.state.lock().expect("trace state lock");
1692 state.span_count += 1;
1693 state.has_cursor_position_field |= fields.field("cursor_position").is_some();
1694 if let Some(cursor) = visitor.cursor_position {
1695 state.cursor_positions.push(cursor);
1696 }
1697 if let Some(operation) = visitor.operation {
1698 state.operations.push(operation);
1699 }
1700 }
1701 }
1702
1703 #[allow(dead_code)]
1704 #[test]
1705 fn test_empty_input() {
1706 let input = TextInput::new();
1707 assert!(input.value().is_empty());
1708 assert_eq!(input.cursor(), 0);
1709 assert!(input.selected_text().is_none());
1710 }
1711
1712 #[test]
1713 fn test_with_value() {
1714 let mut input = TextInput::new().with_value("hello");
1715 input.set_focused(true);
1716 assert_eq!(input.value(), "hello");
1717 assert_eq!(input.cursor(), 5);
1718 }
1719
1720 #[test]
1721 fn test_set_value() {
1722 let mut input = TextInput::new().with_value("hello world");
1723 input.cursor = 11;
1724 input.set_value("hi");
1725 assert_eq!(input.value(), "hi");
1726 assert_eq!(input.cursor(), 2);
1727 }
1728
1729 #[test]
1730 fn test_clear() {
1731 let mut input = TextInput::new().with_value("hello");
1732 input.set_focused(true);
1733 input.clear();
1734 assert!(input.value().is_empty());
1735 assert_eq!(input.cursor(), 0);
1736 }
1737
1738 #[test]
1739 fn test_insert_char() {
1740 let mut input = TextInput::new();
1741 input.insert_char('a');
1742 input.insert_char('b');
1743 input.insert_char('c');
1744 assert_eq!(input.value(), "abc");
1745 assert_eq!(input.cursor(), 3);
1746 }
1747
1748 #[test]
1749 fn test_insert_char_mid() {
1750 let mut input = TextInput::new().with_value("ac");
1751 input.cursor = 1;
1752 input.insert_char('b');
1753 assert_eq!(input.value(), "abc");
1754 assert_eq!(input.cursor(), 2);
1755 }
1756
1757 #[test]
1758 fn test_max_length() {
1759 let mut input = TextInput::new().with_max_length(3);
1760 for c in "abcdef".chars() {
1761 input.insert_char(c);
1762 }
1763 assert_eq!(input.value(), "abc");
1764 assert_eq!(input.cursor(), 3);
1765 }
1766
1767 #[test]
1768 fn test_delete_char_back() {
1769 let mut input = TextInput::new().with_value("hello");
1770 input.delete_char_back();
1771 assert_eq!(input.value(), "hell");
1772 assert_eq!(input.cursor(), 4);
1773 }
1774
1775 #[test]
1776 fn test_delete_char_back_at_start() {
1777 let mut input = TextInput::new().with_value("hello");
1778 input.cursor = 0;
1779 input.delete_char_back();
1780 assert_eq!(input.value(), "hello");
1781 }
1782
1783 #[test]
1784 fn test_delete_char_forward() {
1785 let mut input = TextInput::new().with_value("hello");
1786 input.cursor = 0;
1787 input.delete_char_forward();
1788 assert_eq!(input.value(), "ello");
1789 assert_eq!(input.cursor(), 0);
1790 }
1791
1792 #[test]
1793 fn test_delete_char_forward_at_end() {
1794 let mut input = TextInput::new().with_value("hello");
1795 input.delete_char_forward();
1796 assert_eq!(input.value(), "hello");
1797 }
1798
1799 #[test]
1800 fn test_cursor_left_right() {
1801 let mut input = TextInput::new().with_value("hello");
1802 assert_eq!(input.cursor(), 5);
1803 input.move_cursor_left();
1804 assert_eq!(input.cursor(), 4);
1805 input.move_cursor_left();
1806 assert_eq!(input.cursor(), 3);
1807 input.move_cursor_right();
1808 assert_eq!(input.cursor(), 4);
1809 }
1810
1811 #[test]
1812 fn test_cursor_bounds() {
1813 let mut input = TextInput::new().with_value("hi");
1814 input.cursor = 0;
1815 input.move_cursor_left();
1816 assert_eq!(input.cursor(), 0);
1817 input.cursor = 2;
1818 input.move_cursor_right();
1819 assert_eq!(input.cursor(), 2);
1820 }
1821
1822 #[test]
1823 fn test_word_movement_left() {
1824 let mut input = TextInput::new().with_value("hello world test");
1825 input.move_cursor_word_left(false);
1828 assert_eq!(input.cursor(), 12); input.move_cursor_word_left(false);
1831 assert_eq!(input.cursor(), 6); input.move_cursor_word_left(false);
1834 assert_eq!(input.cursor(), 0); }
1836
1837 #[test]
1838 fn test_word_movement_right() {
1839 let mut input = TextInput::new().with_value("hello world test");
1840 input.cursor = 0;
1841 input.move_cursor_word_right(false);
1844 assert_eq!(input.cursor(), 6); input.move_cursor_word_right(false);
1847 assert_eq!(input.cursor(), 12); input.move_cursor_word_right(false);
1850 assert_eq!(input.cursor(), 16); }
1852
1853 #[test]
1854 fn test_word_movement_skips_punctuation() {
1855 let mut input = TextInput::new().with_value("hello, world");
1856 input.cursor = 0;
1857 input.move_cursor_word_right(false);
1860 assert_eq!(input.cursor(), 5); input.move_cursor_word_right(false);
1863 assert_eq!(input.cursor(), 7); input.move_cursor_word_right(false);
1866 assert_eq!(input.cursor(), 12); input.move_cursor_word_left(false);
1869 assert_eq!(input.cursor(), 7); }
1871
1872 #[test]
1873 fn test_delete_word_back() {
1874 let mut input = TextInput::new().with_value("hello world");
1875 input.delete_word_back();
1877 assert_eq!(input.value(), "hello "); input.delete_word_back();
1881 assert_eq!(input.value(), ""); }
1883
1884 #[test]
1885 fn test_delete_word_forward() {
1886 let mut input = TextInput::new().with_value("hello world");
1887 input.cursor = 0;
1888 input.delete_word_forward();
1890 assert_eq!(input.value(), "world"); input.delete_word_forward();
1893 assert_eq!(input.value(), ""); }
1895
1896 #[test]
1897 fn test_select_all() {
1898 let mut input = TextInput::new().with_value("hello");
1899 input.select_all();
1900 assert_eq!(input.selected_text(), Some("hello"));
1901 }
1902
1903 #[test]
1904 fn test_delete_selection() {
1905 let mut input = TextInput::new().with_value("hello world");
1906 input.selection_anchor = Some(0);
1907 input.cursor = 5;
1908 input.delete_selection();
1909 assert_eq!(input.value(), " world");
1910 assert_eq!(input.cursor(), 0);
1911 }
1912
1913 #[test]
1914 fn test_insert_replaces_selection() {
1915 let mut input = TextInput::new().with_value("hello");
1916 input.select_all();
1917 input.delete_selection();
1918 input.insert_char('x');
1919 assert_eq!(input.value(), "x");
1920 }
1921
1922 #[test]
1923 fn test_unicode_grapheme_handling() {
1924 let mut input = TextInput::new();
1925 input.set_value("café");
1926 assert_eq!(input.grapheme_count(), 4);
1927 input.cursor = 4;
1928 input.delete_char_back();
1929 assert_eq!(input.value(), "caf");
1930 }
1931
1932 #[test]
1933 fn test_multi_codepoint_grapheme_cursor_movement() {
1934 let mut input = TextInput::new().with_value("a👩💻b");
1935 assert_eq!(input.grapheme_count(), 3);
1936 assert_eq!(input.cursor(), 3);
1937
1938 input.move_cursor_left();
1939 assert_eq!(input.cursor(), 2);
1940 input.move_cursor_left();
1941 assert_eq!(input.cursor(), 1);
1942 input.move_cursor_left();
1943 assert_eq!(input.cursor(), 0);
1944
1945 input.move_cursor_right();
1946 assert_eq!(input.cursor(), 1);
1947 input.move_cursor_right();
1948 assert_eq!(input.cursor(), 2);
1949 input.move_cursor_right();
1950 assert_eq!(input.cursor(), 3);
1951 }
1952
1953 #[test]
1954 fn test_delete_back_multi_codepoint_grapheme() {
1955 let mut input = TextInput::new().with_value("a👩💻b");
1956 input.cursor = 2; input.delete_char_back();
1958 assert_eq!(input.value(), "ab");
1959 assert_eq!(input.cursor(), 1);
1960 assert_eq!(input.grapheme_count(), 2);
1961 }
1962
1963 #[test]
1964 fn test_ime_composition_start_update_commit() {
1965 let mut input = TextInput::new().with_value("ab");
1966 input.cursor = 1;
1967
1968 input.ime_start_composition();
1969 assert_eq!(input.ime_composition(), Some(""));
1970
1971 input.ime_update_composition("漢");
1972 assert_eq!(input.ime_composition(), Some("漢"));
1973
1974 assert!(input.ime_commit_composition());
1975 assert_eq!(input.ime_composition(), None);
1976 assert_eq!(input.value(), "a漢b");
1977 assert_eq!(input.cursor(), 2);
1978 }
1979
1980 #[test]
1981 fn test_ime_composition_cancel_keeps_value() {
1982 let mut input = TextInput::new().with_value("hello");
1983 input.ime_start_composition();
1984 input.ime_update_composition("👩💻");
1985 assert_eq!(input.ime_composition(), Some("👩💻"));
1986 assert!(input.ime_cancel_composition());
1987 assert_eq!(input.ime_composition(), None);
1988 assert_eq!(input.value(), "hello");
1989 assert_eq!(input.cursor(), 5);
1990 }
1991
1992 #[test]
1993 fn test_ime_commit_without_session_is_noop() {
1994 let mut input = TextInput::new().with_value("abc");
1995 assert!(!input.ime_commit_composition());
1996 assert_eq!(input.value(), "abc");
1997 assert_eq!(input.cursor(), 3);
1998 }
1999
2000 #[test]
2001 fn test_handle_event_ime_update_and_commit() {
2002 let mut input = TextInput::new().with_value("ab");
2003 input.cursor = 1;
2004
2005 assert!(input.handle_event(&Event::Ime(ImeEvent::start())));
2006 assert!(input.handle_event(&Event::Ime(ImeEvent::update("漢"))));
2007 assert_eq!(input.ime_composition(), Some("漢"));
2008 assert!(input.handle_event(&Event::Ime(ImeEvent::commit("漢"))));
2009 assert_eq!(input.ime_composition(), None);
2010 assert_eq!(input.value(), "a漢b");
2011 assert_eq!(input.cursor(), 2);
2012 }
2013
2014 #[test]
2015 fn test_handle_event_ime_cancel() {
2016 let mut input = TextInput::new().with_value("hello");
2017 input.cursor = 5;
2018 assert!(input.handle_event(&Event::Ime(ImeEvent::start())));
2019 assert!(input.handle_event(&Event::Ime(ImeEvent::update("👩💻"))));
2020 assert!(input.handle_event(&Event::Ime(ImeEvent::cancel())));
2021 assert_eq!(input.ime_composition(), None);
2022 assert_eq!(input.value(), "hello");
2023 assert_eq!(input.cursor(), 5);
2024 }
2025
2026 #[test]
2027 fn test_flag_emoji_grapheme_delete_and_cursor() {
2028 let mut input = TextInput::new().with_value("a🇺🇸b");
2029 assert_eq!(input.grapheme_count(), 3);
2030 input.cursor = 2;
2031 input.delete_char_back();
2032 assert_eq!(input.value(), "ab");
2033 assert_eq!(input.cursor(), 1);
2034 }
2035
2036 #[test]
2037 fn test_combining_grapheme_delete_and_cursor() {
2038 let mut input = TextInput::new().with_value("a\u{0301}b");
2039 assert_eq!(input.grapheme_count(), 2);
2040 input.cursor = 1;
2041 input.delete_char_back();
2042 assert_eq!(input.value(), "b");
2043 assert_eq!(input.cursor(), 0);
2044 }
2045
2046 #[test]
2047 fn test_bidi_logical_cursor_movement_over_graphemes() {
2048 let mut input = TextInput::new().with_value("AאבB");
2049 assert_eq!(input.grapheme_count(), 4);
2050
2051 input.move_cursor_left();
2052 assert_eq!(input.cursor(), 3);
2053 input.move_cursor_left();
2054 assert_eq!(input.cursor(), 2);
2055 input.move_cursor_left();
2056 assert_eq!(input.cursor(), 1);
2057 input.move_cursor_left();
2058 assert_eq!(input.cursor(), 0);
2059
2060 input.move_cursor_right();
2061 assert_eq!(input.cursor(), 1);
2062 input.move_cursor_right();
2063 assert_eq!(input.cursor(), 2);
2064 input.move_cursor_right();
2065 assert_eq!(input.cursor(), 3);
2066 input.move_cursor_right();
2067 assert_eq!(input.cursor(), 4);
2068 }
2069
2070 #[test]
2071 fn test_handle_event_char() {
2072 let mut input = TextInput::new();
2073 let event = Event::Key(KeyEvent::new(KeyCode::Char('a')));
2074 assert!(input.handle_event(&event));
2075 assert_eq!(input.value(), "a");
2076 }
2077
2078 #[test]
2079 fn test_handle_event_backspace() {
2080 let mut input = TextInput::new().with_value("ab");
2081 let event = Event::Key(KeyEvent::new(KeyCode::Backspace));
2082 assert!(input.handle_event(&event));
2083 assert_eq!(input.value(), "a");
2084 }
2085
2086 #[test]
2087 fn test_handle_event_ctrl_a() {
2088 let mut input = TextInput::new().with_value("hello");
2089 let event = Event::Key(KeyEvent::new(KeyCode::Char('a')).with_modifiers(Modifiers::CTRL));
2090 assert!(input.handle_event(&event));
2091 assert_eq!(input.selected_text(), Some("hello"));
2092 }
2093
2094 #[test]
2095 fn test_handle_event_ctrl_backspace() {
2096 let mut input = TextInput::new().with_value("hello world");
2097 let event = Event::Key(KeyEvent::new(KeyCode::Backspace).with_modifiers(Modifiers::CTRL));
2098 assert!(input.handle_event(&event));
2099 assert_eq!(input.value(), "hello ");
2100 }
2101
2102 #[test]
2103 fn test_handle_event_home_end() {
2104 let mut input = TextInput::new().with_value("hello");
2105 input.cursor = 3;
2106 let home = Event::Key(KeyEvent::new(KeyCode::Home));
2107 assert!(input.handle_event(&home));
2108 assert_eq!(input.cursor(), 0);
2109 let end = Event::Key(KeyEvent::new(KeyCode::End));
2110 assert!(input.handle_event(&end));
2111 assert_eq!(input.cursor(), 5);
2112 }
2113
2114 #[test]
2115 fn test_shift_left_creates_selection() {
2116 let mut input = TextInput::new().with_value("hello");
2117 let event = Event::Key(KeyEvent::new(KeyCode::Left).with_modifiers(Modifiers::SHIFT));
2118 assert!(input.handle_event(&event));
2119 assert_eq!(input.cursor(), 4);
2120 assert_eq!(input.selection_anchor, Some(5));
2121 assert_eq!(input.selected_text(), Some("o"));
2122 }
2123
2124 #[test]
2125 fn test_cursor_position() {
2126 let input = TextInput::new().with_value("hello");
2127 let area = Rect::new(10, 5, 20, 1);
2128 let (x, y) = input.cursor_position(area);
2129 assert_eq!(x, 15);
2130 assert_eq!(y, 5);
2131 }
2132
2133 #[test]
2134 fn test_cursor_position_empty() {
2135 let input = TextInput::new();
2136 let area = Rect::new(0, 0, 80, 1);
2137 let (x, y) = input.cursor_position(area);
2138 assert_eq!(x, 0);
2139 assert_eq!(y, 0);
2140 }
2141
2142 #[test]
2143 fn test_password_mask() {
2144 let input = TextInput::new().with_mask('*').with_value("secret");
2145 assert_eq!(input.value(), "secret");
2146 assert_eq!(input.cursor_visual_pos(), 6);
2147 }
2148
2149 #[test]
2150 fn test_render_basic() {
2151 use ftui_render::frame::Frame;
2152 use ftui_render::grapheme_pool::GraphemePool;
2153
2154 let input = TextInput::new().with_value("hi");
2155 let area = Rect::new(0, 0, 10, 1);
2156 let mut pool = GraphemePool::new();
2157 let mut frame = Frame::new(10, 1, &mut pool);
2158 input.render(area, &mut frame);
2159 let cell_h = cell_at(&frame, 0, 0);
2160 assert_eq!(cell_h.content.as_char(), Some('h'));
2161 let cell_i = cell_at(&frame, 1, 0);
2162 assert_eq!(cell_i.content.as_char(), Some('i'));
2163 }
2164
2165 #[test]
2166 fn test_render_sets_cursor_when_focused() {
2167 use ftui_render::frame::Frame;
2168 use ftui_render::grapheme_pool::GraphemePool;
2169
2170 let input = TextInput::new().with_value("hi").with_focused(true);
2171 let area = Rect::new(0, 0, 10, 1);
2172 let mut pool = GraphemePool::new();
2173 let mut frame = Frame::new(10, 1, &mut pool);
2174 input.render(area, &mut frame);
2175
2176 assert_eq!(frame.cursor_position, Some((2, 0)));
2177 assert!(frame.cursor_visible);
2178 }
2179
2180 #[test]
2181 fn test_render_does_not_set_cursor_when_unfocused() {
2182 use ftui_render::frame::Frame;
2183 use ftui_render::grapheme_pool::GraphemePool;
2184
2185 let input = TextInput::new().with_value("hi");
2186 let area = Rect::new(0, 0, 10, 1);
2187 let mut pool = GraphemePool::new();
2188 let mut frame = Frame::new(10, 1, &mut pool);
2189 input.render(area, &mut frame);
2190
2191 assert!(frame.cursor_position.is_none());
2192 }
2193
2194 #[test]
2195 fn test_render_grapheme_uses_pool() {
2196 use ftui_render::frame::Frame;
2197 use ftui_render::grapheme_pool::GraphemePool;
2198
2199 let grapheme = "👩💻";
2200 let input = TextInput::new().with_value(grapheme);
2201 let area = Rect::new(0, 0, 6, 1);
2202 let mut pool = GraphemePool::new();
2203 let mut frame = Frame::new(6, 1, &mut pool);
2204 input.render(area, &mut frame);
2205
2206 let cell = cell_at(&frame, 0, 0);
2207 assert!(cell.content.is_grapheme());
2208 let width = grapheme_width(grapheme);
2209 if width > 1 {
2210 assert!(cell_at(&frame, 1, 0).is_continuation());
2211 }
2212 }
2213
2214 #[test]
2215 fn test_render_shorter_value_clears_stale_suffix_and_owned_rows() {
2216 use ftui_render::frame::Frame;
2217 use ftui_render::grapheme_pool::GraphemePool;
2218
2219 let area = Rect::new(0, 0, 8, 2);
2220 let mut pool = GraphemePool::new();
2221 let mut frame = Frame::new(8, 2, &mut pool);
2222
2223 TextInput::new()
2224 .with_value("abcdef")
2225 .render(area, &mut frame);
2226 TextInput::new().with_value("xy").render(area, &mut frame);
2227
2228 assert_eq!(raw_row_text(&frame, 0, 8), "xy ");
2229 assert_eq!(raw_row_text(&frame, 1, 8), " ");
2230 }
2231
2232 #[test]
2233 fn test_left_collapses_selection() {
2234 let mut input = TextInput::new().with_value("hello");
2235 input.selection_anchor = Some(1);
2236 input.cursor = 4;
2237 input.move_cursor_left();
2238 assert_eq!(input.cursor(), 1);
2239 assert!(input.selection_anchor.is_none());
2240 }
2241
2242 #[test]
2243 fn test_right_collapses_selection() {
2244 let mut input = TextInput::new().with_value("hello");
2245 input.selection_anchor = Some(1);
2246 input.cursor = 4;
2247 input.move_cursor_right();
2248 assert_eq!(input.cursor(), 4);
2249 assert!(input.selection_anchor.is_none());
2250 }
2251
2252 #[test]
2253 fn test_render_sets_frame_cursor() {
2254 use ftui_render::frame::Frame;
2255 use ftui_render::grapheme_pool::GraphemePool;
2256
2257 let input = TextInput::new().with_value("hello").with_focused(true);
2258 let area = Rect::new(5, 3, 20, 1);
2259 let mut pool = GraphemePool::new();
2260 let mut frame = Frame::new(30, 10, &mut pool);
2261 input.render(area, &mut frame);
2262
2263 assert_eq!(frame.cursor_position, Some((10, 3)));
2267 }
2268
2269 #[test]
2270 fn test_render_cursor_mid_text() {
2271 use ftui_render::frame::Frame;
2272 use ftui_render::grapheme_pool::GraphemePool;
2273
2274 let mut input = TextInput::new().with_value("hello").with_focused(true);
2275 input.cursor = 2; let area = Rect::new(0, 0, 20, 1);
2277 let mut pool = GraphemePool::new();
2278 let mut frame = Frame::new(20, 1, &mut pool);
2279 input.render(area, &mut frame);
2280
2281 assert_eq!(frame.cursor_position, Some((2, 0)));
2283 }
2284
2285 #[test]
2290 fn test_undo_widget_id_is_stable() {
2291 let input = TextInput::new();
2292 let id1 = input.undo_id();
2293 let id2 = input.undo_id();
2294 assert_eq!(id1, id2);
2295 }
2296
2297 #[test]
2298 fn test_undo_widget_id_unique_per_instance() {
2299 let input1 = TextInput::new();
2300 let input2 = TextInput::new();
2301 assert_ne!(input1.undo_id(), input2.undo_id());
2302 }
2303
2304 #[test]
2305 fn test_snapshot_and_restore() {
2306 let mut input = TextInput::new().with_value("hello");
2307 input.cursor = 3;
2308 input.selection_anchor = Some(1);
2309
2310 let snapshot = input.create_snapshot();
2311
2312 input.set_value("world");
2314 input.cursor = 5;
2315 input.selection_anchor = None;
2316
2317 assert_eq!(input.value(), "world");
2318 assert_eq!(input.cursor(), 5);
2319
2320 assert!(input.restore_snapshot(snapshot.as_ref()));
2322 assert_eq!(input.value(), "hello");
2323 assert_eq!(input.cursor(), 3);
2324 assert_eq!(input.selection_anchor, Some(1));
2325 }
2326
2327 #[test]
2328 fn test_text_input_undo_ext_insert() {
2329 let mut input = TextInput::new().with_value("hello");
2330 input.cursor = 2;
2331
2332 input.insert_text_at(2, " world");
2333 assert_eq!(input.value(), "he worldllo");
2335 assert_eq!(input.cursor(), 8); }
2337
2338 #[test]
2339 fn test_text_input_undo_ext_delete() {
2340 let mut input = TextInput::new().with_value("hello world");
2341 input.cursor = 8;
2342
2343 input.delete_text_range(5, 11); assert_eq!(input.value(), "hello");
2345 assert_eq!(input.cursor(), 5); }
2347
2348 #[test]
2349 fn test_create_text_edit_command() {
2350 let input = TextInput::new().with_value("hello");
2351 let cmd = input.create_text_edit_command(TextEditOperation::Insert {
2352 position: 0,
2353 text: "hi".to_string(),
2354 });
2355 assert!(cmd.is_some());
2356 let cmd = cmd.expect("test command should exist");
2357 assert_eq!(cmd.widget_id(), input.undo_id());
2358 assert_eq!(cmd.description(), "Insert text");
2359 }
2360
2361 #[test]
2362 fn test_paste_bulk_insert() {
2363 let mut input = TextInput::new().with_value("hello");
2364 input.cursor = 5;
2365 let event = Event::Paste(ftui_core::event::PasteEvent::bracketed(" world"));
2366 assert!(input.handle_event(&event));
2367 assert_eq!(input.value(), "hello world");
2368 assert_eq!(input.cursor(), 11);
2369 }
2370
2371 #[test]
2372 fn test_paste_multi_grapheme_sequence() {
2373 let mut input = TextInput::new().with_value("hi");
2374 input.cursor = 2;
2375 let event = Event::Paste(ftui_core::event::PasteEvent::new("👩💻🔥", false));
2376 assert!(input.handle_event(&event));
2377 assert_eq!(input.value(), "hi👩💻🔥");
2378 assert_eq!(input.cursor(), 4);
2379 }
2380
2381 #[test]
2382 fn test_paste_max_length() {
2383 let mut input = TextInput::new().with_value("abc").with_max_length(5);
2384 input.cursor = 3;
2385 let event = Event::Paste(ftui_core::event::PasteEvent::bracketed("def"));
2387 assert!(input.handle_event(&event));
2388 assert_eq!(input.value(), "abcde");
2389 assert_eq!(input.cursor(), 5);
2390 }
2391
2392 #[test]
2393 fn test_paste_combining_merge() {
2394 let mut input = TextInput::new().with_value("e");
2395 input.cursor = 1;
2396 let event = Event::Paste(ftui_core::event::PasteEvent::bracketed("\u{0301}"));
2399 assert!(input.handle_event(&event));
2400 assert_eq!(input.value(), "e\u{0301}");
2401 assert_eq!(input.grapheme_count(), 1);
2402 assert_eq!(input.cursor(), 1);
2403 }
2404
2405 #[test]
2406 fn test_paste_combining_merge_mid_string() {
2407 let mut input = TextInput::new().with_value("ab");
2408 input.cursor = 1; let event = Event::Paste(ftui_core::event::PasteEvent::bracketed("\u{0301}"));
2410 assert!(input.handle_event(&event));
2411 assert_eq!(input.value(), "a\u{0301}b");
2412 assert_eq!(input.grapheme_count(), 2);
2413 assert_eq!(input.cursor(), 1);
2414 }
2415
2416 #[test]
2417 fn test_wide_char_scroll_visibility() {
2418 use ftui_render::frame::Frame;
2419 use ftui_render::grapheme_pool::GraphemePool;
2420
2421 let wide_char = "\u{3000}"; let mut input = TextInput::new().with_value(wide_char).with_focused(true);
2423 input.cursor = 1; let area = Rect::new(0, 0, 2, 1);
2431 let mut pool = GraphemePool::new();
2432 let mut frame = Frame::new(2, 1, &mut pool);
2433 input.render(area, &mut frame);
2434
2435 let cell = cell_at(&frame, 0, 0);
2436 assert!(!cell.is_empty(), "Wide char should be visible");
2438 }
2439
2440 #[test]
2441 fn test_wide_char_scroll_snapping() {
2442 let _input = TextInput::new().with_value("a\u{3000}b"); let wide_char = "\u{3000}";
2473 let text = format!("a{wide_char}b");
2474 let mut input = TextInput::new().with_value(&text);
2475
2476 input.cursor = 3; let _area = Rect::new(0, 0, 2, 1); }
2573
2574 #[cfg(feature = "tracing")]
2575 #[test]
2576 fn tracing_input_edit_span_tracks_cursor_positions() {
2577 let state = Arc::new(Mutex::new(InputTraceState::default()));
2578 let _trace_test_guard = crate::tracing_test_support::acquire();
2579 let subscriber = tracing_subscriber::registry().with(InputTraceCapture {
2580 state: Arc::clone(&state),
2581 });
2582 let _guard = tracing::subscriber::set_default(subscriber);
2583 tracing::callsite::rebuild_interest_cache();
2584
2585 let mut input = TextInput::new().with_value("ab");
2586 tracing::callsite::rebuild_interest_cache();
2587 assert!(input.handle_event(&Event::Key(KeyEvent::new(KeyCode::Char('c')))));
2588 tracing::callsite::rebuild_interest_cache();
2589 assert!(input.handle_event(&Event::Key(KeyEvent::new(KeyCode::Left))));
2590 tracing::callsite::rebuild_interest_cache();
2591 assert!(input.handle_event(&Event::Key(KeyEvent::new(KeyCode::Backspace))));
2592
2593 tracing::callsite::rebuild_interest_cache();
2594 let snapshot = state.lock().expect("trace state lock");
2595 assert!(
2596 snapshot.span_count >= 3,
2597 "expected at least 3 input.edit spans, got {}",
2598 snapshot.span_count
2599 );
2600 assert!(
2601 snapshot.has_cursor_position_field,
2602 "input.edit span missing cursor_position field"
2603 );
2604 assert_eq!(
2605 snapshot.cursor_positions,
2606 vec![3, 2, 1],
2607 "expected cursor positions after insert/left/backspace"
2608 );
2609 assert!(
2610 snapshot.operations.starts_with(&[
2611 "insert_char".to_string(),
2612 "move_left".to_string(),
2613 "delete_back".to_string()
2614 ]),
2615 "unexpected operations: {:?}",
2616 snapshot.operations
2617 );
2618 }
2619}
2620
2621#[cfg(test)]
2622mod scroll_edge_tests {
2623 use super::*;
2624 use ftui_render::frame::Frame;
2625 use ftui_render::grapheme_pool::GraphemePool;
2626
2627 #[test]
2628 fn test_scroll_snap_left_cursor_visibility() {
2629 let mut input = TextInput::new().with_value("ABC");
2637 input.cursor = 1; let area = Rect::new(0, 0, 1, 1);
2642 let mut pool = GraphemePool::new();
2643 let mut frame = Frame::new(1, 1, &mut pool);
2644 input.render(area, &mut frame); input.move_cursor_left(); input.render(area, &mut frame);
2651
2652 let cell = frame.buffer.get(0, 0).unwrap();
2654 assert_eq!(cell.content.as_char(), Some('A'));
2655 }
2656
2657 #[test]
2658 fn test_max_length_replacement_failure() {
2659 let mut input = TextInput::new().with_value("abc").with_max_length(3);
2665 input.selection_anchor = Some(1); input.cursor = 2; let event = Event::Paste(ftui_core::event::PasteEvent::new("de", false));
2670 input.handle_event(&event);
2671
2672 assert_eq!(input.value(), "abc");
2674 assert_eq!(input.cursor(), 2);
2675 assert_eq!(input.selection_anchor, Some(1));
2676 }
2677
2678 mod history_tests {
2679 use super::*;
2680 use proptest::prelude::*;
2681
2682 fn key(code: KeyCode) -> Event {
2683 Event::Key(KeyEvent::new(code))
2684 }
2685
2686 fn typ(input: &mut TextInput, s: &str) {
2687 for c in s.chars() {
2688 input.handle_event(&key(KeyCode::Char(c)));
2689 }
2690 }
2691
2692 fn submit_and_clear(input: &mut TextInput) {
2695 input.handle_event(&key(KeyCode::Enter));
2696 input.clear();
2697 }
2698
2699 fn up(input: &mut TextInput) -> bool {
2700 input.handle_event(&key(KeyCode::Up))
2701 }
2702
2703 fn down(input: &mut TextInput) -> bool {
2704 input.handle_event(&key(KeyCode::Down))
2705 }
2706
2707 #[test]
2708 fn up_recalls_previous_entry() {
2709 let mut input = TextInput::new().with_history(10);
2710 typ(&mut input, "one");
2711 submit_and_clear(&mut input);
2712 typ(&mut input, "two");
2713 submit_and_clear(&mut input);
2714
2715 assert!(up(&mut input));
2716 assert_eq!(input.value(), "two");
2717 assert!(up(&mut input));
2718 assert_eq!(input.value(), "one");
2719 assert!(!up(&mut input));
2722 assert_eq!(input.value(), "one");
2723 assert_eq!(input.history().collect::<Vec<_>>(), vec!["one", "two"]);
2724 }
2725
2726 #[test]
2727 fn down_returns_to_draft() {
2728 let mut input = TextInput::new().with_history(10);
2729 typ(&mut input, "one");
2730 submit_and_clear(&mut input);
2731 typ(&mut input, "two");
2732 submit_and_clear(&mut input);
2733 typ(&mut input, "dr");
2735
2736 assert!(up(&mut input));
2737 assert_eq!(input.value(), "two");
2738 assert!(up(&mut input));
2739 assert_eq!(input.value(), "one");
2740 assert!(down(&mut input));
2741 assert_eq!(input.value(), "two");
2742 assert!(down(&mut input));
2743 assert_eq!(
2744 input.value(),
2745 "dr",
2746 "past the newest entry the draft returns"
2747 );
2748 assert!(!down(&mut input));
2750 assert_eq!(input.value(), "dr");
2751 }
2752
2753 #[test]
2754 fn history_dedups_consecutive() {
2755 let mut input = TextInput::new().with_history(10);
2756 for value in ["a", "a", "b", "a"] {
2757 input.set_value(value);
2758 input.push_history();
2759 }
2760 assert_eq!(input.history().collect::<Vec<_>>(), vec!["a", "b", "a"]);
2762 }
2763
2764 #[test]
2765 fn history_caps_at_capacity() {
2766 let mut input = TextInput::new().with_history(3);
2767 for value in ["a", "b", "c", "d", "e"] {
2768 input.set_value(value);
2769 input.push_history();
2770 }
2771 assert_eq!(input.history_capacity(), Some(3));
2772 assert_eq!(input.history().collect::<Vec<_>>(), vec!["c", "d", "e"]);
2773 }
2774
2775 #[test]
2776 fn submit_resets_cursor() {
2777 let mut input = TextInput::new().with_history(10);
2778 typ(&mut input, "aa");
2779 submit_and_clear(&mut input);
2780 typ(&mut input, "bb");
2781 submit_and_clear(&mut input);
2782
2783 assert!(up(&mut input));
2785 assert_eq!(input.value(), "bb");
2786 assert!(up(&mut input));
2787 assert_eq!(input.value(), "aa");
2788
2789 submit_and_clear(&mut input);
2793 assert!(up(&mut input));
2794 assert_eq!(input.value(), "aa", "recall restarts at the newest entry");
2795 assert!(up(&mut input));
2798 assert_eq!(input.value(), "bb");
2799 }
2800
2801 #[test]
2802 fn typing_after_recall_clears_cursor() {
2803 let mut input = TextInput::new().with_history(10);
2804 typ(&mut input, "one");
2805 submit_and_clear(&mut input);
2806 typ(&mut input, "two");
2807 submit_and_clear(&mut input);
2808
2809 assert!(up(&mut input));
2810 assert_eq!(input.value(), "two");
2811 typ(&mut input, "x");
2814 assert_eq!(input.value(), "twox");
2815 assert!(up(&mut input));
2816 assert_eq!(input.value(), "two", "Up restarts recall from the newest");
2817 assert!(down(&mut input));
2818 assert_eq!(
2819 input.value(),
2820 "twox",
2821 "Down past the newest restores the edited draft"
2822 );
2823 }
2824
2825 #[test]
2826 fn empty_submit_not_recorded() {
2827 let mut input = TextInput::new().with_history(10);
2828 input.handle_event(&key(KeyCode::Enter));
2830 typ(&mut input, "x");
2831 submit_and_clear(&mut input);
2832 assert_eq!(input.history().collect::<Vec<_>>(), vec!["x"]);
2833 }
2834
2835 #[test]
2836 fn no_history_leaves_arrows_for_the_parent() {
2837 let mut input = TextInput::new();
2840 assert!(!input.handle_event(&key(KeyCode::Up)));
2841 assert!(!input.handle_event(&key(KeyCode::Down)));
2842 assert!(!input.handle_event(&key(KeyCode::Enter)));
2843 assert_eq!(input.history_capacity(), None);
2844 }
2845
2846 proptest! {
2847 #![proptest_config(ProptestConfig::with_cases(512))]
2848
2849 #[test]
2852 fn updown_sequences_never_panic_and_end_in_draft(
2853 entries in prop::collection::vec("[a-c]{1,3}", 0..8),
2854 draft in "[a-c]{0,3}",
2855 ups in 0usize..12,
2856 ) {
2857 let mut input = TextInput::new().with_history(16);
2858 for entry in &entries {
2859 input.set_value(entry.clone());
2860 input.push_history();
2861 }
2862 input.clear();
2863 input.set_value(draft.clone());
2864
2865 for _ in 0..ups {
2866 input.handle_event(&key(KeyCode::Up));
2867 }
2868 for _ in 0..(ups + entries.len() + 2) {
2870 input.handle_event(&key(KeyCode::Down));
2871 }
2872 prop_assert_eq!(input.value(), draft.as_str());
2873 }
2874 }
2875 }
2876}