Skip to main content

ftui_widgets/
input.rs

1#![forbid(unsafe_code)]
2
3//! Text input widget.
4//!
5//! A single-line text input field with cursor management, scrolling, selection,
6//! word-level operations, and styling. Grapheme-cluster aware for correct Unicode handling.
7
8use 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/// A single-line text input widget.
22#[derive(Debug, Clone, Default)]
23pub struct TextInput {
24    /// Unique ID for undo tracking.
25    undo_id: UndoWidgetId,
26    /// Text value.
27    value: String,
28    /// Cursor position (grapheme index).
29    cursor: usize,
30    /// Scroll offset (visual cells) for horizontal scrolling.
31    scroll_cells: std::cell::Cell<usize>,
32    /// Selection anchor (grapheme index). When set, selection spans from anchor to cursor.
33    selection_anchor: Option<usize>,
34    /// Active IME composition text (preedit), if any.
35    ime_composition: Option<String>,
36    /// Placeholder text.
37    placeholder: String,
38    /// Mask character for password mode.
39    mask_char: Option<char>,
40    /// Maximum length in graphemes (None = unlimited).
41    max_length: Option<usize>,
42    /// Base style.
43    style: Style,
44    /// Cursor style.
45    cursor_style: Style,
46    /// Placeholder style.
47    placeholder_style: Style,
48    /// Selection highlight style.
49    selection_style: Style,
50    /// Whether the input is focused (controls cursor output).
51    focused: bool,
52    /// Optional command-line style entry recall (see [`InputHistory`]).
53    ///
54    /// This is entry recall — the shell-style Up/Down list of submitted values
55    /// — and is distinct from edit undo/redo, which lives on
56    /// [`create_text_edit_command`](TextInput::create_text_edit_command) +
57    /// [`ftui_runtime::undo::HistoryManager`]. It is `None` until
58    /// [`with_history`](TextInput::with_history) opts in.
59    history: Option<InputHistory>,
60}
61
62/// A bounded, command-line style entry-recall buffer for [`TextInput`].
63///
64/// This is the shell "type a command, press Enter, later press Up to get it
65/// back" facility, deliberately *not* built on the runtime's undo
66/// [`HistoryManager`](ftui_runtime::undo::HistoryManager): recall is a list of
67/// submitted strings with a single recall cursor, whereas undo is a stack of
68/// reversible edit commands. The two are complementary — undo walks the edits
69/// within one line, recall walks between previously submitted lines.
70///
71/// Semantics match a typical shell with `ignoredups`:
72/// - `push` records a non-empty value, skipping a run of an identical value,
73///   evicting the oldest once capacity is exceeded, and ending any recall.
74/// - `recall_older` (Up) stores the in-progress draft on first use, then walks
75///   toward older entries, stopping at the oldest.
76/// - `recall_newer` (Down) walks toward newer entries and, once past the
77///   newest, restores the saved draft and ends recall.
78/// - Editing the value ends recall (the edited text becomes the new draft).
79#[derive(Debug, Clone)]
80pub struct InputHistory {
81    /// Submitted values, oldest at the front, newest at the back.
82    entries: VecDeque<String>,
83    /// Maximum retained entries (at least 1).
84    cap: usize,
85    /// Index into `entries` while recalling; `None` when not recalling.
86    cursor: Option<usize>,
87    /// The in-progress line saved when recall began, restored on Down past the
88    /// newest entry.
89    draft: Option<String>,
90}
91
92impl InputHistory {
93    /// A new empty history retaining up to `capacity` entries (clamped to at
94    /// least 1).
95    #[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    /// Record a submitted value. Empty values and a value equal to the most
106    /// recent entry are not stored (`ignoredups`); the oldest entry is evicted
107    /// once capacity is exceeded. Either way, any active recall ends.
108    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    /// Recall the previous (older) entry, saving `current` as the draft on the
120    /// first step. Returns the entry to display, or `None` when there is
121    /// nothing to recall. Stops at the oldest entry.
122    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    /// Recall the next (newer) entry. Once past the newest entry, restores the
138    /// saved draft and ends recall. Returns `None` when no recall is active.
139    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    /// End any active recall without changing the entries. Called when the
154    /// value is edited: the edited text becomes the new draft on the next Up.
155    fn note_edit(&mut self) {
156        self.cursor = None;
157        self.draft = None;
158    }
159
160    /// The retained entries, oldest first.
161    pub fn entries(&self) -> impl Iterator<Item = &str> {
162        self.entries.iter().map(String::as_str)
163    }
164
165    /// Number of retained entries.
166    #[must_use]
167    pub fn len(&self) -> usize {
168        self.entries.len()
169    }
170
171    /// Whether no entries are retained.
172    #[must_use]
173    pub fn is_empty(&self) -> bool {
174        self.entries.is_empty()
175    }
176
177    /// Drop all entries and end any recall.
178    pub fn clear(&mut self) {
179        self.entries.clear();
180        self.cursor = None;
181        self.draft = None;
182    }
183
184    /// The maximum number of retained entries.
185    #[must_use]
186    pub fn capacity(&self) -> usize {
187        self.cap
188    }
189}
190
191impl TextInput {
192    /// Create a new empty text input.
193    pub fn new() -> Self {
194        Self::default()
195    }
196
197    // --- Builder methods ---
198
199    /// Set the text value (builder).
200    #[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    /// Set the placeholder text (builder).
209    #[must_use]
210    pub fn with_placeholder(mut self, placeholder: impl Into<String>) -> Self {
211        self.placeholder = placeholder.into();
212        self
213    }
214
215    /// Set password mode with mask character (builder).
216    #[must_use]
217    pub fn with_mask(mut self, mask: char) -> Self {
218        self.mask_char = Some(mask);
219        self
220    }
221
222    /// Set maximum length in graphemes (builder).
223    #[must_use]
224    pub fn with_max_length(mut self, max: usize) -> Self {
225        self.max_length = Some(max);
226        self
227    }
228
229    /// Enable command-line style entry recall with the given capacity (builder).
230    ///
231    /// With history enabled the widget records the value on `Enter` and recalls
232    /// previous entries with `Up`/`Down` (see [`InputHistory`]). This is entry
233    /// recall, separate from edit undo/redo
234    /// ([`create_text_edit_command`](TextInput::create_text_edit_command) +
235    /// [`ftui_runtime::undo::HistoryManager`]). Recall state is session-only and
236    /// is deliberately not part of [`TextInputSnapshot`]; a consumer that wants
237    /// persistent history stores [`history`](TextInput::history) itself.
238    #[must_use]
239    pub fn with_history(mut self, capacity: usize) -> Self {
240        self.history = Some(InputHistory::new(capacity));
241        self
242    }
243
244    /// Set base style (builder).
245    #[must_use]
246    pub fn with_style(mut self, style: Style) -> Self {
247        self.style = style;
248        self
249    }
250
251    /// Set cursor style (builder).
252    #[must_use]
253    pub fn with_cursor_style(mut self, style: Style) -> Self {
254        self.cursor_style = style;
255        self
256    }
257
258    /// Set placeholder style (builder).
259    #[must_use]
260    pub fn with_placeholder_style(mut self, style: Style) -> Self {
261        self.placeholder_style = style;
262        self
263    }
264
265    /// Set selection style (builder).
266    #[must_use]
267    pub fn with_selection_style(mut self, style: Style) -> Self {
268        self.selection_style = style;
269        self
270    }
271
272    /// Set whether the input is focused (builder).
273    #[must_use]
274    pub fn with_focused(mut self, focused: bool) -> Self {
275        self.focused = focused;
276        self
277    }
278
279    // --- Value access ---
280
281    /// Get the current value.
282    pub fn value(&self) -> &str {
283        &self.value
284    }
285
286    /// Set the value, clamping cursor to valid range.
287    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    /// Clear all text.
296    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    /// Get the cursor position (grapheme index).
304    #[inline]
305    pub fn cursor(&self) -> usize {
306        self.cursor
307    }
308
309    /// Check if the input is focused.
310    #[inline]
311    pub fn focused(&self) -> bool {
312        self.focused
313    }
314
315    /// Set focus state.
316    pub fn set_focused(&mut self, focused: bool) {
317        self.focused = focused;
318    }
319
320    /// Record the current value in the entry-recall history, if enabled.
321    ///
322    /// This is what `Enter` does automatically when history is enabled; it is
323    /// also exposed so a consumer with its own submit key can record entries.
324    /// Empty values and a value equal to the most recent entry are skipped
325    /// (`ignoredups`), and any active recall ends.
326    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    /// The recorded entry-recall history, oldest first (empty if history is not
334    /// enabled). This is entry recall, not edit undo/redo.
335    pub fn history(&self) -> impl Iterator<Item = &str> {
336        self.history.iter().flat_map(InputHistory::entries)
337    }
338
339    /// Drop all recorded entry-recall history (no-op if not enabled).
340    pub fn clear_history(&mut self) {
341        if let Some(history) = self.history.as_mut() {
342            history.clear();
343        }
344    }
345
346    /// The entry-recall history capacity, or `None` if history is not enabled.
347    #[must_use]
348    pub fn history_capacity(&self) -> Option<usize> {
349        self.history.as_ref().map(InputHistory::capacity)
350    }
351
352    /// Recall the previous (older) history entry into the value. Returns whether
353    /// the value changed (so a parent keeps its own Up handling when recall is
354    /// already at the oldest entry).
355    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(&current)) {
358            Some(recalled) if recalled != current => {
359                self.set_value_from_recall(recalled);
360                true
361            }
362            _ => false,
363        }
364    }
365
366    /// Recall the next (newer) history entry, or the saved draft once past the
367    /// newest, into the value. Returns whether the value changed.
368    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    /// Replace the value from a recall without touching the history state (so a
380    /// recall does not count as an edit that ends recall).
381    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    /// Get the cursor screen position relative to a render area.
389    ///
390    /// Returns `(x, y)` where x is the column and y is the row.
391    /// Useful for `Frame::set_cursor()`.
392    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    /// Get selected text, if any.
404    #[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    /// Start an IME composition session.
414    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    /// Update active IME preedit text.
424    ///
425    /// Starts composition automatically if none is active.
426    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    /// Commit active IME preedit text into the input value.
436    ///
437    /// Returns `true` if a composition session existed (even if empty).
438    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    /// Cancel the active IME composition session.
454    ///
455    /// Returns `true` if a composition session was active.
456    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    /// Get active IME preedit text, if any.
466    #[must_use]
467    pub fn ime_composition(&self) -> Option<&str> {
468        self.ime_composition.as_deref()
469    }
470
471    // --- Event handling ---
472
473    /// Handle a terminal event.
474    ///
475    /// Returns `true` if the state changed.
476    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                // For replacement pastes under a max-length constraint, reject
488                // oversized payloads before deleting the selection.
489                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        // Command-line style entry recall. Only plain Up/Down/Enter are claimed,
551        // and only when history is enabled, so parents keep their own Up/Down
552        // (e.g. list navigation) whenever recall does not apply. Up/Down return
553        // `true` only when the value actually changes.
554        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                    // Enter records the entry but does not itself change the
560                    // value; the parent keeps whatever submit semantics it had.
561                    self.push_history();
562                    return false;
563                }
564                _ => {}
565            }
566        }
567
568        // Snapshot the value so a genuine edit (not a cursor move) can end an
569        // active recall; only taken when history is enabled.
570        let value_before = if self.history.is_some() {
571            Some(self.value.clone())
572        } else {
573            None
574        };
575
576        // Command/Windows-key chords belong to the host, not the field. Only
577        // CTRL used to be excluded, so on macOS every Cmd+<letter> shortcut
578        // typed its letter: Cmd+V inserted a literal "v" next to the paste.
579        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            // Ctrl+A: select all
587            KeyCode::Char('a') if ctrl => {
588                self.select_all();
589                true
590            }
591            // Ctrl+W: delete word back
592            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        // A genuine edit (value changed, not a cursor move) ends any active
659        // recall; the edited text becomes the new draft on the next Up.
660        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    // --- Editing operations ---
731
732    fn sanitize_input_text(text: &str) -> String {
733        // Map line breaks/tabs to spaces, filter other control chars
734        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    /// Insert text at the current cursor position.
747    ///
748    /// This method:
749    /// - Replaces newlines and tabs with spaces.
750    /// - Filters out other control characters.
751    /// - Respects `max_length` (truncating if necessary).
752    /// - Efficiently inserts the result in one operation.
753    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                // Allow trying to insert 1 grapheme to see if it merges (combining char)
766                1
767            } else {
768                max - current_count
769            }
770        } else {
771            usize::MAX
772        };
773
774        // Calculate grapheme count of new text to see if we need to truncate
775        let new_graphemes = clean_text.graphemes(true).count();
776        let to_insert = if new_graphemes > avail {
777            // Find byte index to truncate at
778            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        // Check if we exceeded max_length
796        let new_total = self.grapheme_count();
797        if let Some(max) = self.max_length
798            && new_total > max
799        {
800            // Revert change
801            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        // Strict control character filtering to prevent terminal corruption
814        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        // Check constraints
826        if let Some(max) = self.max_length
827            && new_count > max
828        {
829            // Revert change
830            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        // Use standard movement logic to find start of deletion
876        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        // Use standard movement logic to find end of deletion
894        self.move_cursor_word_right(false);
895        let new_cursor = self.cursor;
896        // Reset cursor to start (deletion happens forward from here)
897        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    // --- Selection ---
911
912    /// Select all text.
913    pub fn select_all(&mut self) {
914        self.selection_anchor = Some(0);
915        self.cursor = self.grapheme_count();
916    }
917
918    /// Delete selected text. No-op if no selection.
919    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    // --- Cursor movement ---
957
958    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    // --- Internal helpers ---
1076
1077    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            // Logical order: TextInput renders its value in logical order, so
1114            // the caret must be measured the same way (#102).
1115            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            // Ensure the character BEFORE the cursor is also fully visible
1140            // (prevent "hole" artifact for wide characters where start < scroll)
1141            let prev_width = self.prev_grapheme_width();
1142            let max_scroll_for_prev = cursor_visual.saturating_sub(prev_width);
1143
1144            // Only enforce wide-char visibility if the viewport is wide enough to show
1145            // both the character and the cursor. Prioritize cursor visibility otherwise.
1146            if viewport_width > prev_width {
1147                scroll = candidate_scroll.min(max_scroll_for_prev);
1148            } else {
1149                scroll = candidate_scroll;
1150            }
1151        }
1152
1153        // Sanitize: ensure scroll aligns with grapheme boundaries
1154        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 scroll is in the middle of this grapheme: [pos < scroll < next_pos]
1169            if pos < scroll && scroll < next_pos {
1170                // Try snapping to the start of the character to keep it visible.
1171                // Only allowed if the cursor remains visible on the right.
1172                // Cursor visibility condition: cursor_visual < new_scroll + viewport_width
1173                if cursor_visual <= pos + viewport_width {
1174                    return pos;
1175                } else {
1176                    // Cannot snap left without hiding cursor. Snap right (hide the character).
1177                    return next_pos;
1178                }
1179            }
1180
1181            if next_pos > scroll {
1182                // Passed the scroll point, no split found.
1183                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        // Not for an empty area: nothing lands on screen for one, so a node
1194        // would describe a widget that was never drawn, and every such node
1195        // collides on the id of the same empty rect
1196        // (bd-a11y-sibling-id-collision-6zqd2).
1197        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        // TextInput is essential — always render content, but skip styling
1218        // at NoStyling+. At Skeleton, still render the raw text value.
1219        // We explicitly DO NOT check deg.render_content() here because this widget is essential.
1220        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        // Use arena allocation when available to avoid per-frame heap churn.
1228        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        // Render content
1244        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                // Fully scrolled out (left)
1260                if visual_x + w <= effective_scroll {
1261                    visual_x += w;
1262                    continue;
1263                }
1264
1265                // Partially scrolled out (left) - skip drawing
1266                if visual_x < effective_scroll {
1267                    visual_x += w;
1268                    continue;
1269                }
1270
1271                let rel_x = visual_x - effective_scroll;
1272
1273                // Fully clipped (right)
1274                if rel_x >= viewport_width {
1275                    break;
1276                }
1277
1278                // Partially clipped (right) - skip drawing
1279                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                // Fully scrolled out (left)
1344                if visual_x + w <= effective_scroll {
1345                    visual_x += w;
1346                    continue;
1347                }
1348
1349                // Partially scrolled out (left) - skip drawing
1350                if visual_x < effective_scroll {
1351                    visual_x += w;
1352                    continue;
1353                }
1354
1355                let rel_x = visual_x - effective_scroll;
1356
1357                // Fully clipped (right)
1358                if rel_x >= viewport_width {
1359                    break;
1360                }
1361
1362                // Partially clipped (right) - skip drawing
1363                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            // Set cursor style at cursor position
1392            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                        // At NoStyling, just use reverse video for cursor
1398                        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                        // Default: toggle reverse video for cursor visibility
1404                        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
1424// ============================================================================
1425// Accessibility
1426// ============================================================================
1427
1428impl 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            // Don't expose masked values to screen readers.
1437            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// ============================================================================
1461// Undo Support Implementation
1462// ============================================================================
1463
1464/// Snapshot of TextInput state for undo.
1465///
1466/// This captures the editable state (value, cursor, selection). It deliberately
1467/// does **not** include the entry-recall [`InputHistory`]: recall entries are
1468/// session state, not per-edit widget state, so undo/redo never rewinds the
1469/// recall list. A consumer that wants persistent recall stores
1470/// [`TextInput::history`] itself.
1471#[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); // Reset scroll on restore
1497            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    /// Create an undo command for the given text edit operation.
1556    ///
1557    /// This creates a command that can be added to a [`HistoryManager`] for undo/redo support.
1558    /// The command includes callbacks that will be called when the operation is undone or redone.
1559    ///
1560    /// # Example
1561    ///
1562    /// ```ignore
1563    /// let mut input = TextInput::new();
1564    /// let old_value = input.value().to_string();
1565    ///
1566    /// // Perform the edit
1567    /// input.set_value("new text");
1568    ///
1569    /// // Create undo command
1570    /// if let Some(cmd) = input.create_text_edit_command(TextEditOperation::SetValue {
1571    ///     old_value,
1572    ///     new_value: "new text".to_string(),
1573    /// }) {
1574    ///     history.push(cmd);
1575    /// }
1576    /// ```
1577    ///
1578    /// [`HistoryManager`]: ftui_runtime::undo::HistoryManager
1579    #[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    /// Get the undo widget ID.
1591    ///
1592    /// This can be used to associate undo commands with this widget instance.
1593    #[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        // "hello world test"
1837        //                 ^ (16)
1838        input.move_cursor_word_left(false);
1839        assert_eq!(input.cursor(), 12); // "hello world |test"
1840
1841        input.move_cursor_word_left(false);
1842        assert_eq!(input.cursor(), 6); // "hello |world test"
1843
1844        input.move_cursor_word_left(false);
1845        assert_eq!(input.cursor(), 0); // "|hello world test"
1846    }
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        // "|hello world test"
1853
1854        input.move_cursor_word_right(false);
1855        assert_eq!(input.cursor(), 6); // "hello |world test"
1856
1857        input.move_cursor_word_right(false);
1858        assert_eq!(input.cursor(), 12); // "hello world |test"
1859
1860        input.move_cursor_word_right(false);
1861        assert_eq!(input.cursor(), 16); // "hello world test|"
1862    }
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        // "|hello, world"
1869
1870        input.move_cursor_word_right(false);
1871        assert_eq!(input.cursor(), 5); // "hello|, world"
1872
1873        input.move_cursor_word_right(false);
1874        assert_eq!(input.cursor(), 7); // "hello, |world"
1875
1876        input.move_cursor_word_right(false);
1877        assert_eq!(input.cursor(), 12); // "hello, world|"
1878
1879        input.move_cursor_word_left(false);
1880        assert_eq!(input.cursor(), 7); // "hello, |world"
1881    }
1882
1883    #[test]
1884    fn test_delete_word_back() {
1885        let mut input = TextInput::new().with_value("hello world");
1886        // "hello world|"
1887        input.delete_word_back();
1888        assert_eq!(input.value(), "hello "); // Deleted "world"
1889
1890        // "hello |" — word-left skips space and deletes the preceding word
1891        input.delete_word_back();
1892        assert_eq!(input.value(), ""); // Deleted "hello "
1893    }
1894
1895    #[test]
1896    fn test_delete_word_forward() {
1897        let mut input = TextInput::new().with_value("hello world");
1898        input.cursor = 0;
1899        // "|hello world" — word-right skips "hello" then space
1900        input.delete_word_forward();
1901        assert_eq!(input.value(), "world"); // Deleted "hello "
1902
1903        input.delete_word_forward();
1904        assert_eq!(input.value(), ""); // Deleted "world"
1905    }
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; // after the emoji grapheme
1968        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        // Cursor should be positioned at the end of "hello" (5 chars)
2275        // area.x = 5, cursor_visual_pos = 5, effective_scroll = 0
2276        // So cursor_screen_x = 5 + 5 = 10
2277        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; // After "he"
2287        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        // Cursor after "he" = visual position 2
2293        assert_eq!(frame.cursor_position, Some((2, 0)));
2294    }
2295
2296    // ========================================================================
2297    // Undo Support Tests
2298    // ========================================================================
2299
2300    #[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        // Modify the input
2324        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        // Restore from snapshot
2332        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        // "hello" with " world" inserted at position 2 = "he" + " world" + "llo"
2345        assert_eq!(input.value(), "he worldllo");
2346        assert_eq!(input.cursor(), 8); // cursor moved by inserted text length (6 graphemes)
2347    }
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); // Delete " world"
2355        assert_eq!(input.value(), "hello");
2356        assert_eq!(input.cursor(), 5); // cursor clamped to end of remaining text
2357    }
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        // macOS sends Cmd as SUPER. Cmd+V is the host's paste shortcut; the
2375        // field must not also receive a literal "v" beside the pasted text.
2376        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        // A plain character of the same letter still types.
2384        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        // Paste "def" (3 chars). Should be truncated to "de" (2 chars) to fit max 5.
2414        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        // Paste combining acute accent (U+0301). Should merge with 'e' -> 'é'.
2425        // Grapheme count stays 1. Cursor stays 1 (after the merged grapheme).
2426        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; // between a and b
2437        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}"; // Ideographic space, Width 2
2450        let mut input = TextInput::new().with_value(wide_char).with_focused(true);
2451        input.cursor = 1; // After the char
2452
2453        // Viewport width 2.
2454        // cursor_visual_pos = 2.
2455        // effective_scroll: 2 >= 0 + 2 -> scroll = 1.
2456        // Render: char at 0..2. 0 < 1 -> Skipped!
2457        // Expectation: We should see it.
2458        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        // If bug exists, this assertion will fail because cell is empty/default
2465        assert!(!cell.is_empty(), "Wide char should be visible");
2466    }
2467
2468    #[test]
2469    fn test_wide_char_scroll_snapping() {
2470        // Verify that effective_scroll snaps to grapheme boundaries
2471        let _input = TextInput::new().with_value("a\u{3000}b"); // "a", "ID_SPACE", "b"
2472        // Widths: 1, 2, 1. Positions: 0, 1, 3. Total 4.
2473
2474        // Force scroll to 2 (middle of wide char)
2475        // We can't directly set scroll_cells (private), but we can manipulate cursor/viewport
2476        // to force the logic.
2477
2478        // Viewport width 2.
2479        // Move cursor to end (pos 4).
2480        // effective_scroll tries to show cursor.
2481        // cursor_visual = 4.
2482        // candidate = 4 - 2 + 1 = 3.
2483        // prev_width (b) = 1. max_scroll_for_prev = 4 - 1 = 3.
2484        // scroll = 3.
2485        // At scroll 3, we show "b" (pos 3).
2486        //
2487        // Let's try to force it to land on 2.
2488        // value: "\u{3000}a" (Wide, a).
2489        // Pos: 0, 2. Total 3.
2490        // Cursor at 2 (after wide char).
2491        // Viewport 1.
2492        // cursor_visual = 2.
2493        // candidate = 2 - 1 + 1 = 2.
2494        // prev_width = 2. max_scroll_for_prev = 2 - 2 = 0.
2495        // scroll = min(2, 0) = 0.
2496        // It snaps to 0!
2497
2498        // Let's use the internal logic test if possible, or observe via render.
2499
2500        let wide_char = "\u{3000}";
2501        let text = format!("a{wide_char}b");
2502        let mut input = TextInput::new().with_value(&text);
2503
2504        // We simulate the logic by calling effective_scroll via render logic paths
2505        // or by unit testing the private method if we expose it?
2506        // No, we rely on behavior.
2507
2508        // Case 1: Scroll lands on 2 (start of wide char). Valid.
2509        // Case 2: Scroll lands on 1 (start of 'a' is 0, wide is 1..3).
2510        // Scroll 1 means we skip 'a'. Wide char moves to x=0. Valid.
2511
2512        // Wait, grapheme 1 starts at visual pos 1.
2513        // If scroll is 2. We skip 'a' (1) and half of wide char?
2514        // No. "a" width 1. "Wide" width 2.
2515        // Visual positions: "a"@[0], "Wide"@[1,2].
2516        // If scroll = 1. "a" is at -1. "Wide" is at 0,1. Visible.
2517        // If scroll = 2. "a" at -2. "Wide" at -1,0.
2518        //   Render loop: g="Wide", w=2. visual_x starts at 1.
2519        //   visual_x (1) < scroll (2). visual_x += 2 -> 3. Continue.
2520        //   Wide char is SKIPPED.
2521        //   We see nothing (or 'b').
2522        //   This is the "pop" artifact.
2523
2524        // We want scroll to NOT be 2. It should be 1 or 3.
2525
2526        // How to force scroll=2?
2527        // Cursor at 3 (after 'b'?).
2528        // 'b' is at 3. width 1.
2529        // If we want 'b' visible at x=0. Scroll must be 3.
2530
2531        // We need a setup where candidate_scroll lands on 2.
2532        // Let cursor be at 4 (end of string).
2533        // Viewport 2.
2534        // candidate = 4 - 2 + 1 = 3.
2535
2536        // Let cursor be at 3 (start of b).
2537        // candidate = 3 - 2 + 1 = 2.
2538        // If we force scroll=2.
2539
2540        input.cursor = 3; // Before 'b', after wide char.
2541        let _area = Rect::new(0, 0, 2, 1); // Width 2
2542        // effective_scroll logic:
2543        // cursor_visual = 3.
2544        // candidate = 3 - 2 + 1 = 2.
2545        // prev_width (Wide) = 2. max_scroll_for_prev = 3 - 2 = 1.
2546        // min(2, 1) = 1.
2547        // The existing logic `max_scroll_for_prev` ALREADY protects the previous char!
2548
2549        // So when does the bug happen?
2550        // When we are NOT near the cursor?
2551        // No, effective_scroll is driven by cursor.
2552
2553        // What if we have multiple wide chars?
2554        // "\u{3000}\u{3000}" (Wide, Wide).
2555        // Widths: 2, 2. Pos: 0, 2. Total 4.
2556        // Cursor at 4. Viewport 3.
2557        // candidate = 4 - 3 + 1 = 2.
2558        // prev (Wide #2) width 2. max_for_prev = 4 - 2 = 2.
2559        // scroll = 2.
2560        // Render:
2561        //   Wide#1 @ 0..2. scroll=2. 0 < 2. Skipped. Correct.
2562        //   Wide#2 @ 2..4. scroll=2. 2 >= 2. Rendered at 0. Correct.
2563
2564        // Wait, what if scroll lands *inside* a wide char?
2565        // Text: "a" (1) + "Wide" (2). Total 3.
2566        // Cursor at 3. Viewport 2.
2567        // candidate = 3 - 2 + 1 = 2.
2568        // prev (Wide) width 2. max_for_prev = 3 - 2 = 1.
2569        // scroll = 1.
2570        // Render:
2571        //   'a' @ 0. < 1. Skipped.
2572        //   Wide @ 1. >= 1. Rendered at 0.
2573        // Correct.
2574
2575        // So `max_scroll_for_prev` protects the char *immediately* before the cursor.
2576        // But what about chars before THAT?
2577        // Text: "Wide1" (2) + "Wide2" (2).
2578        // Cursor at 4. Viewport 2.
2579        // scroll = 2.
2580        // Wide1 @ 0. < 2. Skipped.
2581        // Wide2 @ 2. >= 2. Rendered.
2582
2583        // Is it possible for scroll to land on 1?
2584        // If we manually scroll? Input widget doesn't expose manual scroll.
2585        // It relies on cursor position.
2586
2587        // What if viewport is 1?
2588        // Cursor at 4.
2589        // candidate = 4 - 1 + 1 = 4.
2590        // max_for_prev = 4 - 2 = 2.
2591        // scroll = 2.
2592        // Wide1 @ 0. Skipped.
2593        // Wide2 @ 2. Rendered at 0. (Clipped to width 1).
2594
2595        // It seems `max_scroll_for_prev` handles the "hole" issue for the active character.
2596        // But the user issue mentioned "partial scrolling".
2597
2598        // Let's assume the fix `snap_scroll_to_grapheme_boundary` is robust regardless.
2599        // It prevents ANY scroll value from landing inside a grapheme.
2600    }
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        // Test the scenario: [Char A][Char B][Char C]
2658        // Viewport width 1.
2659        // Scroll is at B.
2660        // Move cursor to A (left).
2661        // Cursor visual pos = 0.
2662        // effective_scroll must become 0.
2663
2664        let mut input = TextInput::new().with_value("ABC");
2665        input.cursor = 1; // At B
2666
2667        // Force internal scroll to 1 (B) by rendering with narrow viewport
2668        // We can't set private scroll_cells directly, but we can simulate state
2669        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); // Scroll should be 1
2673
2674        // Now move left
2675        input.move_cursor_left(); // Cursor at A (0)
2676
2677        // Render again
2678        input.render(area, &mut frame);
2679
2680        // Cell should be A
2681        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        // "abc", max 3. Select "b". Insert "de".
2688        // Should delete "b" -> "ac".
2689        // Try insert "de" -> "adec" (len 4).
2690        // Should revert insert -> "ac".
2691
2692        let mut input = TextInput::new().with_value("abc").with_max_length(3);
2693        input.selection_anchor = Some(1); // "b" start
2694        input.cursor = 2; // "b" end
2695
2696        // Simulate paste "de"
2697        let event = Event::Paste(ftui_core::event::PasteEvent::new("de", false));
2698        input.handle_event(&event);
2699
2700        // Oversized pastes replace nothing and leave selection intact.
2701        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        /// Submit the current value as a prompt would: Enter records it, then
2721        /// the owner clears the field for the next entry.
2722        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            // At the oldest entry Up reports "unchanged" so a parent keeps its
2748            // own Up handling.
2749            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            // An unsent draft in progress when recall starts.
2762            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            // Past the draft there is nothing newer.
2777            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            // Consecutive duplicates collapse; a non-adjacent repeat is kept.
2789            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            // Recall back to the oldest entry.
2812            assert!(up(&mut input));
2813            assert_eq!(input.value(), "bb");
2814            assert!(up(&mut input));
2815            assert_eq!(input.value(), "aa");
2816
2817            // Submitting the recalled "aa" records it (its predecessor is "bb",
2818            // so it is not a consecutive duplicate) and ends recall, leaving
2819            // entries [aa, bb, aa]. The next Up must restart from the newest.
2820            submit_and_clear(&mut input);
2821            assert!(up(&mut input));
2822            assert_eq!(input.value(), "aa", "recall restarts at the newest entry");
2823            // A second Up steps to the entry before the newest, proving the
2824            // cursor was reset to the end rather than left at the oldest.
2825            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            // Editing the recalled text ends recall; the edited text is the new
2840            // draft.
2841            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            // Enter on an empty field records nothing.
2857            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            // Up still recalls "first" as the newest entry
2879            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            // Without with_history, Up/Down/Enter are not claimed (return false),
2896            // so a parent keeps list navigation and submit handling.
2897            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            /// Arbitrary Up/Down sequences never panic, and pressing Down enough
2908            /// times after any sequence of Ups/Downs always lands back on the unsent draft.
2909            #[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                // Exhaust recall in the newer direction.
2939                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        /// #102: TextInput draws its value in logical order, so its keys must
2947        /// move the caret in logical order too (the v0.8.0 behavior), with or
2948        /// without the `bidi` feature, and the caret column must be the summed
2949        /// width of whole grapheme clusters.
2950        #[test]
2951        fn input_rtl_keys_move_in_logical_order_like_the_renderer() {
2952            // Arabic text: "مرحبا" (5 characters, pure RTL)
2953            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            // a + combining acute, space, Hebrew: grapheme 2 sits after "a\u{301} ".
2975            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            // Multi-scalar emoji cluster counts its full width once.
2982            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}