Skip to main content

ftui_widgets/
textarea.rs

1//! Multi-line text editing widget.
2//!
3//! [`TextArea`] wraps [`Editor`] for text manipulation and
4//! provides Frame-based rendering with viewport scrolling and cursor display.
5//!
6//! # Example
7//! ```
8//! use ftui_widgets::textarea::{TextArea, TextAreaState};
9//!
10//! let mut ta = TextArea::new();
11//! ta.insert_text("Hello\nWorld");
12//! assert_eq!(ta.line_count(), 2);
13//! ```
14
15use std::ops::Range;
16use std::sync::Arc;
17use std::time::Duration;
18use web_time::Instant;
19
20use ftui_core::event::{
21    Event, KeyCode, KeyEvent, KeyEventKind, Modifiers, MouseButton, MouseEvent, MouseEventKind,
22};
23use ftui_core::geometry::Rect;
24use ftui_core::gesture::GestureConfig;
25use ftui_render::frame::Frame;
26use ftui_style::Style;
27use ftui_text::editor::{Editor, Selection};
28use ftui_text::wrap::display_width;
29use ftui_text::{CursorNavigator, CursorPosition};
30use unicode_segmentation::UnicodeSegmentation;
31
32use crate::{StatefulWidget, Widget, apply_style, clear_text_area, draw_text_span};
33
34/// Multi-line text editor widget.
35/// A per-line syntax style provider for [`TextArea::with_highlighter`].
36///
37/// Called once per visible logical line per render with `(line_index,
38/// line_text)`, where `line_text` has no trailing newline. It returns byte
39/// ranges into `line_text` paired with a [`Style`] to merge over the base
40/// style (before the selection style, so selection still wins). Ranges may
41/// overlap — a later range wins for a byte it covers. Ranges that fall outside
42/// the line or that do not sit on grapheme boundaries are ignored; an empty
43/// vector means "no highlight". The hook lives entirely in `ftui-widgets` and
44/// knows nothing about any tokenizer.
45pub type LineHighlighter = Arc<dyn Fn(usize, &str) -> Vec<(Range<usize>, Style)> + Send + Sync>;
46
47#[derive(Clone)]
48pub struct TextArea {
49    editor: Editor,
50    /// Placeholder text shown when empty.
51    placeholder: String,
52    /// Whether the widget has input focus.
53    focused: bool,
54    /// Show line numbers in gutter.
55    show_line_numbers: bool,
56    /// Base style.
57    style: Style,
58    /// Cursor line highlight style.
59    cursor_line_style: Option<Style>,
60    /// Selection highlight style.
61    selection_style: Style,
62    /// Placeholder style.
63    placeholder_style: Style,
64    /// Line number style.
65    line_number_style: Style,
66    /// Soft-wrap long lines.
67    ///
68    /// Visual wrapping preserves whitespace and breaks on word boundaries with
69    /// a grapheme fallback for long segments.
70    soft_wrap: bool,
71    /// Maximum height in lines (0 = unlimited / fill area).
72    max_height: usize,
73    /// Viewport scroll anchor (logical_line_idx, visual_wrap_offset).
74    ///
75    /// In soft-wrap mode, this tracks the first visible visual line.
76    /// In no-wrap mode, the second element is ignored (always 0).
77    scroll_anchor: std::cell::Cell<(usize, usize)>,
78    /// Horizontal scroll offset (visual columns).
79    scroll_left: std::cell::Cell<usize>,
80    /// Last viewport height for page movement and visibility checks.
81    #[allow(dead_code)]
82    last_viewport_height: std::cell::Cell<usize>,
83    /// Last viewport width for visibility checks.
84    last_viewport_width: std::cell::Cell<usize>,
85    /// Optional per-line syntax style provider (see [`LineHighlighter`]).
86    highlighter: Option<LineHighlighter>,
87    /// Origin for event timestamps; explicit replay timestamps bypass this clock.
88    undo_clock: Instant,
89    /// Area of the last render, for mapping mouse positions to text.
90    last_area: std::cell::Cell<Rect>,
91    /// The previous left press, for double and triple clicks.
92    last_click: Option<LastClick>,
93    /// A left press inside the area started a drag selection.
94    mouse_selecting: bool,
95}
96
97/// A left press, remembered to count multi-clicks.
98#[derive(Debug, Clone, Copy)]
99struct LastClick {
100    at_ms: u64,
101    x: u16,
102    y: u16,
103    /// 1, 2 or 3: single, double or triple.
104    count: u8,
105}
106
107impl std::fmt::Debug for TextArea {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        f.debug_struct("TextArea")
110            .field("editor", &self.editor)
111            .field("placeholder", &self.placeholder)
112            .field("focused", &self.focused)
113            .field("show_line_numbers", &self.show_line_numbers)
114            .field("style", &self.style)
115            .field("cursor_line_style", &self.cursor_line_style)
116            .field("selection_style", &self.selection_style)
117            .field("placeholder_style", &self.placeholder_style)
118            .field("line_number_style", &self.line_number_style)
119            .field("soft_wrap", &self.soft_wrap)
120            .field("max_height", &self.max_height)
121            .field("scroll_anchor", &self.scroll_anchor)
122            .field("scroll_left", &self.scroll_left)
123            .field("last_viewport_height", &self.last_viewport_height)
124            .field("last_viewport_width", &self.last_viewport_width)
125            .field("highlighter", &self.highlighter.as_ref().map(|_| "<fn>"))
126            .field("last_area", &self.last_area)
127            .field("last_click", &self.last_click)
128            .field("mouse_selecting", &self.mouse_selecting)
129            .finish()
130    }
131}
132
133/// The style of the last range in `spans` that covers `byte`, or `None`.
134///
135/// Ranges are byte ranges into a single line; a later range wins on overlap.
136/// Never panics: offsets outside every range simply return `None`.
137fn style_at(spans: &[(Range<usize>, Style)], byte: usize) -> Option<Style> {
138    spans
139        .iter()
140        .rev()
141        .find(|(range, _)| range.contains(&byte))
142        .map(|(_, style)| *style)
143}
144
145impl Default for TextArea {
146    fn default() -> Self {
147        Self::new()
148    }
149}
150
151/// Render state tracked across frames.
152#[derive(Debug, Clone, Default)]
153pub struct TextAreaState {
154    /// Viewport height from last render.
155    pub last_viewport_height: u16,
156    /// Viewport width from last render.
157    pub last_viewport_width: u16,
158}
159
160#[derive(Debug, Clone)]
161struct WrappedSlice<'a> {
162    text: &'a str,
163    start_byte: usize,
164    start_col: usize,
165    width: usize,
166}
167
168impl TextArea {
169    /// Create a new empty text area.
170    #[must_use]
171    pub fn new() -> Self {
172        Self {
173            editor: Editor::new(),
174            placeholder: String::new(),
175            focused: false,
176            show_line_numbers: false,
177            style: Style::default(),
178            cursor_line_style: None,
179            selection_style: Style::new().reverse(),
180            placeholder_style: Style::new().dim(),
181            line_number_style: Style::new().dim(),
182            soft_wrap: false,
183            max_height: 0,
184            scroll_anchor: std::cell::Cell::new((usize::MAX, 0)), // sentinel
185            scroll_left: std::cell::Cell::new(0),
186            last_viewport_height: std::cell::Cell::new(0),
187            last_viewport_width: std::cell::Cell::new(0),
188            highlighter: None,
189            undo_clock: Instant::now(),
190            last_area: std::cell::Cell::new(Rect::default()),
191            last_click: None,
192            mouse_selecting: false,
193        }
194    }
195
196    // ── Event Handling ─────────────────────────────────────────────
197
198    /// Handle a terminal event.
199    ///
200    /// Returns `true` if the state changed.
201    pub fn handle_event(&mut self, event: &Event) -> bool {
202        let now_ms = u64::try_from(self.undo_clock.elapsed().as_millis()).unwrap_or(u64::MAX);
203        self.handle_event_at(event, now_ms)
204    }
205
206    /// Handle an event with a caller-supplied monotonic millisecond timestamp.
207    /// Use this instead of [`Self::handle_event`] for deterministic replay.
208    /// Switching to an earlier clock value starts a new undo group.
209    pub fn handle_event_at(&mut self, event: &Event, now_ms: u64) -> bool {
210        self.editor.tick(now_ms);
211        match event {
212            Event::Key(key)
213                if key.kind == KeyEventKind::Press || key.kind == KeyEventKind::Repeat =>
214            {
215                self.handle_key(key)
216            }
217            Event::Paste(paste) => {
218                self.insert_text(&paste.text);
219                true
220            }
221            Event::Focus(false) => {
222                self.editor.break_undo_group();
223                false
224            }
225            Event::Mouse(mouse) => self.handle_mouse(mouse, now_ms),
226            _ => false,
227        }
228    }
229
230    /// Left press places the cursor, a second press selects the word under
231    /// it (Unicode word boundaries) and a third the line. Presses count as
232    /// one multi-click within [`GestureConfig`]'s window and tolerance (300
233    /// ms, 1 cell), so timing matches the runtime's gesture recognizer.
234    /// Dragging after a single press extends the selection. Presses outside
235    /// the area last rendered are ignored, and so is a drag that started
236    /// outside it, so a host can forward every mouse event.
237    fn handle_mouse(&mut self, mouse: &MouseEvent, now_ms: u64) -> bool {
238        match mouse.kind {
239            MouseEventKind::Down(MouseButton::Left) => {
240                let Some(pos) = self.position_at(mouse.x, mouse.y) else {
241                    self.mouse_selecting = false;
242                    return false;
243                };
244                let config = GestureConfig::default();
245                let window =
246                    u64::try_from(config.multi_click_timeout.as_millis()).unwrap_or(u64::MAX);
247                let count = match self.last_click {
248                    Some(last)
249                        if now_ms >= last.at_ms
250                            && now_ms - last.at_ms <= window
251                            && last.x.abs_diff(mouse.x) <= config.click_tolerance
252                            && last.y.abs_diff(mouse.y) <= config.click_tolerance =>
253                    {
254                        last.count % 3 + 1
255                    }
256                    _ => 1,
257                };
258                self.last_click = Some(LastClick {
259                    at_ms: now_ms,
260                    x: mouse.x,
261                    y: mouse.y,
262                    count,
263                });
264                self.mouse_selecting = count == 1;
265                match count {
266                    1 => self.editor.set_cursor(pos),
267                    2 => self.select_word_at(pos),
268                    _ => self.select_line_at(pos),
269                }
270                true
271            }
272            MouseEventKind::Drag(MouseButton::Left) if self.mouse_selecting => {
273                let area = self.last_area.get();
274                if area.is_empty() {
275                    return false;
276                }
277                let x = mouse.x.clamp(area.x, area.right() - 1);
278                let y = mouse.y.clamp(area.y, area.bottom() - 1);
279                let pos = self.position_in_area(area, x, y);
280                self.editor.extend_selection_to(pos);
281                true
282            }
283            MouseEventKind::Up(MouseButton::Left) => {
284                self.mouse_selecting = false;
285                false
286            }
287            _ => false,
288        }
289    }
290
291    /// The text position under a cell of the last rendered area, or `None`
292    /// outside it (or before the first render).
293    fn position_at(&self, x: u16, y: u16) -> Option<CursorPosition> {
294        let area = self.last_area.get();
295        (!area.is_empty() && area.contains(x, y)).then(|| self.position_in_area(area, x, y))
296    }
297
298    /// Invert the render's layout: rows from the scroll anchor (wrapped
299    /// slices when soft-wrapping), columns past the gutter plus the
300    /// horizontal scroll. Below the text maps to the last line; the gutter
301    /// maps to column 0.
302    fn position_in_area(&self, area: Rect, x: u16, y: u16) -> CursorPosition {
303        let col = usize::from(x.saturating_sub(area.x.saturating_add(self.gutter_width())));
304        let row = usize::from(y.saturating_sub(area.y));
305        let rope = self.editor.rope();
306        let nav = CursorNavigator::new(rope);
307        let (top_line, top_vrow) = self.scroll_anchor.get();
308        let top_line = if top_line == usize::MAX { 0 } else { top_line };
309        let line_count = self.editor.line_count();
310
311        if !self.soft_wrap {
312            return nav.from_visual_col(top_line + row, self.scroll_left.get() + col);
313        }
314
315        let width = self.last_viewport_width.get();
316        let mut remaining = row;
317        for line_idx in top_line..line_count {
318            let line_text = rope
319                .line(line_idx)
320                .unwrap_or(std::borrow::Cow::Borrowed(""));
321            let line_text = line_text.trim_end_matches(['\n', '\r']);
322            let slices = Self::wrap_line_slices(line_text, width);
323            let skip = if line_idx == top_line { top_vrow } else { 0 };
324            let visible = slices.len().saturating_sub(skip);
325            if remaining < visible {
326                let index = skip + remaining;
327                let slice = &slices[index];
328                // Past the end of a slice that wraps, stay on that row
329                // rather than landing at the start of the next one.
330                let max = if index + 1 < slices.len() {
331                    slice.width.saturating_sub(1)
332                } else {
333                    slice.width
334                };
335                return nav.from_visual_col(line_idx, slice.start_col + col.min(max));
336            }
337            remaining -= visible;
338        }
339        nav.from_visual_col(line_count.saturating_sub(1), usize::MAX)
340    }
341
342    /// Select the Unicode word segment (UAX #29) under `pos`: a word, a run
343    /// of spaces, or one punctuation mark.
344    fn select_word_at(&mut self, pos: CursorPosition) {
345        let rope = self.editor.rope();
346        let nav = CursorNavigator::new(rope);
347        let line_text = rope
348            .line(pos.line)
349            .unwrap_or(std::borrow::Cow::Borrowed(""));
350        let line_text = line_text.trim_end_matches(['\n', '\r']);
351        let line_start = nav.to_byte_index(nav.from_line_grapheme(pos.line, 0));
352        let offset = nav.to_byte_index(pos) - line_start;
353        let segment = line_text
354            .split_word_bound_indices()
355            .find(|(start, word)| offset < start + word.len())
356            .or_else(|| line_text.split_word_bound_indices().next_back());
357        let Some((start, word)) = segment else {
358            self.editor.set_cursor(pos);
359            return;
360        };
361        let from = nav.from_byte_index(line_start + start);
362        let to = nav.from_byte_index(line_start + start + word.len());
363        self.editor.set_cursor(from);
364        self.editor.extend_selection_to(to);
365    }
366
367    /// Select the whole logical line under `pos`, without its newline.
368    fn select_line_at(&mut self, pos: CursorPosition) {
369        let nav = CursorNavigator::new(self.editor.rope());
370        let from = nav.from_line_grapheme(pos.line, 0);
371        let to = nav.from_line_grapheme(pos.line, usize::MAX);
372        self.editor.set_cursor(from);
373        self.editor.extend_selection_to(to);
374    }
375
376    fn handle_key(&mut self, key: &KeyEvent) -> bool {
377        let ctrl = key.modifiers.contains(Modifiers::CTRL);
378        let shift = key.modifiers.contains(Modifiers::SHIFT);
379        let _alt = key.modifiers.contains(Modifiers::ALT);
380        // Command/Windows-key chords belong to the host, not the buffer. Only
381        // CTRL used to be excluded, so on macOS every Cmd+<letter> shortcut
382        // typed its letter: Cmd+V inserted a literal "v" next to the paste.
383        let cmd = key.modifiers.contains(Modifiers::SUPER);
384
385        match key.code {
386            KeyCode::Char(c) if !ctrl && !cmd => {
387                self.insert_char(c);
388                true
389            }
390            KeyCode::Enter => {
391                self.insert_newline();
392                true
393            }
394            KeyCode::Backspace => {
395                if ctrl {
396                    self.delete_word_backward();
397                } else {
398                    self.delete_backward();
399                }
400                true
401            }
402            KeyCode::Delete => {
403                if ctrl {
404                    self.delete_word_forward();
405                } else {
406                    self.delete_forward();
407                }
408                true
409            }
410            KeyCode::Left => {
411                if ctrl && shift {
412                    self.select_word_left();
413                } else if ctrl {
414                    self.move_word_left();
415                } else if shift {
416                    self.select_left();
417                } else {
418                    self.move_left();
419                }
420                true
421            }
422            KeyCode::Right => {
423                if ctrl && shift {
424                    self.select_word_right();
425                } else if ctrl {
426                    self.move_word_right();
427                } else if shift {
428                    self.select_right();
429                } else {
430                    self.move_right();
431                }
432                true
433            }
434            KeyCode::Up => {
435                if ctrl && shift {
436                    self.select_paragraph_up();
437                } else if ctrl {
438                    self.move_paragraph_up();
439                } else if shift {
440                    self.select_up();
441                } else {
442                    self.move_up();
443                }
444                true
445            }
446            KeyCode::Down => {
447                if ctrl && shift {
448                    self.select_paragraph_down();
449                } else if ctrl {
450                    self.move_paragraph_down();
451                } else if shift {
452                    self.select_down();
453                } else {
454                    self.move_down();
455                }
456                true
457            }
458            KeyCode::Home => {
459                self.move_to_line_start();
460                true
461            }
462            KeyCode::End => {
463                self.move_to_line_end();
464                true
465            }
466            KeyCode::PageUp => {
467                let page = self.last_viewport_height.get().max(1);
468                if self.soft_wrap {
469                    self.move_cursor_visual_up(page, shift);
470                } else {
471                    for _ in 0..page {
472                        if shift {
473                            self.editor.select_up();
474                        } else {
475                            self.editor.move_up();
476                        }
477                    }
478                }
479                self.ensure_cursor_visible();
480                true
481            }
482            KeyCode::PageDown => {
483                let page = self.last_viewport_height.get().max(1);
484                if self.soft_wrap {
485                    self.move_cursor_visual_down(page, shift);
486                } else {
487                    for _ in 0..page {
488                        if shift {
489                            self.editor.select_down();
490                        } else {
491                            self.editor.move_down();
492                        }
493                    }
494                }
495                self.ensure_cursor_visible();
496                true
497            }
498            KeyCode::Char('a') if ctrl => {
499                self.select_all();
500                true
501            }
502            // Ctrl+K: Delete to end of line (common emacs/shell binding)
503            KeyCode::Char('k') if ctrl => {
504                self.delete_to_end_of_line();
505                true
506            }
507            // Ctrl+Z: Undo
508            KeyCode::Char('z') if ctrl => {
509                self.undo();
510                true
511            }
512            // Ctrl+Y: Redo
513            KeyCode::Char('y') if ctrl => {
514                self.redo();
515                true
516            }
517            _ => false,
518        }
519    }
520
521    // ── Builder methods ────────────────────────────────────────────
522
523    /// Set initial text content (builder).
524    #[must_use]
525    pub fn with_text(mut self, text: &str) -> Self {
526        self.editor = Editor::with_text(text);
527        self.editor.move_to_document_start();
528        self
529    }
530
531    /// Set placeholder text (builder).
532    #[must_use]
533    pub fn with_placeholder(mut self, text: impl Into<String>) -> Self {
534        self.placeholder = text.into();
535        self
536    }
537
538    /// Set focused state (builder).
539    #[must_use]
540    pub fn with_focus(mut self, focused: bool) -> Self {
541        self.set_focused(focused);
542        self
543    }
544
545    /// Enable line numbers (builder).
546    #[must_use]
547    pub fn with_line_numbers(mut self, show: bool) -> Self {
548        self.show_line_numbers = show;
549        self
550    }
551
552    /// Install a per-line syntax style provider (builder). See
553    /// [`LineHighlighter`].
554    #[must_use]
555    pub fn with_highlighter(mut self, highlighter: LineHighlighter) -> Self {
556        self.highlighter = Some(highlighter);
557        self
558    }
559
560    /// Set or clear the per-line syntax style provider.
561    pub fn set_highlighter(&mut self, highlighter: Option<LineHighlighter>) {
562        self.highlighter = highlighter;
563    }
564
565    /// Whether a syntax highlighter is installed.
566    #[must_use]
567    pub fn has_highlighter(&self) -> bool {
568        self.highlighter.is_some()
569    }
570
571    /// The highlight spans for one line, or empty when there is no highlighter
572    /// or styling is disabled. Ranges that don't sit on grapheme boundaries of
573    /// `line_text` are dropped so partial-grapheme styling can't occur.
574    fn line_spans(
575        &self,
576        line_idx: usize,
577        line_text: &str,
578        styling: bool,
579    ) -> Vec<(Range<usize>, Style)> {
580        if !styling {
581            return Vec::new();
582        }
583        let Some(highlighter) = self.highlighter.as_ref() else {
584            return Vec::new();
585        };
586        highlighter(line_idx, line_text)
587            .into_iter()
588            .filter(|(range, _)| {
589                range.start < range.end
590                    && range.end <= line_text.len()
591                    && line_text.is_char_boundary(range.start)
592                    && line_text.is_char_boundary(range.end)
593            })
594            .collect()
595    }
596
597    /// Set base style (builder).
598    #[must_use]
599    pub fn with_style(mut self, style: Style) -> Self {
600        self.style = style;
601        self
602    }
603
604    /// Set cursor line highlight style (builder).
605    #[must_use]
606    pub fn with_cursor_line_style(mut self, style: Style) -> Self {
607        self.cursor_line_style = Some(style);
608        self
609    }
610
611    /// Set selection style (builder).
612    #[must_use]
613    pub fn with_selection_style(mut self, style: Style) -> Self {
614        self.selection_style = style;
615        self
616    }
617
618    /// Enable soft wrapping (builder).
619    #[must_use]
620    pub fn with_soft_wrap(mut self, wrap: bool) -> Self {
621        self.soft_wrap = wrap;
622        self
623    }
624
625    /// Set maximum height in lines (builder). 0 = fill available area.
626    #[must_use]
627    pub fn with_max_height(mut self, max: usize) -> Self {
628        self.max_height = max;
629        self
630    }
631
632    // ── State access ───────────────────────────────────────────────
633
634    /// Get the full text content.
635    #[must_use]
636    pub fn text(&self) -> String {
637        self.editor.text()
638    }
639
640    /// Set the full text content (resets cursor and undo history).
641    pub fn set_text(&mut self, text: &str) {
642        self.editor.set_text(text);
643        self.scroll_anchor.set((0, 0));
644        self.scroll_left.set(0);
645    }
646
647    /// Number of lines.
648    #[must_use]
649    pub fn line_count(&self) -> usize {
650        self.editor.line_count()
651    }
652
653    /// Current cursor position.
654    #[inline]
655    #[must_use]
656    pub fn cursor(&self) -> CursorPosition {
657        self.editor.cursor()
658    }
659
660    /// Set cursor position (clamped to bounds). Clears selection.
661    pub fn set_cursor_position(&mut self, pos: CursorPosition) {
662        self.editor.set_cursor(pos);
663        self.ensure_cursor_visible();
664    }
665
666    /// Whether the textarea is empty.
667    #[inline]
668    #[must_use]
669    pub fn is_empty(&self) -> bool {
670        self.editor.is_empty()
671    }
672
673    /// Current selection, if any.
674    #[must_use = "use the returned selection (if any)"]
675    pub fn selection(&self) -> Option<Selection> {
676        self.editor.selection()
677    }
678
679    /// Get selected text.
680    #[must_use = "use the returned selected text (if any)"]
681    pub fn selected_text(&self) -> Option<String> {
682        self.editor.selected_text()
683    }
684
685    /// Whether the widget has focus.
686    #[must_use]
687    pub fn is_focused(&self) -> bool {
688        self.focused
689    }
690
691    /// Set focus state.
692    pub fn set_focused(&mut self, focused: bool) {
693        if !focused {
694            self.editor.break_undo_group();
695        }
696        self.focused = focused;
697    }
698
699    /// Set the idle interval for typing/deletion undo groups (default 500 ms).
700    /// Zero disables coalescing.
701    pub fn set_undo_coalesce_idle(&mut self, idle: Duration) {
702        self.editor.set_coalesce_idle(idle);
703    }
704
705    /// Number of available undo steps.
706    #[must_use]
707    pub fn undo_group_count(&self) -> usize {
708        self.editor.undo_group_count()
709    }
710
711    /// Number of available redo steps.
712    #[must_use]
713    pub fn redo_group_count(&self) -> usize {
714        self.editor.redo_group_count()
715    }
716
717    /// Number of primitive edits retained in the undo history.
718    #[must_use]
719    pub fn undo_op_count(&self) -> usize {
720        self.editor.undo_op_count()
721    }
722
723    /// Access the underlying editor.
724    #[must_use]
725    pub fn editor(&self) -> &Editor {
726        &self.editor
727    }
728
729    /// Mutable access to the underlying editor.
730    pub fn editor_mut(&mut self) -> &mut Editor {
731        &mut self.editor
732    }
733
734    // ── Editing operations (delegated to Editor) ───────────────────
735
736    /// Insert text at cursor.
737    pub fn insert_text(&mut self, text: &str) {
738        self.editor.insert_text(text);
739        self.ensure_cursor_visible();
740    }
741
742    /// Insert a single character.
743    pub fn insert_char(&mut self, ch: char) {
744        self.editor.insert_char(ch);
745        self.ensure_cursor_visible();
746    }
747
748    /// Insert a newline.
749    pub fn insert_newline(&mut self) {
750        self.editor.insert_newline();
751        self.ensure_cursor_visible();
752    }
753
754    /// Delete backward (backspace).
755    pub fn delete_backward(&mut self) {
756        self.editor.delete_backward();
757        self.ensure_cursor_visible();
758    }
759
760    /// Delete forward (delete key).
761    pub fn delete_forward(&mut self) {
762        self.editor.delete_forward();
763        self.ensure_cursor_visible();
764    }
765
766    /// Delete word backward (Ctrl+Backspace).
767    pub fn delete_word_backward(&mut self) {
768        self.editor.delete_word_backward();
769        self.ensure_cursor_visible();
770    }
771
772    /// Delete word forward (Ctrl+Delete).
773    pub fn delete_word_forward(&mut self) {
774        self.editor.delete_word_forward();
775        self.ensure_cursor_visible();
776    }
777
778    /// Delete to end of line (Ctrl+K).
779    pub fn delete_to_end_of_line(&mut self) {
780        self.editor.delete_to_end_of_line();
781        self.ensure_cursor_visible();
782    }
783
784    /// Undo last edit.
785    pub fn undo(&mut self) {
786        self.editor.undo();
787        self.ensure_cursor_visible();
788    }
789
790    /// Redo last undo.
791    pub fn redo(&mut self) {
792        self.editor.redo();
793        self.ensure_cursor_visible();
794    }
795
796    // ── Navigation ─────────────────────────────────────────────────
797
798    /// Move cursor left.
799    pub fn move_left(&mut self) {
800        self.editor.move_left();
801        self.ensure_cursor_visible();
802    }
803
804    /// Move cursor right.
805    pub fn move_right(&mut self) {
806        self.editor.move_right();
807        self.ensure_cursor_visible();
808    }
809
810    /// Move cursor up.
811    pub fn move_up(&mut self) {
812        if self.soft_wrap {
813            self.move_cursor_visual_up(1, false);
814        } else {
815            self.editor.move_up();
816        }
817        self.ensure_cursor_visible();
818    }
819
820    /// Move cursor down.
821    pub fn move_down(&mut self) {
822        if self.soft_wrap {
823            self.move_cursor_visual_down(1, false);
824        } else {
825            self.editor.move_down();
826        }
827        self.ensure_cursor_visible();
828    }
829
830    /// Move cursor left by word.
831    pub fn move_word_left(&mut self) {
832        self.editor.move_word_left();
833        self.ensure_cursor_visible();
834    }
835
836    /// Move cursor right by word.
837    pub fn move_word_right(&mut self) {
838        self.editor.move_word_right();
839        self.ensure_cursor_visible();
840    }
841
842    /// Extend selection left by word.
843    pub fn select_word_left(&mut self) {
844        self.editor.select_word_left();
845        self.ensure_cursor_visible();
846    }
847
848    /// Extend selection right by word.
849    pub fn select_word_right(&mut self) {
850        self.editor.select_word_right();
851        self.ensure_cursor_visible();
852    }
853
854    /// Move to the preceding blank-line paragraph boundary (Ctrl+Up).
855    /// See [`CursorNavigator::move_paragraph_up`] for whitespace rules and examples.
856    pub fn move_paragraph_up(&mut self) {
857        self.editor.move_paragraph_up();
858        self.ensure_cursor_visible();
859    }
860
861    /// Move to the following blank-line paragraph boundary (Ctrl+Down).
862    /// See [`CursorNavigator::move_paragraph_down`] for whitespace rules and examples.
863    pub fn move_paragraph_down(&mut self) {
864        self.editor.move_paragraph_down();
865        self.ensure_cursor_visible();
866    }
867
868    /// Extend selection to the preceding paragraph boundary (Ctrl+Shift+Up).
869    /// See [`CursorNavigator::move_paragraph_up`] for whitespace rules and examples.
870    pub fn select_paragraph_up(&mut self) {
871        self.editor.select_paragraph_up();
872        self.ensure_cursor_visible();
873    }
874
875    /// Extend selection to the following paragraph boundary (Ctrl+Shift+Down).
876    /// See [`CursorNavigator::move_paragraph_down`] for whitespace rules and examples.
877    pub fn select_paragraph_down(&mut self) {
878        self.editor.select_paragraph_down();
879        self.ensure_cursor_visible();
880    }
881
882    /// Move to start of line.
883    pub fn move_to_line_start(&mut self) {
884        self.editor.move_to_line_start();
885        self.ensure_cursor_visible();
886    }
887
888    /// Move to end of line.
889    pub fn move_to_line_end(&mut self) {
890        self.editor.move_to_line_end();
891        self.ensure_cursor_visible();
892    }
893
894    /// Move to start of document.
895    pub fn move_to_document_start(&mut self) {
896        self.editor.move_to_document_start();
897        self.ensure_cursor_visible();
898    }
899
900    /// Move cursor to end of document.
901    pub fn move_to_document_end(&mut self) {
902        self.editor.move_to_document_end();
903        self.ensure_cursor_visible();
904    }
905
906    fn move_cursor_visual_down(&mut self, count: usize, extend_selection: bool) {
907        let width = self.last_viewport_width.get();
908        if width == 0 {
909            for _ in 0..count {
910                if extend_selection {
911                    self.editor.select_down();
912                } else {
913                    self.editor.move_down();
914                }
915            }
916            return;
917        }
918
919        let rope = self.editor.rope();
920        let mut cursor = self.editor.cursor();
921        let mut remaining = count;
922
923        let line_text = rope
924            .line(cursor.line)
925            .unwrap_or(std::borrow::Cow::Borrowed(""));
926        let line_text = line_text.trim_end_matches(['\n', '\r']);
927        let (mut current_v_row, _) =
928            Self::cursor_wrap_position(line_text, width, cursor.visual_col);
929
930        // Calculate target screen X (relative to slice start) to preserve column
931        let initial_slices = Self::wrap_line_slices(line_text, width);
932        let initial_slice_start = initial_slices
933            .get(current_v_row)
934            .map(|s| s.start_col)
935            .unwrap_or(0);
936        let target_screen_x = cursor.visual_col.saturating_sub(initial_slice_start);
937
938        while remaining > 0 {
939            let line_text = rope
940                .line(cursor.line)
941                .unwrap_or(std::borrow::Cow::Borrowed(""));
942            let line_text = line_text.trim_end_matches(['\n', '\r']);
943            let wrap_count = Self::measure_wrap_count(line_text, width);
944
945            let available_in_line = wrap_count.saturating_sub(1).saturating_sub(current_v_row);
946
947            if remaining <= available_in_line {
948                current_v_row += remaining;
949                remaining = 0;
950            } else {
951                remaining -= available_in_line + 1;
952                if cursor.line + 1 < self.editor.line_count() {
953                    cursor.line += 1;
954                    current_v_row = 0;
955                } else {
956                    current_v_row = wrap_count.saturating_sub(1);
957                    remaining = 0;
958                }
959            }
960        }
961
962        let line_text = rope
963            .line(cursor.line)
964            .unwrap_or(std::borrow::Cow::Borrowed(""));
965        let line_text = line_text.trim_end_matches(['\n', '\r']);
966        let slices = Self::wrap_line_slices(line_text, width);
967
968        if let Some(slice) = slices.get(current_v_row) {
969            let target_in_slice = target_screen_x.min(slice.width);
970
971            let mut g_idx = 0;
972            let mut v_w = 0;
973            for g in slice.text.graphemes(true) {
974                let w = display_width(g);
975                if v_w + w > target_in_slice {
976                    break;
977                }
978                v_w += w;
979                g_idx += 1;
980            }
981
982            let nav = CursorNavigator::new(rope);
983            let line_start_byte = nav.to_byte_index(nav.from_line_grapheme(cursor.line, 0));
984            let slice_byte_offset: usize = slice
985                .text
986                .graphemes(true)
987                .take(g_idx)
988                .map(|g| g.len())
989                .sum();
990            let final_byte = line_start_byte + slice.start_byte + slice_byte_offset;
991            cursor = nav.from_byte_index(final_byte);
992        }
993
994        if extend_selection {
995            self.editor.extend_selection_to(cursor);
996        } else {
997            self.editor.set_cursor(cursor);
998        }
999    }
1000
1001    fn move_cursor_visual_up(&mut self, count: usize, extend_selection: bool) {
1002        let width = self.last_viewport_width.get();
1003        if width == 0 {
1004            for _ in 0..count {
1005                if extend_selection {
1006                    self.editor.select_up();
1007                } else {
1008                    self.editor.move_up();
1009                }
1010            }
1011            return;
1012        }
1013
1014        let rope = self.editor.rope();
1015        let mut cursor = self.editor.cursor();
1016        let mut remaining = count;
1017
1018        let line_text = rope
1019            .line(cursor.line)
1020            .unwrap_or(std::borrow::Cow::Borrowed(""));
1021        let line_text = line_text.trim_end_matches(['\n', '\r']);
1022        let (mut current_v_row, _) =
1023            Self::cursor_wrap_position(line_text, width, cursor.visual_col);
1024
1025        // Calculate target screen X (relative to slice start) to preserve column
1026        let initial_slices = Self::wrap_line_slices(line_text, width);
1027        let initial_slice_start = initial_slices
1028            .get(current_v_row)
1029            .map(|s| s.start_col)
1030            .unwrap_or(0);
1031        let target_screen_x = cursor.visual_col.saturating_sub(initial_slice_start);
1032
1033        while remaining > 0 {
1034            if remaining <= current_v_row {
1035                current_v_row -= remaining;
1036                remaining = 0;
1037            } else {
1038                remaining -= current_v_row + 1;
1039                if cursor.line > 0 {
1040                    cursor.line -= 1;
1041                    let line_text = rope
1042                        .line(cursor.line)
1043                        .unwrap_or(std::borrow::Cow::Borrowed(""));
1044                    let line_text = line_text.trim_end_matches(['\n', '\r']);
1045                    let wrap_count = Self::measure_wrap_count(line_text, width);
1046                    current_v_row = wrap_count.saturating_sub(1);
1047                } else {
1048                    current_v_row = 0;
1049                    remaining = 0;
1050                }
1051            }
1052        }
1053
1054        let line_text = rope
1055            .line(cursor.line)
1056            .unwrap_or(std::borrow::Cow::Borrowed(""));
1057        let line_text = line_text.trim_end_matches(['\n', '\r']);
1058        let slices = Self::wrap_line_slices(line_text, width);
1059
1060        if let Some(slice) = slices.get(current_v_row) {
1061            let target_in_slice = target_screen_x.min(slice.width);
1062
1063            let mut g_idx = 0;
1064            let mut v_w = 0;
1065            for g in slice.text.graphemes(true) {
1066                let w = display_width(g);
1067                if v_w + w > target_in_slice {
1068                    break;
1069                }
1070                v_w += w;
1071                g_idx += 1;
1072            }
1073
1074            let nav = CursorNavigator::new(rope);
1075            let line_start_byte = nav.to_byte_index(nav.from_line_grapheme(cursor.line, 0));
1076            let slice_byte_offset: usize = slice
1077                .text
1078                .graphemes(true)
1079                .take(g_idx)
1080                .map(|g| g.len())
1081                .sum();
1082            let final_byte = line_start_byte + slice.start_byte + slice_byte_offset;
1083            cursor = nav.from_byte_index(final_byte);
1084        }
1085
1086        if extend_selection {
1087            self.editor.extend_selection_to(cursor);
1088        } else {
1089            self.editor.set_cursor(cursor);
1090        }
1091    }
1092
1093    // ── Selection ──────────────────────────────────────────────────
1094
1095    /// Extend selection left.
1096    pub fn select_left(&mut self) {
1097        self.editor.select_left();
1098        self.ensure_cursor_visible();
1099    }
1100
1101    /// Extend selection right.
1102    pub fn select_right(&mut self) {
1103        self.editor.select_right();
1104        self.ensure_cursor_visible();
1105    }
1106
1107    /// Extend selection up.
1108    pub fn select_up(&mut self) {
1109        if self.soft_wrap {
1110            self.move_cursor_visual_up(1, true);
1111        } else {
1112            self.editor.select_up();
1113        }
1114        self.ensure_cursor_visible();
1115    }
1116
1117    /// Extend selection down.
1118    pub fn select_down(&mut self) {
1119        if self.soft_wrap {
1120            self.move_cursor_visual_down(1, true);
1121        } else {
1122            self.editor.select_down();
1123        }
1124        self.ensure_cursor_visible();
1125    }
1126
1127    /// Select all.
1128    pub fn select_all(&mut self) {
1129        self.editor.select_all();
1130    }
1131
1132    /// Clear selection.
1133    pub fn clear_selection(&mut self) {
1134        self.editor.clear_selection();
1135    }
1136
1137    // ── Viewport management ────────────────────────────────────────
1138
1139    /// Page up (move viewport and cursor up by viewport height).
1140    pub fn page_up(&mut self, state: &TextAreaState) {
1141        let page = state.last_viewport_height.max(1) as usize;
1142        let text_area_width = state
1143            .last_viewport_width
1144            .saturating_sub(self.gutter_width());
1145        self.last_viewport_height.set(page);
1146        self.last_viewport_width.set(text_area_width as usize);
1147        if self.soft_wrap {
1148            if text_area_width > 0 {
1149                self.move_cursor_visual_up(page, false);
1150            } else {
1151                for _ in 0..page {
1152                    self.editor.move_up();
1153                }
1154            }
1155        } else {
1156            for _ in 0..page {
1157                self.editor.move_up();
1158            }
1159        }
1160        self.ensure_cursor_visible();
1161    }
1162
1163    /// Page down (move viewport and cursor down by viewport height).
1164    pub fn page_down(&mut self, state: &TextAreaState) {
1165        let page = state.last_viewport_height.max(1) as usize;
1166        let text_area_width = state
1167            .last_viewport_width
1168            .saturating_sub(self.gutter_width());
1169        self.last_viewport_height.set(page);
1170        self.last_viewport_width.set(text_area_width as usize);
1171        if self.soft_wrap {
1172            if text_area_width > 0 {
1173                self.move_cursor_visual_down(page, false);
1174            } else {
1175                for _ in 0..page {
1176                    self.editor.move_down();
1177                }
1178            }
1179        } else {
1180            for _ in 0..page {
1181                self.editor.move_down();
1182            }
1183        }
1184        self.ensure_cursor_visible();
1185    }
1186
1187    /// Width of the line number gutter.
1188    fn gutter_width(&self) -> u16 {
1189        if !self.show_line_numbers {
1190            return 0;
1191        }
1192        let digits = {
1193            let mut count = self.line_count().max(1);
1194            let mut d: u16 = 0;
1195            while count > 0 {
1196                d += 1;
1197                count /= 10;
1198            }
1199            d
1200        };
1201        digits + 2 // digit width + space + separator
1202    }
1203
1204    /// Count how many wrapped lines this text will occupy.
1205    ///
1206    /// This is a zero-allocation version of `wrap_line_slices` for layout calculations.
1207    fn measure_wrap_count(line_text: &str, max_width: usize) -> usize {
1208        if line_text.is_empty() {
1209            return 1;
1210        }
1211
1212        let mut count = 0;
1213        let mut current_width = 0;
1214        let mut has_content = false;
1215
1216        Self::run_wrapping_logic(line_text, max_width, |_, width, flush| {
1217            if flush {
1218                if width > 0 {
1219                    count += 1;
1220                }
1221                current_width = 0;
1222                has_content = false;
1223            } else {
1224                current_width = width;
1225                has_content = true;
1226            }
1227        });
1228
1229        // If there's pending content or if we flushed but started a new empty line (which shouldn't happen with this logic usually,
1230        // but let's be safe), count the last line.
1231        // Actually run_wrapping_logic only flushes when a line is full.
1232        // We need to count the current line if it has content or if it's the only line.
1233        if has_content || count == 0 {
1234            count += 1;
1235        }
1236
1237        count
1238    }
1239
1240    /// Core wrapping logic that emits events for layout or slicing.
1241    ///
1242    /// The callback receives `(start_index, width, flush)`.
1243    /// - `flush == true`: The current line is full/done. `width` is the width of the flushed line.
1244    /// - `flush == false`: Update current line width.
1245    fn run_wrapping_logic<F>(line_text: &str, max_width: usize, mut callback: F)
1246    where
1247        F: FnMut(usize, usize, bool),
1248    {
1249        let mut current_width = 0;
1250        let mut byte_cursor = 0;
1251
1252        for segment in line_text.split_word_bounds() {
1253            let seg_len = segment.len();
1254            let seg_width: usize = segment.graphemes(true).map(display_width).sum();
1255
1256            if max_width > 0 && current_width + seg_width > max_width {
1257                // Flush current
1258                callback(byte_cursor, current_width, true);
1259                current_width = 0;
1260            }
1261
1262            if max_width > 0 && seg_width > max_width {
1263                for grapheme in segment.graphemes(true) {
1264                    let g_width = display_width(grapheme);
1265                    let g_len = grapheme.len();
1266
1267                    if max_width > 0 && current_width + g_width > max_width && current_width > 0 {
1268                        callback(byte_cursor, current_width, true);
1269                        current_width = 0;
1270                    }
1271
1272                    current_width += g_width;
1273                    byte_cursor += g_len;
1274                    callback(byte_cursor, current_width, false);
1275                }
1276                continue;
1277            }
1278
1279            current_width += seg_width;
1280            byte_cursor += seg_len;
1281            callback(byte_cursor, current_width, false);
1282        }
1283    }
1284
1285    fn wrap_line_slices<'a>(line_text: &'a str, max_width: usize) -> Vec<WrappedSlice<'a>> {
1286        if line_text.is_empty() {
1287            return vec![WrappedSlice {
1288                text: "",
1289                start_byte: 0,
1290                start_col: 0,
1291                width: 0,
1292            }];
1293        }
1294
1295        let mut slices = Vec::new();
1296        let mut current_width = 0;
1297        let mut slice_start_byte = 0;
1298        let mut slice_start_col = 0;
1299        let mut byte_cursor = 0;
1300        let mut col_cursor = 0;
1301
1302        let push_current = |slices: &mut Vec<WrappedSlice<'a>>,
1303                            width: &mut usize,
1304                            start_byte: &mut usize,
1305                            start_col: &mut usize,
1306                            byte_cursor: usize,
1307                            col_cursor: usize| {
1308            if byte_cursor == *start_byte && *width == 0 {
1309                return;
1310            }
1311            slices.push(WrappedSlice {
1312                text: &line_text[*start_byte..byte_cursor],
1313                start_byte: *start_byte,
1314                start_col: *start_col,
1315                width: *width,
1316            });
1317            *start_byte = byte_cursor;
1318            *start_col = col_cursor;
1319            *width = 0;
1320        };
1321
1322        for segment in line_text.split_word_bounds() {
1323            let seg_len = segment.len();
1324            let seg_width: usize = segment.graphemes(true).map(display_width).sum();
1325
1326            if max_width > 0 && current_width + seg_width > max_width {
1327                push_current(
1328                    &mut slices,
1329                    &mut current_width,
1330                    &mut slice_start_byte,
1331                    &mut slice_start_col,
1332                    byte_cursor,
1333                    col_cursor,
1334                );
1335            }
1336
1337            if max_width > 0 && seg_width > max_width {
1338                for grapheme in segment.graphemes(true) {
1339                    let g_width = display_width(grapheme);
1340                    let g_len = grapheme.len();
1341
1342                    if max_width > 0 && current_width + g_width > max_width && current_width > 0 {
1343                        push_current(
1344                            &mut slices,
1345                            &mut current_width,
1346                            &mut slice_start_byte,
1347                            &mut slice_start_col,
1348                            byte_cursor,
1349                            col_cursor,
1350                        );
1351                    }
1352
1353                    current_width += g_width;
1354                    byte_cursor += g_len;
1355                    col_cursor += g_width;
1356                }
1357                continue;
1358            }
1359
1360            current_width += seg_width;
1361            byte_cursor += seg_len;
1362            col_cursor += seg_width;
1363        }
1364
1365        if byte_cursor > slice_start_byte || current_width > 0 || slices.is_empty() {
1366            slices.push(WrappedSlice {
1367                text: &line_text[slice_start_byte..byte_cursor],
1368                start_byte: slice_start_byte,
1369                start_col: slice_start_col,
1370                width: current_width,
1371            });
1372        }
1373
1374        slices
1375    }
1376
1377    fn cursor_wrap_position(
1378        line_text: &str,
1379        max_width: usize,
1380        cursor_col: usize,
1381    ) -> (usize, usize) {
1382        let slices = Self::wrap_line_slices(line_text, max_width);
1383        if slices.is_empty() {
1384            return (0, 0);
1385        }
1386
1387        for (idx, slice) in slices.iter().enumerate() {
1388            let end_col = slice.start_col.saturating_add(slice.width);
1389            // If cursor is at the wrap boundary (equal to end_col), we prefer the start
1390            // of the *next* slice (by skipping this one) unless this is the last slice.
1391            let is_last = idx == slices.len().saturating_sub(1);
1392            if cursor_col < end_col || (cursor_col == end_col && is_last) {
1393                let col_in_slice = cursor_col.saturating_sub(slice.start_col);
1394                return (idx, col_in_slice.min(slice.width));
1395            }
1396        }
1397
1398        (0, 0)
1399    }
1400
1401    /// Get the visual width of the character immediately before the cursor.
1402    fn get_prev_char_width(&self) -> usize {
1403        let cursor = self.editor.cursor();
1404        if cursor.grapheme == 0 {
1405            return 0;
1406        }
1407        let rope = self.editor.rope();
1408        let line = rope
1409            .line(cursor.line)
1410            .unwrap_or(std::borrow::Cow::Borrowed(""));
1411
1412        line.graphemes(true)
1413            .nth(cursor.grapheme - 1)
1414            .map(display_width)
1415            .unwrap_or(0)
1416    }
1417
1418    /// Ensure the cursor line and column are visible in the viewport.
1419    fn ensure_cursor_visible(&self) {
1420        let cursor = self.editor.cursor();
1421
1422        let last_height = self.last_viewport_height.get();
1423        let vp_height = if last_height == 0 { 20 } else { last_height };
1424
1425        let last_width = self.last_viewport_width.get();
1426        let vp_width = if last_width == 0 { 80 } else { last_width };
1427
1428        if self.scroll_anchor.get().0 == usize::MAX {
1429            self.scroll_anchor.set((0, 0));
1430        }
1431
1432        self.ensure_cursor_visible_internal(vp_height, vp_width, cursor);
1433    }
1434
1435    fn ensure_cursor_visible_internal(
1436        &self,
1437        vp_height: usize,
1438        vp_width: usize,
1439        cursor: CursorPosition,
1440    ) {
1441        let (anchor_line, anchor_vrow) = self.scroll_anchor.get();
1442
1443        if !self.soft_wrap {
1444            // Vertical scroll (logical lines)
1445            if cursor.line < anchor_line {
1446                self.scroll_anchor.set((cursor.line, 0));
1447            } else if vp_height > 0 && cursor.line >= anchor_line + vp_height {
1448                self.scroll_anchor
1449                    .set((cursor.line.saturating_sub(vp_height - 1), 0));
1450            }
1451
1452            // Horizontal scroll
1453            let current_left = self.scroll_left.get();
1454            let visual_col = cursor.visual_col;
1455
1456            if visual_col < current_left {
1457                self.scroll_left.set(visual_col);
1458            } else if vp_width > 0 && visual_col >= current_left + vp_width {
1459                let candidate_scroll = visual_col.saturating_sub(vp_width - 1);
1460                let prev_width = self.get_prev_char_width();
1461                let max_scroll_for_prev = visual_col.saturating_sub(prev_width);
1462
1463                let new_scroll = if vp_width > prev_width {
1464                    candidate_scroll.min(max_scroll_for_prev)
1465                } else {
1466                    candidate_scroll
1467                };
1468
1469                self.scroll_left.set(new_scroll);
1470            }
1471            return;
1472        }
1473
1474        // Soft wrap logic
1475        let rope = self.editor.rope();
1476
1477        // 1. Is cursor before anchor?
1478        if cursor.line < anchor_line {
1479            let line_text = rope
1480                .line(cursor.line)
1481                .unwrap_or(std::borrow::Cow::Borrowed(""));
1482            let line_text = line_text.trim_end_matches(['\n', '\r']);
1483            let (v_row, _) = Self::cursor_wrap_position(line_text, vp_width, cursor.visual_col);
1484            self.scroll_anchor.set((cursor.line, v_row));
1485            return;
1486        }
1487
1488        if cursor.line == anchor_line {
1489            let line_text = rope
1490                .line(cursor.line)
1491                .unwrap_or(std::borrow::Cow::Borrowed(""));
1492            let line_text = line_text.trim_end_matches(['\n', '\r']);
1493            let (v_row, _) = Self::cursor_wrap_position(line_text, vp_width, cursor.visual_col);
1494            if v_row < anchor_vrow {
1495                self.scroll_anchor.set((cursor.line, v_row));
1496                return;
1497            }
1498        }
1499
1500        // 2. Is cursor after viewport? Trace forward from anchor.
1501        let mut visual_rows_capacity = vp_height;
1502        let mut current_line = anchor_line;
1503        let mut current_v_start = anchor_vrow;
1504
1505        loop {
1506            if current_line > cursor.line {
1507                // Reached past cursor line without exhausting capacity -> Visible.
1508                return;
1509            }
1510
1511            let line_text = rope
1512                .line(current_line)
1513                .unwrap_or(std::borrow::Cow::Borrowed(""));
1514            let line_text = line_text.trim_end_matches(['\n', '\r']);
1515            let wrap_count = Self::measure_wrap_count(line_text, vp_width);
1516
1517            if current_line == cursor.line {
1518                let (cursor_v_row, _) =
1519                    Self::cursor_wrap_position(line_text, vp_width, cursor.visual_col);
1520                if cursor_v_row >= current_v_start {
1521                    let displayed_row_index = cursor_v_row - current_v_start;
1522                    if displayed_row_index < visual_rows_capacity {
1523                        // Visible.
1524                        return;
1525                    } else {
1526                        // Not visible (below).
1527                        break;
1528                    }
1529                } else {
1530                    // Cursor is before the anchor start? Handled by step 1.
1531                    return;
1532                }
1533            }
1534
1535            let rows_remaining_in_line = wrap_count.saturating_sub(current_v_start);
1536            if rows_remaining_in_line >= visual_rows_capacity {
1537                break;
1538            }
1539
1540            visual_rows_capacity -= rows_remaining_in_line;
1541            current_line += 1;
1542            current_v_start = 0;
1543
1544            if current_line >= self.editor.line_count() {
1545                break;
1546            }
1547        }
1548
1549        // 3. Scroll Down (Backwards Scan)
1550        let mut needed = vp_height;
1551        let mut scan_line = cursor.line;
1552
1553        // For the cursor line itself
1554        let line_text = rope
1555            .line(scan_line)
1556            .unwrap_or(std::borrow::Cow::Borrowed(""));
1557        let line_text = line_text.trim_end_matches(['\n', '\r']);
1558        let (cursor_v, _) = Self::cursor_wrap_position(line_text, vp_width, cursor.visual_col);
1559
1560        let rows_above = cursor_v + 1;
1561        if rows_above >= needed {
1562            let new_v_start = cursor_v + 1 - needed;
1563            self.scroll_anchor.set((scan_line, new_v_start));
1564            return;
1565        }
1566
1567        needed -= rows_above;
1568
1569        // Scan previous lines
1570        while scan_line > 0 {
1571            scan_line -= 1;
1572            let line_text = rope
1573                .line(scan_line)
1574                .unwrap_or(std::borrow::Cow::Borrowed(""));
1575            let line_text = line_text.trim_end_matches(['\n', '\r']);
1576            let wrap_count = Self::measure_wrap_count(line_text, vp_width);
1577
1578            if wrap_count >= needed {
1579                let new_v_start = wrap_count - needed;
1580                self.scroll_anchor.set((scan_line, new_v_start));
1581                return;
1582            }
1583            needed -= wrap_count;
1584        }
1585
1586        // Reached top
1587        self.scroll_anchor.set((0, 0));
1588    }
1589}
1590
1591impl Widget for TextArea {
1592    fn render(&self, area: Rect, frame: &mut Frame) {
1593        if area.width < 1 || area.height < 1 {
1594            return;
1595        }
1596
1597        if frame.a11y_enabled() {
1598            frame.push_a11y_nodes(ftui_a11y::Accessible::accessibility_nodes(self, area));
1599        }
1600
1601        self.last_viewport_height.set(area.height as usize);
1602        self.last_area.set(area);
1603
1604        let deg = frame.buffer.degradation;
1605        let base_style = if deg.apply_styling() {
1606            self.style
1607        } else {
1608            Style::default()
1609        };
1610        clear_text_area(frame, area, base_style);
1611
1612        let gutter_w = self.gutter_width();
1613        let text_area_x = area.x.saturating_add(gutter_w);
1614        let text_area_w = area.width.saturating_sub(gutter_w) as usize;
1615        let vp_height = area.height as usize;
1616
1617        self.last_viewport_width.set(text_area_w);
1618
1619        let cursor = self.editor.cursor();
1620
1621        self.ensure_cursor_visible();
1622
1623        // Re-fetch potentially updated anchor
1624        let (scroll_top_line, scroll_top_vrow) = self.scroll_anchor.get();
1625        let scroll_left = self.scroll_left.get();
1626
1627        let rope = self.editor.rope();
1628        let nav = CursorNavigator::new(rope);
1629
1630        // Selection byte range for highlighting
1631        let sel_range = self.editor.selection().and_then(|sel| {
1632            if sel.is_empty() {
1633                None
1634            } else {
1635                let (a, b) = sel.byte_range(&nav);
1636                Some((a, b))
1637            }
1638        });
1639
1640        // Show placeholder if empty
1641        if self.editor.is_empty() && !self.placeholder.is_empty() {
1642            let style = if deg.apply_styling() {
1643                self.placeholder_style
1644            } else {
1645                Style::default()
1646            };
1647            draw_text_span(
1648                frame,
1649                text_area_x,
1650                area.y,
1651                &self.placeholder,
1652                style,
1653                area.right(),
1654            );
1655            if self.focused {
1656                frame.set_cursor(Some((text_area_x, area.y)));
1657            }
1658            return;
1659        }
1660
1661        if self.soft_wrap {
1662            self.scroll_left.set(0);
1663
1664            // Pre-calculate cursor wrap position
1665            let cursor_line_text = rope
1666                .line(cursor.line)
1667                .unwrap_or(std::borrow::Cow::Borrowed(""));
1668            let cursor_line_text = cursor_line_text.trim_end_matches(['\n', '\r']);
1669            let (cursor_wrap_idx, cursor_col_in_wrap) =
1670                Self::cursor_wrap_position(cursor_line_text, text_area_w, cursor.visual_col);
1671
1672            // Render wrapped lines starting from anchor
1673            let mut current_y = area.y;
1674            let bottom_y = area.bottom();
1675            let line_count = self.editor.line_count();
1676
1677            for line_idx in scroll_top_line..line_count {
1678                if current_y >= bottom_y {
1679                    break;
1680                }
1681
1682                let line_text = rope
1683                    .line(line_idx)
1684                    .unwrap_or(std::borrow::Cow::Borrowed(""));
1685                let line_text = line_text.trim_end_matches(['\n', '\r']);
1686
1687                let line_start_byte = nav.to_byte_index(nav.from_line_grapheme(line_idx, 0));
1688                // Syntax highlight spans for the whole logical line, computed
1689                // once and reused across every wrapped slice.
1690                let hl_spans = self.line_spans(line_idx, line_text, deg.apply_styling());
1691                let slices = Self::wrap_line_slices(line_text, text_area_w);
1692
1693                // If this is the start line, skip slices before anchor_vrow
1694                let start_slice = if line_idx == scroll_top_line {
1695                    scroll_top_vrow
1696                } else {
1697                    0
1698                };
1699
1700                for (slice_idx, slice) in slices.iter().enumerate().skip(start_slice) {
1701                    if current_y >= bottom_y {
1702                        break;
1703                    }
1704
1705                    // Line number gutter (only for first wrapped slice of the line)
1706                    if self.show_line_numbers && slice_idx == 0 {
1707                        let style = if deg.apply_styling() {
1708                            self.line_number_style
1709                        } else {
1710                            Style::default()
1711                        };
1712                        let num_str =
1713                            format!("{:>width$} ", line_idx + 1, width = (gutter_w - 2) as usize);
1714                        draw_text_span(frame, area.x, current_y, &num_str, style, text_area_x);
1715                    }
1716
1717                    // Cursor line highlight
1718                    if line_idx == cursor.line
1719                        && slice_idx == cursor_wrap_idx
1720                        && let Some(cl_style) = self.cursor_line_style
1721                        && deg.apply_styling()
1722                    {
1723                        for cx in text_area_x..area.right() {
1724                            if let Some(cell) = frame.buffer.get_mut(cx, current_y) {
1725                                apply_style(cell, cl_style);
1726                            }
1727                        }
1728                    }
1729
1730                    // Render graphemes inside the wrapped slice
1731                    let mut visual_x: usize = 0;
1732                    let mut grapheme_byte_offset = line_start_byte + slice.start_byte;
1733
1734                    for g in slice.text.graphemes(true) {
1735                        let g_width = display_width(g);
1736                        let g_byte_len = g.len();
1737
1738                        if visual_x >= text_area_w {
1739                            break;
1740                        }
1741
1742                        let px = text_area_x + visual_x as u16;
1743
1744                        // Syntax highlight first, then selection over it.
1745                        let mut g_style = base_style;
1746                        if let Some(hl) = style_at(
1747                            &hl_spans,
1748                            grapheme_byte_offset.saturating_sub(line_start_byte),
1749                        ) {
1750                            g_style = g_style.patch(&hl);
1751                        }
1752                        if let Some((sel_start, sel_end)) = sel_range
1753                            && grapheme_byte_offset >= sel_start
1754                            && grapheme_byte_offset < sel_end
1755                            && deg.apply_styling()
1756                        {
1757                            g_style = g_style.patch(&self.selection_style);
1758                        }
1759
1760                        if g_width > 0 {
1761                            draw_text_span(frame, px, current_y, g, g_style, area.right());
1762                        }
1763
1764                        visual_x += g_width;
1765                        grapheme_byte_offset += g_byte_len;
1766                    }
1767
1768                    // Set cursor position if focused
1769                    if self.focused && line_idx == cursor.line && slice_idx == cursor_wrap_idx {
1770                        let cursor_screen_x = text_area_x.saturating_add(cursor_col_in_wrap as u16);
1771                        if cursor_screen_x < area.right() {
1772                            frame.set_cursor(Some((cursor_screen_x, current_y)));
1773                        }
1774                    }
1775
1776                    current_y += 1;
1777                }
1778            }
1779
1780            return;
1781        }
1782
1783        // Render visible lines (no soft wrap)
1784        for row in 0..vp_height {
1785            let line_idx = scroll_top_line + row;
1786            let y = area.y.saturating_add(row as u16);
1787
1788            if line_idx >= self.editor.line_count() {
1789                break;
1790            }
1791
1792            // Line number gutter
1793            if self.show_line_numbers {
1794                let style = if deg.apply_styling() {
1795                    self.line_number_style
1796                } else {
1797                    Style::default()
1798                };
1799                let num_str = format!("{:>width$} ", line_idx + 1, width = (gutter_w - 2) as usize);
1800                draw_text_span(frame, area.x, y, &num_str, style, text_area_x);
1801            }
1802
1803            // Cursor line highlight
1804            if line_idx == cursor.line
1805                && let Some(cl_style) = self.cursor_line_style
1806                && deg.apply_styling()
1807            {
1808                for cx in text_area_x..area.right() {
1809                    if let Some(cell) = frame.buffer.get_mut(cx, y) {
1810                        apply_style(cell, cl_style);
1811                    }
1812                }
1813            }
1814
1815            // Get line text
1816            let line_text = rope
1817                .line(line_idx)
1818                .unwrap_or(std::borrow::Cow::Borrowed(""));
1819            let line_text = line_text.trim_end_matches(['\n', '\r']);
1820
1821            // Calculate line byte offset for selection mapping
1822            let line_start_byte = nav.to_byte_index(nav.from_line_grapheme(line_idx, 0));
1823            let hl_spans = self.line_spans(line_idx, line_text, deg.apply_styling());
1824
1825            // Render each grapheme
1826            let mut visual_x: usize = 0;
1827            let graphemes: Vec<&str> = line_text.graphemes(true).collect();
1828            let mut grapheme_byte_offset = line_start_byte;
1829
1830            for g in &graphemes {
1831                let g_width = display_width(g);
1832                let g_byte_len = g.len();
1833
1834                // Syntax highlight first, then selection over it.
1835                let mut g_style = base_style;
1836                if let Some(hl) = style_at(
1837                    &hl_spans,
1838                    grapheme_byte_offset.saturating_sub(line_start_byte),
1839                ) {
1840                    g_style = g_style.patch(&hl);
1841                }
1842                if let Some((sel_start, sel_end)) = sel_range
1843                    && grapheme_byte_offset >= sel_start
1844                    && grapheme_byte_offset < sel_end
1845                    && deg.apply_styling()
1846                {
1847                    g_style = g_style.patch(&self.selection_style);
1848                }
1849
1850                // Skip graphemes before horizontal scroll
1851                if visual_x + g_width <= scroll_left {
1852                    visual_x += g_width;
1853                    grapheme_byte_offset += g_byte_len;
1854                    continue;
1855                }
1856
1857                // Handle partial overlap at left edge
1858                if visual_x < scroll_left {
1859                    // Calculate visible width of the partially scrolled grapheme
1860                    let end_x = visual_x + g_width;
1861                    let visible_width = end_x.saturating_sub(scroll_left);
1862
1863                    // Render padding spaces for the visible portion to preserve background style
1864                    for i in 0..visible_width {
1865                        let screen_x = i; // Starts at 0 relative to text area
1866                        let px = text_area_x + screen_x as u16;
1867                        if px < area.right() {
1868                            draw_text_span(frame, px, y, " ", g_style, area.right());
1869                        }
1870                    }
1871
1872                    visual_x += g_width;
1873                    grapheme_byte_offset += g_byte_len;
1874                    continue;
1875                }
1876
1877                // Stop if past viewport
1878                let screen_x = visual_x.saturating_sub(scroll_left);
1879                if screen_x >= text_area_w {
1880                    break;
1881                }
1882
1883                let px = text_area_x + screen_x as u16;
1884
1885                // Write grapheme to buffer
1886                if g_width > 0 {
1887                    draw_text_span(frame, px, y, g, g_style, area.right());
1888                }
1889
1890                visual_x += g_width;
1891                grapheme_byte_offset += g_byte_len;
1892            }
1893        }
1894
1895        // Set cursor position if focused
1896        if self.focused {
1897            let cursor_row = cursor.line.saturating_sub(scroll_top_line);
1898            if cursor_row < vp_height {
1899                let cursor_screen_x = (cursor.visual_col.saturating_sub(scroll_left) as u16)
1900                    .saturating_add(text_area_x);
1901                let cursor_screen_y = area.y.saturating_add(cursor_row as u16);
1902                if cursor_screen_x < area.right() && cursor_screen_y < area.bottom() {
1903                    frame.set_cursor(Some((cursor_screen_x, cursor_screen_y)));
1904                }
1905            }
1906        }
1907    }
1908
1909    fn is_essential(&self) -> bool {
1910        true
1911    }
1912}
1913
1914impl ftui_a11y::Accessible for TextArea {
1915    fn accessibility_nodes(&self, area: Rect) -> Vec<ftui_a11y::node::A11yNodeInfo> {
1916        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState};
1917
1918        if area.is_empty() {
1919            return Vec::new();
1920        }
1921        let text = self.text();
1922        let name = if text.is_empty() {
1923            self.placeholder.clone()
1924        } else {
1925            text
1926        };
1927        vec![
1928            A11yNodeInfo::new(crate::a11y_node_id(area), A11yRole::TextInput, area)
1929                .with_name(name)
1930                .with_description("multi-line text input")
1931                .with_state(A11yState {
1932                    focused: self.focused,
1933                    ..A11yState::default()
1934                }),
1935        ]
1936    }
1937}
1938
1939impl StatefulWidget for TextArea {
1940    type State = TextAreaState;
1941
1942    fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
1943        state.last_viewport_height = area.height;
1944        state.last_viewport_width = area.width;
1945        Widget::render(self, area, frame);
1946    }
1947}
1948
1949#[cfg(test)]
1950mod tests {
1951    use super::*;
1952
1953    mod mouse {
1954        use super::*;
1955        use ftui_render::grapheme_pool::GraphemePool;
1956
1957        fn rendered(ta: &TextArea, area: Rect) {
1958            let mut pool = GraphemePool::new();
1959            let mut frame = Frame::new(area.right(), area.bottom(), &mut pool);
1960            Widget::render(ta, area, &mut frame);
1961        }
1962
1963        fn press(ta: &mut TextArea, x: u16, y: u16, at_ms: u64) -> bool {
1964            let down = MouseEvent::new(MouseEventKind::Down(MouseButton::Left), x, y);
1965            let changed = ta.handle_event_at(&Event::Mouse(down), at_ms);
1966            let up = MouseEvent::new(MouseEventKind::Up(MouseButton::Left), x, y);
1967            ta.handle_event_at(&Event::Mouse(up), at_ms);
1968            changed
1969        }
1970
1971        const AREA: Rect = Rect::new(2, 1, 30, 5);
1972
1973        #[test]
1974        fn click_places_the_cursor_under_the_pointer() {
1975            let mut ta = TextArea::new().with_text("hello world\nsecond line");
1976            rendered(&ta, AREA);
1977            assert!(press(&mut ta, AREA.x + 7, AREA.y + 1, 0));
1978            assert_eq!((ta.cursor().line, ta.cursor().grapheme), (1, 7));
1979            assert_eq!(ta.selection(), None);
1980            // Past the end of a line lands at its end.
1981            press(&mut ta, AREA.x + 25, AREA.y, 1000);
1982            assert_eq!((ta.cursor().line, ta.cursor().grapheme), (0, 11));
1983        }
1984
1985        #[test]
1986        fn textarea_double_click_selects_word() {
1987            let mut ta = TextArea::new().with_text("hello brave world");
1988            rendered(&ta, AREA);
1989            press(&mut ta, AREA.x + 8, AREA.y, 0);
1990            press(&mut ta, AREA.x + 8, AREA.y, 200);
1991            assert_eq!(ta.selected_text().as_deref(), Some("brave"));
1992        }
1993
1994        #[test]
1995        fn textarea_triple_click_selects_line() {
1996            let mut ta = TextArea::new().with_text("first line\nhello brave world\nlast");
1997            rendered(&ta, AREA);
1998            for at in [0, 150, 300] {
1999                press(&mut ta, AREA.x + 3, AREA.y + 1, at);
2000            }
2001            assert_eq!(ta.selected_text().as_deref(), Some("hello brave world"));
2002        }
2003
2004        #[test]
2005        fn slow_or_distant_second_press_is_a_new_click() {
2006            let mut ta = TextArea::new().with_text("hello brave world");
2007            rendered(&ta, AREA);
2008            press(&mut ta, AREA.x + 8, AREA.y, 0);
2009            press(&mut ta, AREA.x + 8, AREA.y, 301);
2010            assert_eq!(ta.selection(), None, "outside the 300 ms window");
2011            press(&mut ta, AREA.x + 14, AREA.y, 400);
2012            assert_eq!(ta.selection(), None, "more than one cell away");
2013            assert_eq!(ta.cursor().grapheme, 14);
2014        }
2015
2016        #[test]
2017        fn drag_extends_the_selection_from_the_press() {
2018            let mut ta = TextArea::new().with_text("hello brave world\nnext");
2019            rendered(&ta, AREA);
2020            let down = MouseEvent::new(MouseEventKind::Down(MouseButton::Left), AREA.x + 6, AREA.y);
2021            ta.handle_event_at(&Event::Mouse(down), 0);
2022            let drag = MouseEvent::new(
2023                MouseEventKind::Drag(MouseButton::Left),
2024                AREA.x + 2,
2025                AREA.y + 1,
2026            );
2027            assert!(ta.handle_event_at(&Event::Mouse(drag), 10));
2028            assert_eq!(ta.selected_text().as_deref(), Some("brave world\nne"));
2029        }
2030
2031        #[test]
2032        fn events_outside_the_area_are_ignored() {
2033            let mut ta = TextArea::new().with_text("hello");
2034            // Before any render there is no area to hit.
2035            assert!(!press(&mut ta, 0, 0, 0));
2036            rendered(&ta, AREA);
2037            let before = ta.cursor();
2038            assert!(!press(&mut ta, AREA.x - 1, AREA.y, 1000));
2039            assert!(!press(&mut ta, AREA.x, AREA.bottom(), 2000));
2040            let drag = MouseEvent::new(MouseEventKind::Drag(MouseButton::Left), AREA.x + 2, AREA.y);
2041            assert!(
2042                !ta.handle_event_at(&Event::Mouse(drag), 3000),
2043                "no drag without a press inside"
2044            );
2045            assert_eq!(ta.cursor(), before);
2046        }
2047
2048        #[test]
2049        fn click_accounts_for_gutter_and_vertical_scroll() {
2050            let text: String = (0..20).map(|i| format!("line{i}\n")).collect();
2051            let mut ta = TextArea::new().with_text(&text).with_line_numbers(true);
2052            ta.set_cursor_position(CursorPosition::new(19, 0, 0));
2053            rendered(&ta, AREA);
2054            let (top, _) = ta.scroll_anchor.get();
2055            assert!(top > 0, "the cursor at line 19 scrolled the view");
2056            let gutter = ta.gutter_width();
2057            press(&mut ta, AREA.x + gutter + 4, AREA.y + 2, 0);
2058            assert_eq!((ta.cursor().line, ta.cursor().grapheme), (top + 2, 4));
2059            // A click in the gutter lands at column 0.
2060            press(&mut ta, AREA.x, AREA.y, 1000);
2061            assert_eq!((ta.cursor().line, ta.cursor().grapheme), (top, 0));
2062        }
2063
2064        #[test]
2065        fn click_on_a_wrapped_row_maps_into_its_slice() {
2066            // Ten columns wide: "aaaa bbbb " fits the first row, "cccc" wraps.
2067            let mut ta = TextArea::new()
2068                .with_text("aaaa bbbb cccc")
2069                .with_soft_wrap(true);
2070            let area = Rect::new(0, 0, 10, 3);
2071            rendered(&ta, area);
2072            press(&mut ta, 2, 1, 0);
2073            assert_eq!((ta.cursor().line, ta.cursor().grapheme), (0, 12));
2074            // Past the end of a row that wraps stays on that row.
2075            press(&mut ta, 9, 0, 1000);
2076            assert_eq!(ta.cursor().grapheme, 9);
2077        }
2078
2079        fn key(ta: &mut TextArea, code: KeyCode, modifiers: Modifiers) {
2080            ta.handle_event(&Event::Key(KeyEvent {
2081                code,
2082                modifiers,
2083                kind: KeyEventKind::Press,
2084            }));
2085        }
2086
2087        fn drawn_cursor(ta: &TextArea, area: Rect) -> (Option<(u16, u16)>, Vec<String>) {
2088            let mut pool = GraphemePool::new();
2089            let mut frame = Frame::new(area.right(), area.bottom(), &mut pool);
2090            Widget::render(ta, area, &mut frame);
2091            let row: Vec<String> = (area.x..area.right())
2092                .map(|x| {
2093                    let cell = frame.buffer.get(x, area.y).unwrap();
2094                    cell.content
2095                        .as_char()
2096                        .map(String::from)
2097                        .or_else(|| {
2098                            cell.content
2099                                .grapheme_id()
2100                                .and_then(|id| frame.pool.get(id).map(str::to_string))
2101                        })
2102                        .unwrap_or_default()
2103                })
2104                .collect();
2105            (frame.cursor_position, row)
2106        }
2107
2108        /// #102 (3): TextArea draws text in logical order, so keys, the drawn
2109        /// caret, clicks, delete and undo must all use the same logical
2110        /// layout, with whole grapheme clusters (default features include
2111        /// `bidi`).
2112        #[test]
2113        fn rtl_and_clusters_render_navigate_click_delete_consistently() {
2114            let text = "a\u{0301} \u{05D0}\u{05D1}";
2115            for wrap in [false, true] {
2116                let mut ta = TextArea::new()
2117                    .with_text(text)
2118                    .with_soft_wrap(wrap)
2119                    .with_focus(true);
2120                let (_, row) = drawn_cursor(&ta, AREA);
2121                assert_eq!(
2122                    &row[..4],
2123                    ["a\u{0301}", " ", "\u{05D0}", "\u{05D1}"],
2124                    "wrap={wrap}"
2125                );
2126
2127                key(&mut ta, KeyCode::Home, Modifiers::NONE);
2128                assert_eq!(ta.cursor().grapheme, 0);
2129                key(&mut ta, KeyCode::Right, Modifiers::NONE);
2130                key(&mut ta, KeyCode::Right, Modifiers::NONE);
2131                assert_eq!(ta.cursor().grapheme, 2, "wrap={wrap}");
2132                let (cursor, _) = drawn_cursor(&ta, AREA);
2133                assert_eq!(
2134                    cursor,
2135                    Some((AREA.x + 2, AREA.y)),
2136                    "wrap={wrap}: caret before the alef"
2137                );
2138
2139                key(&mut ta, KeyCode::End, Modifiers::NONE);
2140                assert_eq!(ta.cursor().grapheme, 4);
2141                let (cursor, _) = drawn_cursor(&ta, AREA);
2142                assert_eq!(cursor, Some((AREA.x + 4, AREA.y)), "wrap={wrap}");
2143
2144                // Clicking between the alef and bet lands between them.
2145                press(&mut ta, AREA.x + 3, AREA.y, 0);
2146                assert_eq!(ta.cursor().grapheme, 3, "wrap={wrap}");
2147                key(&mut ta, KeyCode::Backspace, Modifiers::NONE);
2148                assert_eq!(ta.text(), "a\u{0301} \u{05D1}", "wrap={wrap}");
2149                ta.undo();
2150                assert_eq!(ta.text(), text, "wrap={wrap}");
2151
2152                // Backspace after the combining cluster removes it whole.
2153                press(&mut ta, AREA.x + 1, AREA.y, 5000);
2154                assert_eq!(ta.cursor().grapheme, 1, "wrap={wrap}");
2155                key(&mut ta, KeyCode::Backspace, Modifiers::NONE);
2156                assert_eq!(ta.text(), " \u{05D0}\u{05D1}", "wrap={wrap}");
2157            }
2158        }
2159    }
2160
2161    #[test]
2162    fn undo_groups_keyboard_clock_paste_and_focus() {
2163        let key = |c| {
2164            Event::Key(KeyEvent {
2165                code: KeyCode::Char(c),
2166                modifiers: Modifiers::NONE,
2167                kind: KeyEventKind::Press,
2168            })
2169        };
2170        let mut ta = TextArea::new();
2171        for (tick, c) in "hello world".chars().enumerate() {
2172            ta.handle_event_at(&key(c), tick as u64);
2173        }
2174        assert_eq!(ta.undo_group_count(), 2);
2175        assert_eq!(ta.undo_op_count(), 11);
2176        ta.handle_event_at(
2177            &Event::Key(KeyEvent {
2178                code: KeyCode::Char('z'),
2179                modifiers: Modifiers::CTRL,
2180                kind: KeyEventKind::Press,
2181            }),
2182            11,
2183        );
2184        assert_eq!(ta.text(), "hello ");
2185        ta.redo();
2186        ta.handle_event_at(&key('x'), 600);
2187        assert_eq!(ta.undo_group_count(), 3);
2188        ta.handle_event_at(
2189            &Event::Paste(ftui_core::event::PasteEvent::bracketed("p")),
2190            601,
2191        );
2192        ta.handle_event_at(&key('y'), 602);
2193        assert_eq!(ta.undo_group_count(), 5);
2194        ta.handle_event_at(&Event::Focus(false), 603);
2195        ta.handle_event_at(&key('z'), 604);
2196        assert_eq!(ta.undo_group_count(), 6);
2197        ta.set_focused(false);
2198        ta.handle_event_at(&key('q'), 605);
2199        assert_eq!(ta.undo_group_count(), 7);
2200        // Exercise the normal event entrypoint without a wall-clock deadline.
2201        let mut live = TextArea::new();
2202        live.set_undo_coalesce_idle(Duration::MAX);
2203        live.handle_event(&key('a'));
2204        live.handle_event(&key('b'));
2205        assert_eq!(live.undo_group_count(), 1);
2206        live.undo();
2207        assert_eq!(live.text(), "");
2208    }
2209
2210    #[test]
2211    fn selection_edit_keyboard_undo_redo_restores_cursor() {
2212        for edit in [KeyCode::Char('X'), KeyCode::Backspace, KeyCode::Delete] {
2213            let mut ta = TextArea::new().with_text("界e\u{301}\nsecond");
2214            let key = |code, modifiers| {
2215                Event::Key(KeyEvent {
2216                    code,
2217                    modifiers,
2218                    kind: KeyEventKind::Press,
2219                })
2220            };
2221            ta.handle_event(&key(KeyCode::Char('a'), Modifiers::CTRL));
2222            let original_cursor = ta.cursor();
2223            assert_eq!(original_cursor, CursorPosition::new(1, 6, 6));
2224            ta.handle_event(&key(edit, Modifiers::empty()));
2225            let expected = if edit == KeyCode::Char('X') { "X" } else { "" };
2226            assert_eq!(ta.text(), expected);
2227            let edited_cursor = ta.cursor();
2228            ta.handle_event(&key(KeyCode::Char('z'), Modifiers::CTRL));
2229            assert_eq!(ta.text(), "界e\u{301}\nsecond");
2230            assert_eq!(ta.cursor(), original_cursor);
2231            ta.handle_event(&key(KeyCode::Char('y'), Modifiers::CTRL));
2232            assert_eq!(ta.text(), expected);
2233            assert_eq!(ta.cursor(), edited_cursor);
2234        }
2235    }
2236
2237    #[test]
2238    fn paragraph_keys_move_select_and_preserve_line_navigation() {
2239        for soft_wrap in [false, true] {
2240            let mut ta = TextArea::new()
2241                .with_text("first\ncontinued\n\nsecond\n\nlast")
2242                .with_soft_wrap(soft_wrap);
2243            ta.move_to_document_start();
2244            let key = |code, modifiers, kind| {
2245                Event::Key(KeyEvent {
2246                    code,
2247                    modifiers,
2248                    kind,
2249                })
2250            };
2251            assert!(ta.handle_event(&key(KeyCode::Down, Modifiers::CTRL, KeyEventKind::Press)));
2252            assert_eq!(ta.cursor(), CursorPosition::new(2, 0, 0));
2253            assert!(ta.handle_event(&key(
2254                KeyCode::Down,
2255                Modifiers::CTRL | Modifiers::SHIFT,
2256                KeyEventKind::Repeat
2257            )));
2258            assert_eq!(ta.cursor(), CursorPosition::new(4, 0, 0));
2259            assert_eq!(ta.selected_text().as_deref(), Some("\nsecond\n"));
2260            let anchor = ta.selection().unwrap().anchor;
2261            ta.handle_event(&key(
2262                KeyCode::Up,
2263                Modifiers::CTRL | Modifiers::SHIFT,
2264                KeyEventKind::Press,
2265            ));
2266            assert_eq!(ta.selection().unwrap().anchor, anchor);
2267            assert_eq!(ta.cursor(), anchor);
2268            assert!(!ta.handle_event(&key(KeyCode::Up, Modifiers::CTRL, KeyEventKind::Release)));
2269            assert_eq!(ta.cursor(), anchor);
2270            ta.handle_event(&key(KeyCode::Up, Modifiers::CTRL, KeyEventKind::Press));
2271            assert_eq!(ta.cursor(), CursorPosition::default());
2272            assert!(ta.selection().is_none());
2273            ta.handle_event(&key(KeyCode::Down, Modifiers::empty(), KeyEventKind::Press));
2274            assert_eq!(ta.cursor().line, 1);
2275            ta.handle_event(&key(KeyCode::Up, Modifiers::SHIFT, KeyEventKind::Press));
2276            assert_eq!(ta.cursor().line, 0);
2277            assert_eq!(ta.selected_text().as_deref(), Some("first\n"));
2278        }
2279    }
2280
2281    fn raw_row_text(frame: &Frame, y: u16, width: u16) -> String {
2282        (0..width)
2283            .map(|x| {
2284                frame
2285                    .buffer
2286                    .get(x, y)
2287                    .and_then(|cell| cell.content.as_char())
2288                    .unwrap_or(' ')
2289            })
2290            .collect()
2291    }
2292
2293    #[test]
2294    fn new_textarea_is_empty() {
2295        let ta = TextArea::new();
2296        assert!(ta.is_empty());
2297        assert_eq!(ta.text(), "");
2298        assert_eq!(ta.line_count(), 1); // empty rope has 1 line
2299    }
2300
2301    #[test]
2302    fn accessibility_preserves_multiline_content_and_focus() {
2303        use ftui_a11y::Accessible;
2304        use ftui_a11y::node::A11yRole;
2305
2306        let area = Rect::new(3, 4, 20, 2);
2307        let mut textarea = TextArea::new().with_text("first é\nsecond 日");
2308        let initial = textarea.accessibility_nodes(area);
2309        assert_eq!(initial.len(), 1);
2310        assert_eq!(initial[0].role, A11yRole::TextInput);
2311        assert_eq!(initial[0].name.as_deref(), Some("first é\nsecond 日"));
2312        assert!(!initial[0].state.focused);
2313        textarea.set_focused(true);
2314        let focused = textarea.accessibility_nodes(area);
2315        assert!(focused[0].state.focused);
2316        assert_eq!(focused[0].id, initial[0].id);
2317        assert_eq!(focused[0].bounds, area);
2318        assert!(
2319            textarea
2320                .accessibility_nodes(Rect::new(0, 0, 0, 2))
2321                .is_empty()
2322        );
2323        let empty = TextArea::new().with_placeholder("Write a message");
2324        assert_eq!(
2325            empty.accessibility_nodes(area)[0].name.as_deref(),
2326            Some("Write a message")
2327        );
2328    }
2329
2330    #[test]
2331    fn render_collects_textarea_accessibility_only_when_enabled() {
2332        use ftui_a11y::tree::A11yTreeBuilder;
2333        use ftui_render::grapheme_pool::GraphemePool;
2334
2335        let textarea = TextArea::new()
2336            .with_text("line one\nline two")
2337            .with_focus(true);
2338        let area = Rect::new(2, 1, 12, 2);
2339        let mut pool = GraphemePool::new();
2340        let mut frame = Frame::new(20, 5, &mut pool);
2341        Widget::render(&textarea, area, &mut frame);
2342        assert!(frame.a11y_order().is_empty());
2343
2344        let mut builder = A11yTreeBuilder::new();
2345        let mut frame = Frame::new(20, 5, &mut pool);
2346        frame.set_a11y(&mut builder);
2347        Widget::render(&textarea, area, &mut frame);
2348        frame.finish_a11y();
2349        drop(frame);
2350        let tree = builder.build();
2351        assert_eq!(tree.nodes().count(), 1);
2352        assert_eq!(
2353            tree.focused().and_then(|node| node.name.as_deref()),
2354            Some("line one\nline two")
2355        );
2356    }
2357
2358    #[test]
2359    fn with_text_builder() {
2360        let ta = TextArea::new().with_text("hello\nworld");
2361        assert_eq!(ta.text(), "hello\nworld");
2362        assert_eq!(ta.line_count(), 2);
2363    }
2364
2365    #[test]
2366    fn insert_text_and_newline() {
2367        let mut ta = TextArea::new();
2368        ta.insert_text("hello");
2369        ta.insert_newline();
2370        ta.insert_text("world");
2371        assert_eq!(ta.text(), "hello\nworld");
2372        assert_eq!(ta.line_count(), 2);
2373    }
2374
2375    #[test]
2376    fn delete_backward_works() {
2377        let mut ta = TextArea::new().with_text("hello");
2378        ta.move_to_document_end();
2379        ta.delete_backward();
2380        assert_eq!(ta.text(), "hell");
2381    }
2382
2383    #[test]
2384    fn cursor_movement() {
2385        let mut ta = TextArea::new().with_text("abc\ndef\nghi");
2386        ta.move_to_document_start();
2387        assert_eq!(ta.cursor().line, 0);
2388        assert_eq!(ta.cursor().grapheme, 0);
2389
2390        ta.move_down();
2391        assert_eq!(ta.cursor().line, 1);
2392
2393        ta.move_to_line_end();
2394        assert_eq!(ta.cursor().grapheme, 3);
2395
2396        ta.move_to_document_end();
2397        assert_eq!(ta.cursor().line, 2);
2398    }
2399
2400    #[test]
2401    fn undo_redo() {
2402        let mut ta = TextArea::new();
2403        ta.insert_text("abc");
2404        assert_eq!(ta.text(), "abc");
2405        ta.undo();
2406        assert_eq!(ta.text(), "");
2407        ta.redo();
2408        assert_eq!(ta.text(), "abc");
2409    }
2410
2411    #[test]
2412    fn selection_and_delete() {
2413        let mut ta = TextArea::new().with_text("hello world");
2414        ta.move_to_document_start();
2415        for _ in 0..5 {
2416            ta.select_right();
2417        }
2418        assert_eq!(ta.selected_text(), Some("hello".to_string()));
2419        ta.delete_backward();
2420        assert_eq!(ta.text(), " world");
2421    }
2422
2423    #[test]
2424    fn select_all() {
2425        let mut ta = TextArea::new().with_text("abc\ndef");
2426        ta.select_all();
2427        assert_eq!(ta.selected_text(), Some("abc\ndef".to_string()));
2428    }
2429
2430    #[test]
2431    fn set_text_resets() {
2432        let mut ta = TextArea::new().with_text("old");
2433        ta.insert_text(" stuff");
2434        ta.set_text("new");
2435        assert_eq!(ta.text(), "new");
2436    }
2437
2438    #[test]
2439    fn scroll_follows_cursor() {
2440        let mut ta = TextArea::new();
2441        // Insert many lines
2442        for i in 0..50 {
2443            ta.insert_text(&format!("line {}\n", i));
2444        }
2445        // Cursor should be at the bottom, scroll anchor adjusted.
2446        assert!(ta.scroll_anchor.get().0 > 0);
2447        assert!(ta.cursor().line >= 49);
2448
2449        // Move to top
2450        ta.move_to_document_start();
2451        assert_eq!(ta.scroll_anchor.get().0, 0);
2452    }
2453
2454    #[test]
2455    fn gutter_width_without_line_numbers() {
2456        let ta = TextArea::new();
2457        assert_eq!(ta.gutter_width(), 0);
2458    }
2459
2460    #[test]
2461    fn gutter_width_with_line_numbers() {
2462        let mut ta = TextArea::new().with_line_numbers(true);
2463        ta.insert_text("a\nb\nc");
2464        assert_eq!(ta.gutter_width(), 3); // 1 digit + space + separator
2465    }
2466
2467    #[test]
2468    fn gutter_width_many_lines() {
2469        let mut ta = TextArea::new().with_line_numbers(true);
2470        for i in 0..100 {
2471            ta.insert_text(&format!("line {}\n", i));
2472        }
2473        assert_eq!(ta.gutter_width(), 5); // 3 digits + space + separator
2474    }
2475
2476    #[test]
2477    fn focus_state() {
2478        let mut ta = TextArea::new();
2479        assert!(!ta.is_focused());
2480        ta.set_focused(true);
2481        assert!(ta.is_focused());
2482    }
2483
2484    #[test]
2485    fn word_movement() {
2486        let mut ta = TextArea::new().with_text("hello world foo");
2487        ta.move_to_document_start();
2488        ta.move_word_right();
2489        assert_eq!(ta.cursor().grapheme, 6);
2490        ta.move_word_left();
2491        assert_eq!(ta.cursor().grapheme, 0);
2492    }
2493
2494    #[test]
2495    fn page_up_down() {
2496        let mut ta = TextArea::new();
2497        for i in 0..50 {
2498            ta.insert_text(&format!("line {}\n", i));
2499        }
2500        ta.move_to_document_start();
2501        let state = TextAreaState {
2502            last_viewport_height: 10,
2503            last_viewport_width: 80,
2504        };
2505        ta.page_down(&state);
2506        assert!(ta.cursor().line >= 10);
2507        ta.page_up(&state);
2508        assert_eq!(ta.cursor().line, 0);
2509    }
2510
2511    #[test]
2512    fn insert_replaces_selection() {
2513        let mut ta = TextArea::new().with_text("hello world");
2514        ta.move_to_document_start();
2515        for _ in 0..5 {
2516            ta.select_right();
2517        }
2518        ta.insert_text("goodbye");
2519        assert_eq!(ta.text(), "goodbye world");
2520    }
2521
2522    #[test]
2523    fn insert_single_char() {
2524        let mut ta = TextArea::new();
2525        ta.insert_char('X');
2526        assert_eq!(ta.text(), "X");
2527        assert_eq!(ta.cursor().grapheme, 1);
2528    }
2529
2530    #[test]
2531    fn insert_multiline_text() {
2532        let mut ta = TextArea::new();
2533        ta.insert_text("line1\nline2\nline3");
2534        assert_eq!(ta.line_count(), 3);
2535        assert_eq!(ta.cursor().line, 2);
2536    }
2537
2538    #[test]
2539    fn delete_forward_works() {
2540        let mut ta = TextArea::new().with_text("hello");
2541        ta.move_to_document_start();
2542        ta.delete_forward();
2543        assert_eq!(ta.text(), "ello");
2544    }
2545
2546    #[test]
2547    fn delete_backward_at_line_start_joins_lines() {
2548        let mut ta = TextArea::new().with_text("abc\ndef");
2549        // Move to start of line 2
2550        ta.move_to_document_start();
2551        ta.move_down();
2552        ta.move_to_line_start();
2553        ta.delete_backward();
2554        assert_eq!(ta.text(), "abcdef");
2555        assert_eq!(ta.line_count(), 1);
2556    }
2557
2558    #[test]
2559    fn cursor_horizontal_movement() {
2560        let mut ta = TextArea::new().with_text("abc");
2561        ta.move_to_document_start();
2562        ta.move_right();
2563        assert_eq!(ta.cursor().grapheme, 1);
2564        ta.move_right();
2565        assert_eq!(ta.cursor().grapheme, 2);
2566        ta.move_left();
2567        assert_eq!(ta.cursor().grapheme, 1);
2568    }
2569
2570    #[test]
2571    fn cursor_vertical_maintains_column() {
2572        let mut ta = TextArea::new().with_text("abcde\nfg\nhijkl");
2573        ta.move_to_document_start();
2574        ta.move_to_line_end(); // col 5
2575        ta.move_down(); // line 1 only has 2 chars, should clamp
2576        assert_eq!(ta.cursor().line, 1);
2577        ta.move_down(); // line 2 has 5 chars, should restore col
2578        assert_eq!(ta.cursor().line, 2);
2579    }
2580
2581    #[test]
2582    fn selection_shift_arrow() {
2583        let mut ta = TextArea::new().with_text("abcdef");
2584        ta.move_to_document_start();
2585        ta.select_right();
2586        ta.select_right();
2587        ta.select_right();
2588        assert_eq!(ta.selected_text(), Some("abc".to_string()));
2589    }
2590
2591    #[test]
2592    fn selection_extends_up_down() {
2593        let mut ta = TextArea::new().with_text("line1\nline2\nline3");
2594        ta.move_to_document_start();
2595        ta.select_down();
2596        let sel = ta.selected_text().unwrap();
2597        assert!(sel.contains('\n'));
2598    }
2599
2600    #[test]
2601    fn undo_chain() {
2602        let mut ta = TextArea::new();
2603        ta.insert_text("a");
2604        ta.insert_text("b");
2605        ta.insert_text("c");
2606        assert_eq!(ta.text(), "abc");
2607        ta.undo();
2608        ta.undo();
2609        ta.undo();
2610        assert_eq!(ta.text(), "");
2611    }
2612
2613    #[test]
2614    fn redo_discarded_on_new_edit() {
2615        let mut ta = TextArea::new();
2616        ta.insert_text("abc");
2617        ta.undo();
2618        ta.insert_text("xyz");
2619        ta.redo(); // should be no-op
2620        assert_eq!(ta.text(), "xyz");
2621    }
2622
2623    #[test]
2624    fn clear_selection() {
2625        let mut ta = TextArea::new().with_text("hello");
2626        ta.select_all();
2627        assert!(ta.selection().is_some());
2628        ta.clear_selection();
2629        assert!(ta.selection().is_none());
2630    }
2631
2632    #[test]
2633    fn delete_word_backward() {
2634        let mut ta = TextArea::new().with_text("hello world");
2635        ta.move_to_document_end();
2636        ta.delete_word_backward();
2637        assert_eq!(ta.text(), "hello ");
2638    }
2639
2640    #[test]
2641    fn delete_to_end_of_line() {
2642        let mut ta = TextArea::new().with_text("hello world");
2643        ta.move_to_document_start();
2644        ta.move_right(); // after 'h'
2645        ta.delete_to_end_of_line();
2646        assert_eq!(ta.text(), "h");
2647    }
2648
2649    #[test]
2650    fn placeholder_builder() {
2651        let ta = TextArea::new().with_placeholder("Enter text...");
2652        assert!(ta.is_empty());
2653        assert_eq!(ta.placeholder, "Enter text...");
2654    }
2655
2656    #[test]
2657    fn soft_wrap_builder() {
2658        let ta = TextArea::new().with_soft_wrap(true);
2659        assert!(ta.soft_wrap);
2660    }
2661
2662    #[test]
2663    fn soft_wrap_renders_wrapped_lines() {
2664        use crate::Widget;
2665        use ftui_render::grapheme_pool::GraphemePool;
2666
2667        let ta = TextArea::new().with_soft_wrap(true).with_text("abcdef");
2668        let area = Rect::new(0, 0, 3, 2);
2669        let mut pool = GraphemePool::new();
2670        let mut frame = Frame::new(3, 2, &mut pool);
2671        Widget::render(&ta, area, &mut frame);
2672
2673        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('a'));
2674        assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('c'));
2675        assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('d'));
2676        assert_eq!(frame.buffer.get(2, 1).unwrap().content.as_char(), Some('f'));
2677    }
2678
2679    #[test]
2680    fn max_height_builder() {
2681        let ta = TextArea::new().with_max_height(10);
2682        assert_eq!(ta.max_height, 10);
2683    }
2684
2685    #[test]
2686    fn editor_access() {
2687        let mut ta = TextArea::new().with_text("test");
2688        assert_eq!(ta.editor().text(), "test");
2689        ta.editor_mut().insert_char('!');
2690        assert!(ta.text().contains('!'));
2691    }
2692
2693    #[test]
2694    fn move_to_line_start_and_end() {
2695        let mut ta = TextArea::new().with_text("hello world");
2696        ta.move_to_document_start();
2697        ta.move_to_line_end();
2698        assert_eq!(ta.cursor().grapheme, 11);
2699        ta.move_to_line_start();
2700        assert_eq!(ta.cursor().grapheme, 0);
2701    }
2702
2703    #[test]
2704    fn render_empty_with_placeholder() {
2705        use ftui_render::grapheme_pool::GraphemePool;
2706        let ta = TextArea::new()
2707            .with_placeholder("Type here")
2708            .with_focus(true);
2709        let mut pool = GraphemePool::new();
2710        let mut frame = Frame::new(20, 5, &mut pool);
2711        let area = Rect::new(0, 0, 20, 5);
2712        Widget::render(&ta, area, &mut frame);
2713        // Placeholder should be rendered
2714        let cell = frame.buffer.get(0, 0).unwrap();
2715        assert_eq!(cell.content.as_char(), Some('T'));
2716        // Cursor should be set
2717        assert!(frame.cursor_position.is_some());
2718    }
2719
2720    #[test]
2721    fn render_with_content() {
2722        use ftui_render::grapheme_pool::GraphemePool;
2723        let ta = TextArea::new().with_text("abc\ndef").with_focus(true);
2724        let mut pool = GraphemePool::new();
2725        let mut frame = Frame::new(20, 5, &mut pool);
2726        let area = Rect::new(0, 0, 20, 5);
2727        Widget::render(&ta, area, &mut frame);
2728        let cell = frame.buffer.get(0, 0).unwrap();
2729        assert_eq!(cell.content.as_char(), Some('a'));
2730    }
2731
2732    #[test]
2733    fn render_shorter_text_clears_stale_suffix_and_extra_lines() {
2734        use ftui_render::grapheme_pool::GraphemePool;
2735
2736        let area = Rect::new(0, 0, 8, 3);
2737        let mut pool = GraphemePool::new();
2738        let mut frame = Frame::new(8, 3, &mut pool);
2739
2740        Widget::render(
2741            &TextArea::new().with_text("abcdef\nghijkl"),
2742            area,
2743            &mut frame,
2744        );
2745        Widget::render(&TextArea::new().with_text("hi"), area, &mut frame);
2746
2747        assert_eq!(raw_row_text(&frame, 0, 8), "hi      ");
2748        assert_eq!(raw_row_text(&frame, 1, 8), "        ");
2749        assert_eq!(raw_row_text(&frame, 2, 8), "        ");
2750    }
2751
2752    #[test]
2753    fn render_line_numbers_without_styling() {
2754        use ftui_render::budget::DegradationLevel;
2755        use ftui_render::grapheme_pool::GraphemePool;
2756
2757        let ta = TextArea::new().with_text("a\nb").with_line_numbers(true);
2758        let mut pool = GraphemePool::new();
2759        let mut frame = Frame::new(8, 2, &mut pool);
2760        frame.set_degradation(DegradationLevel::NoStyling);
2761
2762        Widget::render(&ta, Rect::new(0, 0, 8, 2), &mut frame);
2763
2764        let cell = frame.buffer.get(0, 0).unwrap();
2765        assert_eq!(cell.content.as_char(), Some('1'));
2766    }
2767
2768    #[test]
2769    fn stateful_render_updates_viewport_state() {
2770        use ftui_render::grapheme_pool::GraphemePool;
2771
2772        let ta = TextArea::new();
2773        let mut state = TextAreaState::default();
2774        let mut pool = GraphemePool::new();
2775        let mut frame = Frame::new(10, 3, &mut pool);
2776        let area = Rect::new(0, 0, 10, 3);
2777
2778        StatefulWidget::render(&ta, area, &mut frame, &mut state);
2779
2780        assert_eq!(state.last_viewport_height, 3);
2781        assert_eq!(state.last_viewport_width, 10);
2782    }
2783
2784    #[test]
2785    fn render_zero_area_no_panic() {
2786        let ta = TextArea::new().with_text("test");
2787        use ftui_render::grapheme_pool::GraphemePool;
2788        let mut pool = GraphemePool::new();
2789        let mut frame = Frame::new(10, 10, &mut pool);
2790        Widget::render(&ta, Rect::new(0, 0, 0, 0), &mut frame);
2791    }
2792
2793    #[test]
2794    fn is_essential() {
2795        let ta = TextArea::new();
2796        assert!(Widget::is_essential(&ta));
2797    }
2798
2799    #[test]
2800    fn default_impl() {
2801        let ta = TextArea::default();
2802        assert!(ta.is_empty());
2803    }
2804
2805    #[test]
2806    fn insert_newline_splits_line() {
2807        let mut ta = TextArea::new().with_text("abcdef");
2808        ta.move_to_document_start();
2809        ta.move_right();
2810        ta.move_right();
2811        ta.move_right();
2812        ta.insert_newline();
2813        assert_eq!(ta.line_count(), 2);
2814        assert_eq!(ta.cursor().line, 1);
2815    }
2816
2817    #[test]
2818    fn command_chords_do_not_type_their_letter() {
2819        // macOS sends Cmd as SUPER. Cmd+V is a paste shortcut handled by the
2820        // host; the buffer must not also receive a literal "v". Same for the
2821        // other common Cmd chords a user will hit over a focused editor.
2822        for (label, ch) in [("paste", 'v'), ("copy", 'c'), ("cut", 'x'), ("all", 'a')] {
2823            let mut ta = TextArea::new();
2824            let handled = ta.handle_event(&Event::Key(
2825                KeyEvent::new(KeyCode::Char(ch)).with_modifiers(Modifiers::SUPER),
2826            ));
2827            assert_eq!(ta.text(), "", "Cmd+{ch} ({label}) typed into the buffer");
2828            assert!(!handled, "Cmd+{ch} ({label}) should be left to the host");
2829        }
2830    }
2831
2832    #[test]
2833    fn key_release_does_not_type() {
2834        // Synthetic drivers (the demo's guided tour) send a press followed by a
2835        // release so key-latching screens unlatch. The release must be inert
2836        // here, or every driven keystroke would be typed twice.
2837        let mut ta = TextArea::new();
2838        let handled = ta.handle_event(&Event::Key(
2839            KeyEvent::new(KeyCode::Char('x')).with_kind(KeyEventKind::Release),
2840        ));
2841        assert!(!handled, "a key release should not be consumed as typing");
2842        assert_eq!(ta.text(), "");
2843    }
2844
2845    #[test]
2846    fn plain_and_shifted_characters_still_type() {
2847        let mut ta = TextArea::new();
2848        assert!(ta.handle_event(&Event::Key(KeyEvent::new(KeyCode::Char('v')))));
2849        assert!(ta.handle_event(&Event::Key(
2850            KeyEvent::new(KeyCode::Char('V')).with_modifiers(Modifiers::SHIFT),
2851        )));
2852        assert_eq!(ta.text(), "vV");
2853    }
2854
2855    #[test]
2856    fn paste_event_inserts_clipboard_text() {
2857        let mut ta = TextArea::new().with_text("ab");
2858        ta.move_to_document_end();
2859        assert!(ta.handle_event(&Event::Paste(ftui_core::event::PasteEvent::bracketed("cd"))));
2860        assert_eq!(ta.text(), "abcd");
2861    }
2862
2863    #[test]
2864    fn unicode_grapheme_cluster() {
2865        let mut ta = TextArea::new();
2866        ta.insert_text("café");
2867        // 'é' is a single grapheme even if composed
2868        assert_eq!(ta.text(), "café");
2869    }
2870
2871    mod proptests {
2872        use super::*;
2873        use proptest::prelude::*;
2874
2875        proptest! {
2876            #[test]
2877            fn insert_delete_inverse(text in "[a-zA-Z0-9 ]{1,50}") {
2878                let mut ta = TextArea::new();
2879                ta.insert_text(&text);
2880                // Delete all characters backwards
2881                for _ in 0..text.len() {
2882                    ta.delete_backward();
2883                }
2884                prop_assert!(ta.is_empty() || ta.text().is_empty());
2885            }
2886
2887            #[test]
2888            fn undo_redo_inverse(text in "[a-zA-Z0-9]{1,30}") {
2889                let mut ta = TextArea::new();
2890                ta.insert_text(&text);
2891                let after_insert = ta.text();
2892                ta.undo();
2893                ta.redo();
2894                prop_assert_eq!(ta.text(), after_insert);
2895            }
2896
2897            #[test]
2898            fn cursor_always_valid(ops in proptest::collection::vec(0u8..10, 1..20)) {
2899                let mut ta = TextArea::new().with_text("abc\ndef\nghi\njkl");
2900                for op in ops {
2901                    match op {
2902                        0 => ta.move_left(),
2903                        1 => ta.move_right(),
2904                        2 => ta.move_up(),
2905                        3 => ta.move_down(),
2906                        4 => ta.move_to_line_start(),
2907                        5 => ta.move_to_line_end(),
2908                        6 => ta.move_to_document_start(),
2909                        7 => ta.move_to_document_end(),
2910                        8 => ta.move_word_left(),
2911                        _ => ta.move_word_right(),
2912                    }
2913                    let cursor = ta.cursor();
2914                    prop_assert!(cursor.line < ta.line_count(),
2915                        "cursor line {} >= line_count {}", cursor.line, ta.line_count());
2916                }
2917            }
2918
2919            #[test]
2920            fn selection_ordered(n in 1usize..20) {
2921                let mut ta = TextArea::new().with_text("hello world foo bar");
2922                ta.move_to_document_start();
2923                for _ in 0..n {
2924                    ta.select_right();
2925                }
2926                if let Some(sel) = ta.selection() {
2927                    // When selecting right from start, anchor should be at/before head
2928                    prop_assert!(sel.anchor.line <= sel.head.line
2929                        || (sel.anchor.line == sel.head.line
2930                            && sel.anchor.grapheme <= sel.head.grapheme));
2931                }
2932            }
2933        }
2934    }
2935
2936    mod highlighter_tests {
2937        use super::*;
2938        use ftui_render::cell::{PackedRgba, StyleFlags};
2939        use ftui_render::frame::Frame;
2940        use ftui_render::grapheme_pool::GraphemePool;
2941        use proptest::prelude::*;
2942
2943        fn render(ta: &TextArea, w: u16, h: u16, mut f: impl FnMut(&Frame)) {
2944            let mut pool = GraphemePool::new();
2945            let mut frame = Frame::new(w, h, &mut pool);
2946            Widget::render(ta, Rect::new(0, 0, w, h), &mut frame);
2947            f(&frame);
2948        }
2949
2950        #[test]
2951        fn highlighter_receives_each_visible_line_once() {
2952            let seen = Arc::new(std::sync::Mutex::new(Vec::<usize>::new()));
2953            let recorder = seen.clone();
2954            let ta = TextArea::new()
2955                .with_text("one\ntwo\nthree")
2956                .with_highlighter(Arc::new(move |line, _text| {
2957                    recorder.lock().unwrap().push(line);
2958                    Vec::new()
2959                }));
2960            assert!(ta.has_highlighter());
2961            render(&ta, 20, 3, |_| {});
2962            let mut lines = seen.lock().unwrap().clone();
2963            lines.sort_unstable();
2964            assert_eq!(lines, vec![0, 1, 2]);
2965        }
2966
2967        #[test]
2968        fn highlighter_ranges_style_graphemes() {
2969            let ta = TextArea::new()
2970                .with_text("abcdef")
2971                .with_highlighter(Arc::new(|_l, _t| {
2972                    vec![(0..3, Style::new().fg(PackedRgba::RED))]
2973                }));
2974            render(&ta, 10, 1, |frame| {
2975                for x in 0..3 {
2976                    assert_eq!(
2977                        frame.buffer.get(x, 0).unwrap().fg,
2978                        PackedRgba::RED,
2979                        "col {x}"
2980                    );
2981                }
2982                assert_ne!(frame.buffer.get(3, 0).unwrap().fg, PackedRgba::RED);
2983            });
2984        }
2985
2986        #[test]
2987        fn out_of_range_and_non_boundary_ranges_ignored() {
2988            // "café": c(0) a(1) f(2) é(3..5); len 5. All three ranges are
2989            // invalid (past end / splits 'é' / inverted) and are dropped.
2990            let ta = TextArea::new()
2991                .with_text("café")
2992                .with_highlighter(Arc::new(|_l, _t| {
2993                    // Struct literal so clippy does not flag the reversed range.
2994                    let inverted = Range { start: 5, end: 2 };
2995                    vec![
2996                        (0..100, Style::new().fg(PackedRgba::RED)),
2997                        (3..4, Style::new().fg(PackedRgba::GREEN)),
2998                        (inverted, Style::new().fg(PackedRgba::BLUE)),
2999                    ]
3000                }));
3001            assert!(ta.line_spans(0, "café", true).is_empty());
3002            render(&ta, 10, 1, |_| {}); // no panic
3003        }
3004
3005        #[test]
3006        fn multibyte_ranges_align_to_graphemes() {
3007            // Highlight only the 2-byte 'é' (bytes 3..5).
3008            let ta = TextArea::new()
3009                .with_text("café")
3010                .with_highlighter(Arc::new(|_l, _t| {
3011                    vec![(3..5, Style::new().fg(PackedRgba::RED))]
3012                }));
3013            assert_eq!(ta.line_spans(0, "café", true).len(), 1);
3014            render(&ta, 10, 1, |frame| {
3015                assert_eq!(frame.buffer.get(3, 0).unwrap().fg, PackedRgba::RED, "'é'");
3016                assert_ne!(frame.buffer.get(0, 0).unwrap().fg, PackedRgba::RED, "'c'");
3017            });
3018        }
3019
3020        #[test]
3021        fn selection_style_merges_over_highlight() {
3022            let mut ta = TextArea::new()
3023                .with_text("abcdef")
3024                .with_focus(true)
3025                .with_selection_style(Style::new().bg(PackedRgba::GREEN))
3026                .with_highlighter(Arc::new(|_l, _t| {
3027                    vec![(0..6, Style::new().bg(PackedRgba::RED).fg(PackedRgba::WHITE))]
3028                }));
3029            ta.move_to_document_start();
3030            ta.select_right();
3031            ta.select_right();
3032            ta.select_right();
3033            render(&ta, 10, 1, |frame| {
3034                let selected = frame.buffer.get(0, 0).unwrap();
3035                assert_eq!(
3036                    selected.bg,
3037                    PackedRgba::GREEN,
3038                    "selection bg wins over highlight"
3039                );
3040                assert_eq!(selected.fg, PackedRgba::WHITE, "highlight fg preserved");
3041                let highlighted = frame.buffer.get(3, 0).unwrap();
3042                assert_eq!(
3043                    highlighted.bg,
3044                    PackedRgba::RED,
3045                    "unselected cell keeps highlight bg"
3046                );
3047            });
3048        }
3049
3050        #[test]
3051        fn soft_wrap_applies_highlight_on_continuation_rows() {
3052            // 10 chars wrapped at width 5 -> row 0 "abcde", row 1 "fghij"; the
3053            // whole-line highlight must reach the continuation row.
3054            let ta = TextArea::new()
3055                .with_text("abcdefghij")
3056                .with_soft_wrap(true)
3057                .with_highlighter(Arc::new(|_l, _t| {
3058                    vec![(0..10, Style::new().fg(PackedRgba::RED))]
3059                }));
3060            render(&ta, 5, 2, |frame| {
3061                assert_eq!(
3062                    frame.buffer.get(0, 0).unwrap().fg,
3063                    PackedRgba::RED,
3064                    "first row"
3065                );
3066                assert_eq!(
3067                    frame.buffer.get(0, 1).unwrap().fg,
3068                    PackedRgba::RED,
3069                    "continuation row highlighted"
3070                );
3071            });
3072        }
3073
3074        #[test]
3075        fn degraded_frame_ignores_highlight() {
3076            use ftui_render::budget::DegradationLevel;
3077
3078            let ta = TextArea::new()
3079                .with_text("abcdef")
3080                .with_highlighter(Arc::new(|_l, _t| {
3081                    vec![(0..3, Style::new().fg(PackedRgba::RED))]
3082                }));
3083            let mut pool = GraphemePool::new();
3084            let mut frame = Frame::new(10, 1, &mut pool);
3085            frame.buffer.degradation = DegradationLevel::NoStyling;
3086            Widget::render(&ta, Rect::new(0, 0, 10, 1), &mut frame);
3087            for x in 0..6 {
3088                assert_ne!(
3089                    frame.buffer.get(x, 0).unwrap().fg,
3090                    PackedRgba::RED,
3091                    "cell at x={x} must not have highlight fg under NoStyling"
3092                );
3093            }
3094        }
3095
3096        #[test]
3097        fn style_at_last_range_wins() {
3098            let style_a = Style::new().fg(PackedRgba::RED);
3099            let style_b = Style::new().fg(PackedRgba::BLUE);
3100            let spans = vec![(0..5, style_a), (2..4, style_b)];
3101            assert_eq!(style_at(&spans, 0), Some(style_a));
3102            assert_eq!(style_at(&spans, 1), Some(style_a));
3103            assert_eq!(style_at(&spans, 2), Some(style_b));
3104            assert_eq!(style_at(&spans, 3), Some(style_b));
3105            assert_eq!(style_at(&spans, 4), Some(style_a));
3106            assert_eq!(style_at(&spans, 5), None);
3107        }
3108
3109        #[test]
3110        fn cjk_and_emoji_multibyte_ranges_align_to_graphemes() {
3111            // "日本語 ok 🎉"
3112            // 日本 is bytes 0..6 (columns 0 and 2; each width 2)
3113            // 🎉 is bytes 13..17 (column 10; width 2)
3114            let text = "日本語 ok 🎉";
3115            let ta = TextArea::new()
3116                .with_text(text)
3117                .with_highlighter(Arc::new(|_l, _t| {
3118                    vec![
3119                        (0..6, Style::new().fg(PackedRgba::RED)),
3120                        (13..17, Style::new().fg(PackedRgba::BLUE)),
3121                    ]
3122                }));
3123            render(&ta, 20, 1, |frame| {
3124                // Both wide graphemes in 日本 received RED
3125                assert_eq!(
3126                    frame.buffer.get(0, 0).unwrap().fg,
3127                    PackedRgba::RED,
3128                    "日 at col 0"
3129                );
3130                assert_eq!(
3131                    frame.buffer.get(2, 0).unwrap().fg,
3132                    PackedRgba::RED,
3133                    "本 at col 2"
3134                );
3135
3136                // Unstyled graphemes 語 (col 4), ' ' (col 6), 'o' (col 7), 'k' (col 8), ' ' (col 9)
3137                for col in [4, 6, 7, 8, 9] {
3138                    assert_ne!(
3139                        frame.buffer.get(col, 0).unwrap().fg,
3140                        PackedRgba::RED,
3141                        "col {col} must not be red"
3142                    );
3143                    assert_ne!(
3144                        frame.buffer.get(col, 0).unwrap().fg,
3145                        PackedRgba::BLUE,
3146                        "col {col} must not be blue"
3147                    );
3148                }
3149
3150                // Emoji 🎉 covering bytes 13..17 styles the whole emoji at col 10
3151                assert_eq!(
3152                    frame.buffer.get(10, 0).unwrap().fg,
3153                    PackedRgba::BLUE,
3154                    "col 10 of 🎉 must be blue"
3155                );
3156            });
3157        }
3158
3159        fn toy_rust_highlighter(_line_idx: usize, line: &str) -> Vec<(Range<usize>, Style)> {
3160            let mut spans = Vec::new();
3161            let keyword_style = Style::new().bold();
3162            let string_style = Style::new().fg(PackedRgba::GREEN);
3163            let comment_style = Style::new().dim();
3164
3165            let code_part = if let Some(comment_pos) = line.find("//") {
3166                spans.push((comment_pos..line.len(), comment_style));
3167                &line[..comment_pos]
3168            } else {
3169                line
3170            };
3171
3172            let mut in_quote: Option<usize> = None;
3173            for (idx, ch) in code_part.char_indices() {
3174                if ch == '"' {
3175                    if let Some(start) = in_quote {
3176                        spans.push((start..idx + 1, string_style));
3177                        in_quote = None;
3178                    } else {
3179                        in_quote = Some(idx);
3180                    }
3181                }
3182            }
3183
3184            for kw in ["fn", "let"] {
3185                let mut search_from = 0;
3186                while let Some(pos) = code_part[search_from..].find(kw) {
3187                    let abs_pos = search_from + pos;
3188                    let end_pos = abs_pos + kw.len();
3189                    let prev_ok = abs_pos == 0
3190                        || !code_part[..abs_pos]
3191                            .chars()
3192                            .next_back()
3193                            .is_some_and(|c| c.is_alphanumeric() || c == '_');
3194                    let next_ok = end_pos == code_part.len()
3195                        || !code_part[end_pos..]
3196                            .chars()
3197                            .next()
3198                            .is_some_and(|c| c.is_alphanumeric() || c == '_');
3199                    let in_str = spans
3200                        .iter()
3201                        .any(|(r, s)| *s == string_style && r.contains(&abs_pos));
3202                    if prev_ok && next_ok && !in_str {
3203                        spans.push((abs_pos..end_pos, keyword_style));
3204                    }
3205                    search_from = end_pos;
3206                }
3207            }
3208
3209            spans.sort_by_key(|(r, _)| r.start);
3210            spans
3211        }
3212
3213        fn style_row_text(frame: &Frame, y: u16, width: u16) -> String {
3214            (0..width)
3215                .map(|x| {
3216                    let cell = frame.buffer.get(x, y).unwrap();
3217                    if cell.attrs.has_flag(StyleFlags::BOLD) {
3218                        'B'
3219                    } else if cell.fg == PackedRgba::GREEN {
3220                        'S'
3221                    } else if cell.attrs.has_flag(StyleFlags::DIM) {
3222                        'C'
3223                    } else {
3224                        '.'
3225                    }
3226                })
3227                .collect()
3228        }
3229
3230        #[test]
3231        fn textarea_highlighted_rust_60x8() {
3232            let snippet =
3233                "fn main() {\n    let name = \"ftui\"; // greet\n    println!(\"hi {name}\");\n}";
3234            let ta = TextArea::new()
3235                .with_text(snippet)
3236                .with_highlighter(Arc::new(toy_rust_highlighter));
3237
3238            render(&ta, 60, 8, |frame| {
3239                // Verify text content of lines
3240                assert_eq!(raw_row_text(frame, 0, 60), format!("{:<60}", "fn main() {"));
3241                assert_eq!(
3242                    raw_row_text(frame, 1, 60),
3243                    format!("{:<60}", "    let name = \"ftui\"; // greet")
3244                );
3245                assert_eq!(
3246                    raw_row_text(frame, 2, 60),
3247                    format!("{:<60}", "    println!(\"hi {name}\");")
3248                );
3249                assert_eq!(raw_row_text(frame, 3, 60), format!("{:<60}", "}"));
3250                for y in 4..8 {
3251                    assert_eq!(raw_row_text(frame, y, 60), " ".repeat(60));
3252                }
3253
3254                // Verify style masks
3255                // Row 0: fn (bold) main() {
3256                assert_eq!(
3257                    style_row_text(frame, 0, 60),
3258                    format!("BB{}", ".".repeat(58))
3259                );
3260                // Row 1: let (bold), "ftui" (string/green), // greet (dim/comment)
3261                assert_eq!(
3262                    style_row_text(frame, 1, 60),
3263                    format!("....BBB........SSSSSS..CCCCCCCC{}", ".".repeat(29))
3264                );
3265                // Row 2: "hi {name}" (string/green)
3266                assert_eq!(
3267                    style_row_text(frame, 2, 60),
3268                    format!(".............SSSSSSSSSSS..{}", ".".repeat(34))
3269                );
3270                // Row 3: }
3271                assert_eq!(style_row_text(frame, 3, 60), ".".repeat(60));
3272                // Rows 4..8: empty
3273                for y in 4..8 {
3274                    assert_eq!(style_row_text(frame, y, 60), ".".repeat(60));
3275                }
3276            });
3277        }
3278
3279        proptest! {
3280            #![proptest_config(ProptestConfig::with_cases(512))]
3281
3282            /// `style_at` returns the last covering range's style and never
3283            /// panics for any byte offset.
3284            #[test]
3285            fn style_at_returns_last_covering_range(
3286                bounds in prop::collection::vec((0usize..20, 0usize..20), 0..6),
3287                byte in 0usize..25,
3288            ) {
3289                let spans: Vec<(Range<usize>, Style)> = bounds
3290                    .iter()
3291                    .filter(|(a, b)| a < b)
3292                    .enumerate()
3293                    .map(|(i, (a, b))| (*a..*b, Style::new().fg(PackedRgba::rgb((i * 30) as u8, 1, 2))))
3294                    .collect();
3295                let expected = spans.iter().rev().find(|(r, _)| r.contains(&byte)).map(|(_, s)| *s);
3296                prop_assert_eq!(style_at(&spans, byte), expected);
3297            }
3298        }
3299    }
3300}