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;
17
18use ftui_core::event::{Event, KeyCode, KeyEvent, KeyEventKind, Modifiers};
19use ftui_core::geometry::Rect;
20use ftui_render::frame::Frame;
21use ftui_style::Style;
22use ftui_text::editor::{Editor, Selection};
23use ftui_text::wrap::display_width;
24use ftui_text::{CursorNavigator, CursorPosition};
25use unicode_segmentation::UnicodeSegmentation;
26
27use crate::{StatefulWidget, Widget, apply_style, clear_text_area, draw_text_span};
28
29/// Multi-line text editor widget.
30/// A per-line syntax style provider for [`TextArea::with_highlighter`].
31///
32/// Called once per visible logical line per render with `(line_index,
33/// line_text)`, where `line_text` has no trailing newline. It returns byte
34/// ranges into `line_text` paired with a [`Style`] to merge over the base
35/// style (before the selection style, so selection still wins). Ranges may
36/// overlap — a later range wins for a byte it covers. Ranges that fall outside
37/// the line or that do not sit on grapheme boundaries are ignored; an empty
38/// vector means "no highlight". The hook lives entirely in `ftui-widgets` and
39/// knows nothing about any tokenizer.
40pub type LineHighlighter = Arc<dyn Fn(usize, &str) -> Vec<(Range<usize>, Style)> + Send + Sync>;
41
42#[derive(Clone)]
43pub struct TextArea {
44    editor: Editor,
45    /// Placeholder text shown when empty.
46    placeholder: String,
47    /// Whether the widget has input focus.
48    focused: bool,
49    /// Show line numbers in gutter.
50    show_line_numbers: bool,
51    /// Base style.
52    style: Style,
53    /// Cursor line highlight style.
54    cursor_line_style: Option<Style>,
55    /// Selection highlight style.
56    selection_style: Style,
57    /// Placeholder style.
58    placeholder_style: Style,
59    /// Line number style.
60    line_number_style: Style,
61    /// Soft-wrap long lines.
62    ///
63    /// Visual wrapping preserves whitespace and breaks on word boundaries with
64    /// a grapheme fallback for long segments.
65    soft_wrap: bool,
66    /// Maximum height in lines (0 = unlimited / fill area).
67    max_height: usize,
68    /// Viewport scroll anchor (logical_line_idx, visual_wrap_offset).
69    ///
70    /// In soft-wrap mode, this tracks the first visible visual line.
71    /// In no-wrap mode, the second element is ignored (always 0).
72    scroll_anchor: std::cell::Cell<(usize, usize)>,
73    /// Horizontal scroll offset (visual columns).
74    scroll_left: std::cell::Cell<usize>,
75    /// Last viewport height for page movement and visibility checks.
76    #[allow(dead_code)]
77    last_viewport_height: std::cell::Cell<usize>,
78    /// Last viewport width for visibility checks.
79    last_viewport_width: std::cell::Cell<usize>,
80    /// Optional per-line syntax style provider (see [`LineHighlighter`]).
81    highlighter: Option<LineHighlighter>,
82}
83
84impl std::fmt::Debug for TextArea {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        f.debug_struct("TextArea")
87            .field("editor", &self.editor)
88            .field("placeholder", &self.placeholder)
89            .field("focused", &self.focused)
90            .field("show_line_numbers", &self.show_line_numbers)
91            .field("style", &self.style)
92            .field("cursor_line_style", &self.cursor_line_style)
93            .field("selection_style", &self.selection_style)
94            .field("placeholder_style", &self.placeholder_style)
95            .field("line_number_style", &self.line_number_style)
96            .field("soft_wrap", &self.soft_wrap)
97            .field("max_height", &self.max_height)
98            .field("scroll_anchor", &self.scroll_anchor)
99            .field("scroll_left", &self.scroll_left)
100            .field("last_viewport_height", &self.last_viewport_height)
101            .field("last_viewport_width", &self.last_viewport_width)
102            .field("highlighter", &self.highlighter.as_ref().map(|_| "<fn>"))
103            .finish()
104    }
105}
106
107/// The style of the last range in `spans` that covers `byte`, or `None`.
108///
109/// Ranges are byte ranges into a single line; a later range wins on overlap.
110/// Never panics: offsets outside every range simply return `None`.
111fn style_at(spans: &[(Range<usize>, Style)], byte: usize) -> Option<Style> {
112    spans
113        .iter()
114        .rev()
115        .find(|(range, _)| range.contains(&byte))
116        .map(|(_, style)| *style)
117}
118
119impl Default for TextArea {
120    fn default() -> Self {
121        Self::new()
122    }
123}
124
125/// Render state tracked across frames.
126#[derive(Debug, Clone, Default)]
127pub struct TextAreaState {
128    /// Viewport height from last render.
129    pub last_viewport_height: u16,
130    /// Viewport width from last render.
131    pub last_viewport_width: u16,
132}
133
134#[derive(Debug, Clone)]
135struct WrappedSlice<'a> {
136    text: &'a str,
137    start_byte: usize,
138    start_col: usize,
139    width: usize,
140}
141
142impl TextArea {
143    /// Create a new empty text area.
144    #[must_use]
145    pub fn new() -> Self {
146        Self {
147            editor: Editor::new(),
148            placeholder: String::new(),
149            focused: false,
150            show_line_numbers: false,
151            style: Style::default(),
152            cursor_line_style: None,
153            selection_style: Style::new().reverse(),
154            placeholder_style: Style::new().dim(),
155            line_number_style: Style::new().dim(),
156            soft_wrap: false,
157            max_height: 0,
158            scroll_anchor: std::cell::Cell::new((usize::MAX, 0)), // sentinel
159            scroll_left: std::cell::Cell::new(0),
160            last_viewport_height: std::cell::Cell::new(0),
161            last_viewport_width: std::cell::Cell::new(0),
162            highlighter: None,
163        }
164    }
165
166    // ── Event Handling ─────────────────────────────────────────────
167
168    /// Handle a terminal event.
169    ///
170    /// Returns `true` if the state changed.
171    pub fn handle_event(&mut self, event: &Event) -> bool {
172        match event {
173            Event::Key(key)
174                if key.kind == KeyEventKind::Press || key.kind == KeyEventKind::Repeat =>
175            {
176                self.handle_key(key)
177            }
178            Event::Paste(paste) => {
179                self.insert_text(&paste.text);
180                true
181            }
182            _ => false,
183        }
184    }
185
186    fn handle_key(&mut self, key: &KeyEvent) -> bool {
187        let ctrl = key.modifiers.contains(Modifiers::CTRL);
188        let shift = key.modifiers.contains(Modifiers::SHIFT);
189        let _alt = key.modifiers.contains(Modifiers::ALT);
190
191        match key.code {
192            KeyCode::Char(c) if !ctrl => {
193                self.insert_char(c);
194                true
195            }
196            KeyCode::Enter => {
197                self.insert_newline();
198                true
199            }
200            KeyCode::Backspace => {
201                if ctrl {
202                    self.delete_word_backward();
203                } else {
204                    self.delete_backward();
205                }
206                true
207            }
208            KeyCode::Delete => {
209                if ctrl {
210                    self.delete_word_forward();
211                } else {
212                    self.delete_forward();
213                }
214                true
215            }
216            KeyCode::Left => {
217                if ctrl && shift {
218                    self.select_word_left();
219                } else if ctrl {
220                    self.move_word_left();
221                } else if shift {
222                    self.select_left();
223                } else {
224                    self.move_left();
225                }
226                true
227            }
228            KeyCode::Right => {
229                if ctrl && shift {
230                    self.select_word_right();
231                } else if ctrl {
232                    self.move_word_right();
233                } else if shift {
234                    self.select_right();
235                } else {
236                    self.move_right();
237                }
238                true
239            }
240            KeyCode::Up => {
241                if shift {
242                    self.select_up();
243                } else {
244                    self.move_up();
245                }
246                true
247            }
248            KeyCode::Down => {
249                if shift {
250                    self.select_down();
251                } else {
252                    self.move_down();
253                }
254                true
255            }
256            KeyCode::Home => {
257                self.move_to_line_start();
258                true
259            }
260            KeyCode::End => {
261                self.move_to_line_end();
262                true
263            }
264            KeyCode::PageUp => {
265                let page = self.last_viewport_height.get().max(1);
266                if self.soft_wrap {
267                    self.move_cursor_visual_up(page, shift);
268                } else {
269                    for _ in 0..page {
270                        if shift {
271                            self.editor.select_up();
272                        } else {
273                            self.editor.move_up();
274                        }
275                    }
276                }
277                self.ensure_cursor_visible();
278                true
279            }
280            KeyCode::PageDown => {
281                let page = self.last_viewport_height.get().max(1);
282                if self.soft_wrap {
283                    self.move_cursor_visual_down(page, shift);
284                } else {
285                    for _ in 0..page {
286                        if shift {
287                            self.editor.select_down();
288                        } else {
289                            self.editor.move_down();
290                        }
291                    }
292                }
293                self.ensure_cursor_visible();
294                true
295            }
296            KeyCode::Char('a') if ctrl => {
297                self.select_all();
298                true
299            }
300            // Ctrl+K: Delete to end of line (common emacs/shell binding)
301            KeyCode::Char('k') if ctrl => {
302                self.delete_to_end_of_line();
303                true
304            }
305            // Ctrl+Z: Undo
306            KeyCode::Char('z') if ctrl => {
307                self.undo();
308                true
309            }
310            // Ctrl+Y: Redo
311            KeyCode::Char('y') if ctrl => {
312                self.redo();
313                true
314            }
315            _ => false,
316        }
317    }
318
319    // ── Builder methods ────────────────────────────────────────────
320
321    /// Set initial text content (builder).
322    #[must_use]
323    pub fn with_text(mut self, text: &str) -> Self {
324        self.editor = Editor::with_text(text);
325        self.editor.move_to_document_start();
326        self
327    }
328
329    /// Set placeholder text (builder).
330    #[must_use]
331    pub fn with_placeholder(mut self, text: impl Into<String>) -> Self {
332        self.placeholder = text.into();
333        self
334    }
335
336    /// Set focused state (builder).
337    #[must_use]
338    pub fn with_focus(mut self, focused: bool) -> Self {
339        self.focused = focused;
340        self
341    }
342
343    /// Enable line numbers (builder).
344    #[must_use]
345    pub fn with_line_numbers(mut self, show: bool) -> Self {
346        self.show_line_numbers = show;
347        self
348    }
349
350    /// Install a per-line syntax style provider (builder). See
351    /// [`LineHighlighter`].
352    #[must_use]
353    pub fn with_highlighter(mut self, highlighter: LineHighlighter) -> Self {
354        self.highlighter = Some(highlighter);
355        self
356    }
357
358    /// Set or clear the per-line syntax style provider.
359    pub fn set_highlighter(&mut self, highlighter: Option<LineHighlighter>) {
360        self.highlighter = highlighter;
361    }
362
363    /// Whether a syntax highlighter is installed.
364    #[must_use]
365    pub fn has_highlighter(&self) -> bool {
366        self.highlighter.is_some()
367    }
368
369    /// The highlight spans for one line, or empty when there is no highlighter
370    /// or styling is disabled. Ranges that don't sit on grapheme boundaries of
371    /// `line_text` are dropped so partial-grapheme styling can't occur.
372    fn line_spans(
373        &self,
374        line_idx: usize,
375        line_text: &str,
376        styling: bool,
377    ) -> Vec<(Range<usize>, Style)> {
378        if !styling {
379            return Vec::new();
380        }
381        let Some(highlighter) = self.highlighter.as_ref() else {
382            return Vec::new();
383        };
384        highlighter(line_idx, line_text)
385            .into_iter()
386            .filter(|(range, _)| {
387                range.start < range.end
388                    && range.end <= line_text.len()
389                    && line_text.is_char_boundary(range.start)
390                    && line_text.is_char_boundary(range.end)
391            })
392            .collect()
393    }
394
395    /// Set base style (builder).
396    #[must_use]
397    pub fn with_style(mut self, style: Style) -> Self {
398        self.style = style;
399        self
400    }
401
402    /// Set cursor line highlight style (builder).
403    #[must_use]
404    pub fn with_cursor_line_style(mut self, style: Style) -> Self {
405        self.cursor_line_style = Some(style);
406        self
407    }
408
409    /// Set selection style (builder).
410    #[must_use]
411    pub fn with_selection_style(mut self, style: Style) -> Self {
412        self.selection_style = style;
413        self
414    }
415
416    /// Enable soft wrapping (builder).
417    #[must_use]
418    pub fn with_soft_wrap(mut self, wrap: bool) -> Self {
419        self.soft_wrap = wrap;
420        self
421    }
422
423    /// Set maximum height in lines (builder). 0 = fill available area.
424    #[must_use]
425    pub fn with_max_height(mut self, max: usize) -> Self {
426        self.max_height = max;
427        self
428    }
429
430    // ── State access ───────────────────────────────────────────────
431
432    /// Get the full text content.
433    #[must_use]
434    pub fn text(&self) -> String {
435        self.editor.text()
436    }
437
438    /// Set the full text content (resets cursor and undo history).
439    pub fn set_text(&mut self, text: &str) {
440        self.editor.set_text(text);
441        self.scroll_anchor.set((0, 0));
442        self.scroll_left.set(0);
443    }
444
445    /// Number of lines.
446    #[must_use]
447    pub fn line_count(&self) -> usize {
448        self.editor.line_count()
449    }
450
451    /// Current cursor position.
452    #[inline]
453    #[must_use]
454    pub fn cursor(&self) -> CursorPosition {
455        self.editor.cursor()
456    }
457
458    /// Set cursor position (clamped to bounds). Clears selection.
459    pub fn set_cursor_position(&mut self, pos: CursorPosition) {
460        self.editor.set_cursor(pos);
461        self.ensure_cursor_visible();
462    }
463
464    /// Whether the textarea is empty.
465    #[inline]
466    #[must_use]
467    pub fn is_empty(&self) -> bool {
468        self.editor.is_empty()
469    }
470
471    /// Current selection, if any.
472    #[must_use = "use the returned selection (if any)"]
473    pub fn selection(&self) -> Option<Selection> {
474        self.editor.selection()
475    }
476
477    /// Get selected text.
478    #[must_use = "use the returned selected text (if any)"]
479    pub fn selected_text(&self) -> Option<String> {
480        self.editor.selected_text()
481    }
482
483    /// Whether the widget has focus.
484    #[must_use]
485    pub fn is_focused(&self) -> bool {
486        self.focused
487    }
488
489    /// Set focus state.
490    pub fn set_focused(&mut self, focused: bool) {
491        self.focused = focused;
492    }
493
494    /// Access the underlying editor.
495    #[must_use]
496    pub fn editor(&self) -> &Editor {
497        &self.editor
498    }
499
500    /// Mutable access to the underlying editor.
501    pub fn editor_mut(&mut self) -> &mut Editor {
502        &mut self.editor
503    }
504
505    // ── Editing operations (delegated to Editor) ───────────────────
506
507    /// Insert text at cursor.
508    pub fn insert_text(&mut self, text: &str) {
509        self.editor.insert_text(text);
510        self.ensure_cursor_visible();
511    }
512
513    /// Insert a single character.
514    pub fn insert_char(&mut self, ch: char) {
515        self.editor.insert_char(ch);
516        self.ensure_cursor_visible();
517    }
518
519    /// Insert a newline.
520    pub fn insert_newline(&mut self) {
521        self.editor.insert_newline();
522        self.ensure_cursor_visible();
523    }
524
525    /// Delete backward (backspace).
526    pub fn delete_backward(&mut self) {
527        self.editor.delete_backward();
528        self.ensure_cursor_visible();
529    }
530
531    /// Delete forward (delete key).
532    pub fn delete_forward(&mut self) {
533        self.editor.delete_forward();
534        self.ensure_cursor_visible();
535    }
536
537    /// Delete word backward (Ctrl+Backspace).
538    pub fn delete_word_backward(&mut self) {
539        self.editor.delete_word_backward();
540        self.ensure_cursor_visible();
541    }
542
543    /// Delete word forward (Ctrl+Delete).
544    pub fn delete_word_forward(&mut self) {
545        self.editor.delete_word_forward();
546        self.ensure_cursor_visible();
547    }
548
549    /// Delete to end of line (Ctrl+K).
550    pub fn delete_to_end_of_line(&mut self) {
551        self.editor.delete_to_end_of_line();
552        self.ensure_cursor_visible();
553    }
554
555    /// Undo last edit.
556    pub fn undo(&mut self) {
557        self.editor.undo();
558        self.ensure_cursor_visible();
559    }
560
561    /// Redo last undo.
562    pub fn redo(&mut self) {
563        self.editor.redo();
564        self.ensure_cursor_visible();
565    }
566
567    // ── Navigation ─────────────────────────────────────────────────
568
569    /// Move cursor left.
570    pub fn move_left(&mut self) {
571        self.editor.move_left();
572        self.ensure_cursor_visible();
573    }
574
575    /// Move cursor right.
576    pub fn move_right(&mut self) {
577        self.editor.move_right();
578        self.ensure_cursor_visible();
579    }
580
581    /// Move cursor up.
582    pub fn move_up(&mut self) {
583        if self.soft_wrap {
584            self.move_cursor_visual_up(1, false);
585        } else {
586            self.editor.move_up();
587        }
588        self.ensure_cursor_visible();
589    }
590
591    /// Move cursor down.
592    pub fn move_down(&mut self) {
593        if self.soft_wrap {
594            self.move_cursor_visual_down(1, false);
595        } else {
596            self.editor.move_down();
597        }
598        self.ensure_cursor_visible();
599    }
600
601    /// Move cursor left by word.
602    pub fn move_word_left(&mut self) {
603        self.editor.move_word_left();
604        self.ensure_cursor_visible();
605    }
606
607    /// Move cursor right by word.
608    pub fn move_word_right(&mut self) {
609        self.editor.move_word_right();
610        self.ensure_cursor_visible();
611    }
612
613    /// Extend selection left by word.
614    pub fn select_word_left(&mut self) {
615        self.editor.select_word_left();
616        self.ensure_cursor_visible();
617    }
618
619    /// Extend selection right by word.
620    pub fn select_word_right(&mut self) {
621        self.editor.select_word_right();
622        self.ensure_cursor_visible();
623    }
624
625    /// Move to start of line.
626    pub fn move_to_line_start(&mut self) {
627        self.editor.move_to_line_start();
628        self.ensure_cursor_visible();
629    }
630
631    /// Move to end of line.
632    pub fn move_to_line_end(&mut self) {
633        self.editor.move_to_line_end();
634        self.ensure_cursor_visible();
635    }
636
637    /// Move to start of document.
638    pub fn move_to_document_start(&mut self) {
639        self.editor.move_to_document_start();
640        self.ensure_cursor_visible();
641    }
642
643    /// Move cursor to end of document.
644    pub fn move_to_document_end(&mut self) {
645        self.editor.move_to_document_end();
646        self.ensure_cursor_visible();
647    }
648
649    fn move_cursor_visual_down(&mut self, count: usize, extend_selection: bool) {
650        let width = self.last_viewport_width.get();
651        if width == 0 {
652            for _ in 0..count {
653                if extend_selection {
654                    self.editor.select_down();
655                } else {
656                    self.editor.move_down();
657                }
658            }
659            return;
660        }
661
662        let rope = self.editor.rope();
663        let mut cursor = self.editor.cursor();
664        let mut remaining = count;
665
666        let line_text = rope
667            .line(cursor.line)
668            .unwrap_or(std::borrow::Cow::Borrowed(""));
669        let line_text = line_text.trim_end_matches(['\n', '\r']);
670        let (mut current_v_row, _) =
671            Self::cursor_wrap_position(line_text, width, cursor.visual_col);
672
673        // Calculate target screen X (relative to slice start) to preserve column
674        let initial_slices = Self::wrap_line_slices(line_text, width);
675        let initial_slice_start = initial_slices
676            .get(current_v_row)
677            .map(|s| s.start_col)
678            .unwrap_or(0);
679        let target_screen_x = cursor.visual_col.saturating_sub(initial_slice_start);
680
681        while remaining > 0 {
682            let line_text = rope
683                .line(cursor.line)
684                .unwrap_or(std::borrow::Cow::Borrowed(""));
685            let line_text = line_text.trim_end_matches(['\n', '\r']);
686            let wrap_count = Self::measure_wrap_count(line_text, width);
687
688            let available_in_line = wrap_count.saturating_sub(1).saturating_sub(current_v_row);
689
690            if remaining <= available_in_line {
691                current_v_row += remaining;
692                remaining = 0;
693            } else {
694                remaining -= available_in_line + 1;
695                if cursor.line + 1 < self.editor.line_count() {
696                    cursor.line += 1;
697                    current_v_row = 0;
698                } else {
699                    current_v_row = wrap_count.saturating_sub(1);
700                    remaining = 0;
701                }
702            }
703        }
704
705        let line_text = rope
706            .line(cursor.line)
707            .unwrap_or(std::borrow::Cow::Borrowed(""));
708        let line_text = line_text.trim_end_matches(['\n', '\r']);
709        let slices = Self::wrap_line_slices(line_text, width);
710
711        if let Some(slice) = slices.get(current_v_row) {
712            let target_in_slice = target_screen_x.min(slice.width);
713
714            let mut g_idx = 0;
715            let mut v_w = 0;
716            for g in slice.text.graphemes(true) {
717                let w = display_width(g);
718                if v_w + w > target_in_slice {
719                    break;
720                }
721                v_w += w;
722                g_idx += 1;
723            }
724
725            let nav = CursorNavigator::new(rope);
726            let line_start_byte = nav.to_byte_index(nav.from_line_grapheme(cursor.line, 0));
727            let slice_byte_offset: usize = slice
728                .text
729                .graphemes(true)
730                .take(g_idx)
731                .map(|g| g.len())
732                .sum();
733            let final_byte = line_start_byte + slice.start_byte + slice_byte_offset;
734            cursor = nav.from_byte_index(final_byte);
735        }
736
737        if extend_selection {
738            self.editor.extend_selection_to(cursor);
739        } else {
740            self.editor.set_cursor(cursor);
741        }
742    }
743
744    fn move_cursor_visual_up(&mut self, count: usize, extend_selection: bool) {
745        let width = self.last_viewport_width.get();
746        if width == 0 {
747            for _ in 0..count {
748                if extend_selection {
749                    self.editor.select_up();
750                } else {
751                    self.editor.move_up();
752                }
753            }
754            return;
755        }
756
757        let rope = self.editor.rope();
758        let mut cursor = self.editor.cursor();
759        let mut remaining = count;
760
761        let line_text = rope
762            .line(cursor.line)
763            .unwrap_or(std::borrow::Cow::Borrowed(""));
764        let line_text = line_text.trim_end_matches(['\n', '\r']);
765        let (mut current_v_row, _) =
766            Self::cursor_wrap_position(line_text, width, cursor.visual_col);
767
768        // Calculate target screen X (relative to slice start) to preserve column
769        let initial_slices = Self::wrap_line_slices(line_text, width);
770        let initial_slice_start = initial_slices
771            .get(current_v_row)
772            .map(|s| s.start_col)
773            .unwrap_or(0);
774        let target_screen_x = cursor.visual_col.saturating_sub(initial_slice_start);
775
776        while remaining > 0 {
777            if remaining <= current_v_row {
778                current_v_row -= remaining;
779                remaining = 0;
780            } else {
781                remaining -= current_v_row + 1;
782                if cursor.line > 0 {
783                    cursor.line -= 1;
784                    let line_text = rope
785                        .line(cursor.line)
786                        .unwrap_or(std::borrow::Cow::Borrowed(""));
787                    let line_text = line_text.trim_end_matches(['\n', '\r']);
788                    let wrap_count = Self::measure_wrap_count(line_text, width);
789                    current_v_row = wrap_count.saturating_sub(1);
790                } else {
791                    current_v_row = 0;
792                    remaining = 0;
793                }
794            }
795        }
796
797        let line_text = rope
798            .line(cursor.line)
799            .unwrap_or(std::borrow::Cow::Borrowed(""));
800        let line_text = line_text.trim_end_matches(['\n', '\r']);
801        let slices = Self::wrap_line_slices(line_text, width);
802
803        if let Some(slice) = slices.get(current_v_row) {
804            let target_in_slice = target_screen_x.min(slice.width);
805
806            let mut g_idx = 0;
807            let mut v_w = 0;
808            for g in slice.text.graphemes(true) {
809                let w = display_width(g);
810                if v_w + w > target_in_slice {
811                    break;
812                }
813                v_w += w;
814                g_idx += 1;
815            }
816
817            let nav = CursorNavigator::new(rope);
818            let line_start_byte = nav.to_byte_index(nav.from_line_grapheme(cursor.line, 0));
819            let slice_byte_offset: usize = slice
820                .text
821                .graphemes(true)
822                .take(g_idx)
823                .map(|g| g.len())
824                .sum();
825            let final_byte = line_start_byte + slice.start_byte + slice_byte_offset;
826            cursor = nav.from_byte_index(final_byte);
827        }
828
829        if extend_selection {
830            self.editor.extend_selection_to(cursor);
831        } else {
832            self.editor.set_cursor(cursor);
833        }
834    }
835
836    // ── Selection ──────────────────────────────────────────────────
837
838    /// Extend selection left.
839    pub fn select_left(&mut self) {
840        self.editor.select_left();
841        self.ensure_cursor_visible();
842    }
843
844    /// Extend selection right.
845    pub fn select_right(&mut self) {
846        self.editor.select_right();
847        self.ensure_cursor_visible();
848    }
849
850    /// Extend selection up.
851    pub fn select_up(&mut self) {
852        if self.soft_wrap {
853            self.move_cursor_visual_up(1, true);
854        } else {
855            self.editor.select_up();
856        }
857        self.ensure_cursor_visible();
858    }
859
860    /// Extend selection down.
861    pub fn select_down(&mut self) {
862        if self.soft_wrap {
863            self.move_cursor_visual_down(1, true);
864        } else {
865            self.editor.select_down();
866        }
867        self.ensure_cursor_visible();
868    }
869
870    /// Select all.
871    pub fn select_all(&mut self) {
872        self.editor.select_all();
873    }
874
875    /// Clear selection.
876    pub fn clear_selection(&mut self) {
877        self.editor.clear_selection();
878    }
879
880    // ── Viewport management ────────────────────────────────────────
881
882    /// Page up (move viewport and cursor up by viewport height).
883    pub fn page_up(&mut self, state: &TextAreaState) {
884        let page = state.last_viewport_height.max(1) as usize;
885        let text_area_width = state
886            .last_viewport_width
887            .saturating_sub(self.gutter_width());
888        self.last_viewport_height.set(page);
889        self.last_viewport_width.set(text_area_width as usize);
890        if self.soft_wrap {
891            if text_area_width > 0 {
892                self.move_cursor_visual_up(page, false);
893            } else {
894                for _ in 0..page {
895                    self.editor.move_up();
896                }
897            }
898        } else {
899            for _ in 0..page {
900                self.editor.move_up();
901            }
902        }
903        self.ensure_cursor_visible();
904    }
905
906    /// Page down (move viewport and cursor down by viewport height).
907    pub fn page_down(&mut self, state: &TextAreaState) {
908        let page = state.last_viewport_height.max(1) as usize;
909        let text_area_width = state
910            .last_viewport_width
911            .saturating_sub(self.gutter_width());
912        self.last_viewport_height.set(page);
913        self.last_viewport_width.set(text_area_width as usize);
914        if self.soft_wrap {
915            if text_area_width > 0 {
916                self.move_cursor_visual_down(page, false);
917            } else {
918                for _ in 0..page {
919                    self.editor.move_down();
920                }
921            }
922        } else {
923            for _ in 0..page {
924                self.editor.move_down();
925            }
926        }
927        self.ensure_cursor_visible();
928    }
929
930    /// Width of the line number gutter.
931    fn gutter_width(&self) -> u16 {
932        if !self.show_line_numbers {
933            return 0;
934        }
935        let digits = {
936            let mut count = self.line_count().max(1);
937            let mut d: u16 = 0;
938            while count > 0 {
939                d += 1;
940                count /= 10;
941            }
942            d
943        };
944        digits + 2 // digit width + space + separator
945    }
946
947    /// Count how many wrapped lines this text will occupy.
948    ///
949    /// This is a zero-allocation version of `wrap_line_slices` for layout calculations.
950    fn measure_wrap_count(line_text: &str, max_width: usize) -> usize {
951        if line_text.is_empty() {
952            return 1;
953        }
954
955        let mut count = 0;
956        let mut current_width = 0;
957        let mut has_content = false;
958
959        Self::run_wrapping_logic(line_text, max_width, |_, width, flush| {
960            if flush {
961                if width > 0 {
962                    count += 1;
963                }
964                current_width = 0;
965                has_content = false;
966            } else {
967                current_width = width;
968                has_content = true;
969            }
970        });
971
972        // If there's pending content or if we flushed but started a new empty line (which shouldn't happen with this logic usually,
973        // but let's be safe), count the last line.
974        // Actually run_wrapping_logic only flushes when a line is full.
975        // We need to count the current line if it has content or if it's the only line.
976        if has_content || count == 0 {
977            count += 1;
978        }
979
980        count
981    }
982
983    /// Core wrapping logic that emits events for layout or slicing.
984    ///
985    /// The callback receives `(start_index, width, flush)`.
986    /// - `flush == true`: The current line is full/done. `width` is the width of the flushed line.
987    /// - `flush == false`: Update current line width.
988    fn run_wrapping_logic<F>(line_text: &str, max_width: usize, mut callback: F)
989    where
990        F: FnMut(usize, usize, bool),
991    {
992        let mut current_width = 0;
993        let mut byte_cursor = 0;
994
995        for segment in line_text.split_word_bounds() {
996            let seg_len = segment.len();
997            let seg_width: usize = segment.graphemes(true).map(display_width).sum();
998
999            if max_width > 0 && current_width + seg_width > max_width {
1000                // Flush current
1001                callback(byte_cursor, current_width, true);
1002                current_width = 0;
1003            }
1004
1005            if max_width > 0 && seg_width > max_width {
1006                for grapheme in segment.graphemes(true) {
1007                    let g_width = display_width(grapheme);
1008                    let g_len = grapheme.len();
1009
1010                    if max_width > 0 && current_width + g_width > max_width && current_width > 0 {
1011                        callback(byte_cursor, current_width, true);
1012                        current_width = 0;
1013                    }
1014
1015                    current_width += g_width;
1016                    byte_cursor += g_len;
1017                    callback(byte_cursor, current_width, false);
1018                }
1019                continue;
1020            }
1021
1022            current_width += seg_width;
1023            byte_cursor += seg_len;
1024            callback(byte_cursor, current_width, false);
1025        }
1026    }
1027
1028    fn wrap_line_slices<'a>(line_text: &'a str, max_width: usize) -> Vec<WrappedSlice<'a>> {
1029        if line_text.is_empty() {
1030            return vec![WrappedSlice {
1031                text: "",
1032                start_byte: 0,
1033                start_col: 0,
1034                width: 0,
1035            }];
1036        }
1037
1038        let mut slices = Vec::new();
1039        let mut current_width = 0;
1040        let mut slice_start_byte = 0;
1041        let mut slice_start_col = 0;
1042        let mut byte_cursor = 0;
1043        let mut col_cursor = 0;
1044
1045        let push_current = |slices: &mut Vec<WrappedSlice<'a>>,
1046                            width: &mut usize,
1047                            start_byte: &mut usize,
1048                            start_col: &mut usize,
1049                            byte_cursor: usize,
1050                            col_cursor: usize| {
1051            if byte_cursor == *start_byte && *width == 0 {
1052                return;
1053            }
1054            slices.push(WrappedSlice {
1055                text: &line_text[*start_byte..byte_cursor],
1056                start_byte: *start_byte,
1057                start_col: *start_col,
1058                width: *width,
1059            });
1060            *start_byte = byte_cursor;
1061            *start_col = col_cursor;
1062            *width = 0;
1063        };
1064
1065        for segment in line_text.split_word_bounds() {
1066            let seg_len = segment.len();
1067            let seg_width: usize = segment.graphemes(true).map(display_width).sum();
1068
1069            if max_width > 0 && current_width + seg_width > max_width {
1070                push_current(
1071                    &mut slices,
1072                    &mut current_width,
1073                    &mut slice_start_byte,
1074                    &mut slice_start_col,
1075                    byte_cursor,
1076                    col_cursor,
1077                );
1078            }
1079
1080            if max_width > 0 && seg_width > max_width {
1081                for grapheme in segment.graphemes(true) {
1082                    let g_width = display_width(grapheme);
1083                    let g_len = grapheme.len();
1084
1085                    if max_width > 0 && current_width + g_width > max_width && current_width > 0 {
1086                        push_current(
1087                            &mut slices,
1088                            &mut current_width,
1089                            &mut slice_start_byte,
1090                            &mut slice_start_col,
1091                            byte_cursor,
1092                            col_cursor,
1093                        );
1094                    }
1095
1096                    current_width += g_width;
1097                    byte_cursor += g_len;
1098                    col_cursor += g_width;
1099                }
1100                continue;
1101            }
1102
1103            current_width += seg_width;
1104            byte_cursor += seg_len;
1105            col_cursor += seg_width;
1106        }
1107
1108        if byte_cursor > slice_start_byte || current_width > 0 || slices.is_empty() {
1109            slices.push(WrappedSlice {
1110                text: &line_text[slice_start_byte..byte_cursor],
1111                start_byte: slice_start_byte,
1112                start_col: slice_start_col,
1113                width: current_width,
1114            });
1115        }
1116
1117        slices
1118    }
1119
1120    fn cursor_wrap_position(
1121        line_text: &str,
1122        max_width: usize,
1123        cursor_col: usize,
1124    ) -> (usize, usize) {
1125        let slices = Self::wrap_line_slices(line_text, max_width);
1126        if slices.is_empty() {
1127            return (0, 0);
1128        }
1129
1130        for (idx, slice) in slices.iter().enumerate() {
1131            let end_col = slice.start_col.saturating_add(slice.width);
1132            // If cursor is at the wrap boundary (equal to end_col), we prefer the start
1133            // of the *next* slice (by skipping this one) unless this is the last slice.
1134            let is_last = idx == slices.len().saturating_sub(1);
1135            if cursor_col < end_col || (cursor_col == end_col && is_last) {
1136                let col_in_slice = cursor_col.saturating_sub(slice.start_col);
1137                return (idx, col_in_slice.min(slice.width));
1138            }
1139        }
1140
1141        (0, 0)
1142    }
1143
1144    /// Get the visual width of the character immediately before the cursor.
1145    fn get_prev_char_width(&self) -> usize {
1146        let cursor = self.editor.cursor();
1147        if cursor.grapheme == 0 {
1148            return 0;
1149        }
1150        let rope = self.editor.rope();
1151        let line = rope
1152            .line(cursor.line)
1153            .unwrap_or(std::borrow::Cow::Borrowed(""));
1154
1155        line.graphemes(true)
1156            .nth(cursor.grapheme - 1)
1157            .map(display_width)
1158            .unwrap_or(0)
1159    }
1160
1161    /// Ensure the cursor line and column are visible in the viewport.
1162    fn ensure_cursor_visible(&self) {
1163        let cursor = self.editor.cursor();
1164
1165        let last_height = self.last_viewport_height.get();
1166        let vp_height = if last_height == 0 { 20 } else { last_height };
1167
1168        let last_width = self.last_viewport_width.get();
1169        let vp_width = if last_width == 0 { 80 } else { last_width };
1170
1171        if self.scroll_anchor.get().0 == usize::MAX {
1172            self.scroll_anchor.set((0, 0));
1173        }
1174
1175        self.ensure_cursor_visible_internal(vp_height, vp_width, cursor);
1176    }
1177
1178    fn ensure_cursor_visible_internal(
1179        &self,
1180        vp_height: usize,
1181        vp_width: usize,
1182        cursor: CursorPosition,
1183    ) {
1184        let (anchor_line, anchor_vrow) = self.scroll_anchor.get();
1185
1186        if !self.soft_wrap {
1187            // Vertical scroll (logical lines)
1188            if cursor.line < anchor_line {
1189                self.scroll_anchor.set((cursor.line, 0));
1190            } else if vp_height > 0 && cursor.line >= anchor_line + vp_height {
1191                self.scroll_anchor
1192                    .set((cursor.line.saturating_sub(vp_height - 1), 0));
1193            }
1194
1195            // Horizontal scroll
1196            let current_left = self.scroll_left.get();
1197            let visual_col = cursor.visual_col;
1198
1199            if visual_col < current_left {
1200                self.scroll_left.set(visual_col);
1201            } else if vp_width > 0 && visual_col >= current_left + vp_width {
1202                let candidate_scroll = visual_col.saturating_sub(vp_width - 1);
1203                let prev_width = self.get_prev_char_width();
1204                let max_scroll_for_prev = visual_col.saturating_sub(prev_width);
1205
1206                let new_scroll = if vp_width > prev_width {
1207                    candidate_scroll.min(max_scroll_for_prev)
1208                } else {
1209                    candidate_scroll
1210                };
1211
1212                self.scroll_left.set(new_scroll);
1213            }
1214            return;
1215        }
1216
1217        // Soft wrap logic
1218        let rope = self.editor.rope();
1219
1220        // 1. Is cursor before anchor?
1221        if cursor.line < anchor_line {
1222            let line_text = rope
1223                .line(cursor.line)
1224                .unwrap_or(std::borrow::Cow::Borrowed(""));
1225            let line_text = line_text.trim_end_matches(['\n', '\r']);
1226            let (v_row, _) = Self::cursor_wrap_position(line_text, vp_width, cursor.visual_col);
1227            self.scroll_anchor.set((cursor.line, v_row));
1228            return;
1229        }
1230
1231        if cursor.line == anchor_line {
1232            let line_text = rope
1233                .line(cursor.line)
1234                .unwrap_or(std::borrow::Cow::Borrowed(""));
1235            let line_text = line_text.trim_end_matches(['\n', '\r']);
1236            let (v_row, _) = Self::cursor_wrap_position(line_text, vp_width, cursor.visual_col);
1237            if v_row < anchor_vrow {
1238                self.scroll_anchor.set((cursor.line, v_row));
1239                return;
1240            }
1241        }
1242
1243        // 2. Is cursor after viewport? Trace forward from anchor.
1244        let mut visual_rows_capacity = vp_height;
1245        let mut current_line = anchor_line;
1246        let mut current_v_start = anchor_vrow;
1247
1248        loop {
1249            if current_line > cursor.line {
1250                // Reached past cursor line without exhausting capacity -> Visible.
1251                return;
1252            }
1253
1254            let line_text = rope
1255                .line(current_line)
1256                .unwrap_or(std::borrow::Cow::Borrowed(""));
1257            let line_text = line_text.trim_end_matches(['\n', '\r']);
1258            let wrap_count = Self::measure_wrap_count(line_text, vp_width);
1259
1260            if current_line == cursor.line {
1261                let (cursor_v_row, _) =
1262                    Self::cursor_wrap_position(line_text, vp_width, cursor.visual_col);
1263                if cursor_v_row >= current_v_start {
1264                    let displayed_row_index = cursor_v_row - current_v_start;
1265                    if displayed_row_index < visual_rows_capacity {
1266                        // Visible.
1267                        return;
1268                    } else {
1269                        // Not visible (below).
1270                        break;
1271                    }
1272                } else {
1273                    // Cursor is before the anchor start? Handled by step 1.
1274                    return;
1275                }
1276            }
1277
1278            let rows_remaining_in_line = wrap_count.saturating_sub(current_v_start);
1279            if rows_remaining_in_line >= visual_rows_capacity {
1280                break;
1281            }
1282
1283            visual_rows_capacity -= rows_remaining_in_line;
1284            current_line += 1;
1285            current_v_start = 0;
1286
1287            if current_line >= self.editor.line_count() {
1288                break;
1289            }
1290        }
1291
1292        // 3. Scroll Down (Backwards Scan)
1293        let mut needed = vp_height;
1294        let mut scan_line = cursor.line;
1295
1296        // For the cursor line itself
1297        let line_text = rope
1298            .line(scan_line)
1299            .unwrap_or(std::borrow::Cow::Borrowed(""));
1300        let line_text = line_text.trim_end_matches(['\n', '\r']);
1301        let (cursor_v, _) = Self::cursor_wrap_position(line_text, vp_width, cursor.visual_col);
1302
1303        let rows_above = cursor_v + 1;
1304        if rows_above >= needed {
1305            let new_v_start = cursor_v + 1 - needed;
1306            self.scroll_anchor.set((scan_line, new_v_start));
1307            return;
1308        }
1309
1310        needed -= rows_above;
1311
1312        // Scan previous lines
1313        while scan_line > 0 {
1314            scan_line -= 1;
1315            let line_text = rope
1316                .line(scan_line)
1317                .unwrap_or(std::borrow::Cow::Borrowed(""));
1318            let line_text = line_text.trim_end_matches(['\n', '\r']);
1319            let wrap_count = Self::measure_wrap_count(line_text, vp_width);
1320
1321            if wrap_count >= needed {
1322                let new_v_start = wrap_count - needed;
1323                self.scroll_anchor.set((scan_line, new_v_start));
1324                return;
1325            }
1326            needed -= wrap_count;
1327        }
1328
1329        // Reached top
1330        self.scroll_anchor.set((0, 0));
1331    }
1332}
1333
1334impl Widget for TextArea {
1335    fn render(&self, area: Rect, frame: &mut Frame) {
1336        if area.width < 1 || area.height < 1 {
1337            return;
1338        }
1339
1340        if frame.a11y_enabled() {
1341            frame.push_a11y_nodes(ftui_a11y::Accessible::accessibility_nodes(self, area));
1342        }
1343
1344        self.last_viewport_height.set(area.height as usize);
1345
1346        let deg = frame.buffer.degradation;
1347        let base_style = if deg.apply_styling() {
1348            self.style
1349        } else {
1350            Style::default()
1351        };
1352        clear_text_area(frame, area, base_style);
1353
1354        let gutter_w = self.gutter_width();
1355        let text_area_x = area.x.saturating_add(gutter_w);
1356        let text_area_w = area.width.saturating_sub(gutter_w) as usize;
1357        let vp_height = area.height as usize;
1358
1359        self.last_viewport_width.set(text_area_w);
1360
1361        let cursor = self.editor.cursor();
1362
1363        self.ensure_cursor_visible();
1364
1365        // Re-fetch potentially updated anchor
1366        let (scroll_top_line, scroll_top_vrow) = self.scroll_anchor.get();
1367        let scroll_left = self.scroll_left.get();
1368
1369        let rope = self.editor.rope();
1370        let nav = CursorNavigator::new(rope);
1371
1372        // Selection byte range for highlighting
1373        let sel_range = self.editor.selection().and_then(|sel| {
1374            if sel.is_empty() {
1375                None
1376            } else {
1377                let (a, b) = sel.byte_range(&nav);
1378                Some((a, b))
1379            }
1380        });
1381
1382        // Show placeholder if empty
1383        if self.editor.is_empty() && !self.placeholder.is_empty() {
1384            let style = if deg.apply_styling() {
1385                self.placeholder_style
1386            } else {
1387                Style::default()
1388            };
1389            draw_text_span(
1390                frame,
1391                text_area_x,
1392                area.y,
1393                &self.placeholder,
1394                style,
1395                area.right(),
1396            );
1397            if self.focused {
1398                frame.set_cursor(Some((text_area_x, area.y)));
1399            }
1400            return;
1401        }
1402
1403        if self.soft_wrap {
1404            self.scroll_left.set(0);
1405
1406            // Pre-calculate cursor wrap position
1407            let cursor_line_text = rope
1408                .line(cursor.line)
1409                .unwrap_or(std::borrow::Cow::Borrowed(""));
1410            let cursor_line_text = cursor_line_text.trim_end_matches(['\n', '\r']);
1411            let (cursor_wrap_idx, cursor_col_in_wrap) =
1412                Self::cursor_wrap_position(cursor_line_text, text_area_w, cursor.visual_col);
1413
1414            // Render wrapped lines starting from anchor
1415            let mut current_y = area.y;
1416            let bottom_y = area.bottom();
1417            let line_count = self.editor.line_count();
1418
1419            for line_idx in scroll_top_line..line_count {
1420                if current_y >= bottom_y {
1421                    break;
1422                }
1423
1424                let line_text = rope
1425                    .line(line_idx)
1426                    .unwrap_or(std::borrow::Cow::Borrowed(""));
1427                let line_text = line_text.trim_end_matches(['\n', '\r']);
1428
1429                let line_start_byte = nav.to_byte_index(nav.from_line_grapheme(line_idx, 0));
1430                // Syntax highlight spans for the whole logical line, computed
1431                // once and reused across every wrapped slice.
1432                let hl_spans = self.line_spans(line_idx, line_text, deg.apply_styling());
1433                let slices = Self::wrap_line_slices(line_text, text_area_w);
1434
1435                // If this is the start line, skip slices before anchor_vrow
1436                let start_slice = if line_idx == scroll_top_line {
1437                    scroll_top_vrow
1438                } else {
1439                    0
1440                };
1441
1442                for (slice_idx, slice) in slices.iter().enumerate().skip(start_slice) {
1443                    if current_y >= bottom_y {
1444                        break;
1445                    }
1446
1447                    // Line number gutter (only for first wrapped slice of the line)
1448                    if self.show_line_numbers && slice_idx == 0 {
1449                        let style = if deg.apply_styling() {
1450                            self.line_number_style
1451                        } else {
1452                            Style::default()
1453                        };
1454                        let num_str =
1455                            format!("{:>width$} ", line_idx + 1, width = (gutter_w - 2) as usize);
1456                        draw_text_span(frame, area.x, current_y, &num_str, style, text_area_x);
1457                    }
1458
1459                    // Cursor line highlight
1460                    if line_idx == cursor.line
1461                        && slice_idx == cursor_wrap_idx
1462                        && let Some(cl_style) = self.cursor_line_style
1463                        && deg.apply_styling()
1464                    {
1465                        for cx in text_area_x..area.right() {
1466                            if let Some(cell) = frame.buffer.get_mut(cx, current_y) {
1467                                apply_style(cell, cl_style);
1468                            }
1469                        }
1470                    }
1471
1472                    // Render graphemes inside the wrapped slice
1473                    let mut visual_x: usize = 0;
1474                    let mut grapheme_byte_offset = line_start_byte + slice.start_byte;
1475
1476                    for g in slice.text.graphemes(true) {
1477                        let g_width = display_width(g);
1478                        let g_byte_len = g.len();
1479
1480                        if visual_x >= text_area_w {
1481                            break;
1482                        }
1483
1484                        let px = text_area_x + visual_x as u16;
1485
1486                        // Syntax highlight first, then selection over it.
1487                        let mut g_style = base_style;
1488                        if let Some(hl) = style_at(
1489                            &hl_spans,
1490                            grapheme_byte_offset.saturating_sub(line_start_byte),
1491                        ) {
1492                            g_style = g_style.patch(&hl);
1493                        }
1494                        if let Some((sel_start, sel_end)) = sel_range
1495                            && grapheme_byte_offset >= sel_start
1496                            && grapheme_byte_offset < sel_end
1497                            && deg.apply_styling()
1498                        {
1499                            g_style = g_style.patch(&self.selection_style);
1500                        }
1501
1502                        if g_width > 0 {
1503                            draw_text_span(frame, px, current_y, g, g_style, area.right());
1504                        }
1505
1506                        visual_x += g_width;
1507                        grapheme_byte_offset += g_byte_len;
1508                    }
1509
1510                    // Set cursor position if focused
1511                    if self.focused && line_idx == cursor.line && slice_idx == cursor_wrap_idx {
1512                        let cursor_screen_x = text_area_x.saturating_add(cursor_col_in_wrap as u16);
1513                        if cursor_screen_x < area.right() {
1514                            frame.set_cursor(Some((cursor_screen_x, current_y)));
1515                        }
1516                    }
1517
1518                    current_y += 1;
1519                }
1520            }
1521
1522            return;
1523        }
1524
1525        // Render visible lines (no soft wrap)
1526        for row in 0..vp_height {
1527            let line_idx = scroll_top_line + row;
1528            let y = area.y.saturating_add(row as u16);
1529
1530            if line_idx >= self.editor.line_count() {
1531                break;
1532            }
1533
1534            // Line number gutter
1535            if self.show_line_numbers {
1536                let style = if deg.apply_styling() {
1537                    self.line_number_style
1538                } else {
1539                    Style::default()
1540                };
1541                let num_str = format!("{:>width$} ", line_idx + 1, width = (gutter_w - 2) as usize);
1542                draw_text_span(frame, area.x, y, &num_str, style, text_area_x);
1543            }
1544
1545            // Cursor line highlight
1546            if line_idx == cursor.line
1547                && let Some(cl_style) = self.cursor_line_style
1548                && deg.apply_styling()
1549            {
1550                for cx in text_area_x..area.right() {
1551                    if let Some(cell) = frame.buffer.get_mut(cx, y) {
1552                        apply_style(cell, cl_style);
1553                    }
1554                }
1555            }
1556
1557            // Get line text
1558            let line_text = rope
1559                .line(line_idx)
1560                .unwrap_or(std::borrow::Cow::Borrowed(""));
1561            let line_text = line_text.trim_end_matches(['\n', '\r']);
1562
1563            // Calculate line byte offset for selection mapping
1564            let line_start_byte = nav.to_byte_index(nav.from_line_grapheme(line_idx, 0));
1565            let hl_spans = self.line_spans(line_idx, line_text, deg.apply_styling());
1566
1567            // Render each grapheme
1568            let mut visual_x: usize = 0;
1569            let graphemes: Vec<&str> = line_text.graphemes(true).collect();
1570            let mut grapheme_byte_offset = line_start_byte;
1571
1572            for g in &graphemes {
1573                let g_width = display_width(g);
1574                let g_byte_len = g.len();
1575
1576                // Syntax highlight first, then selection over it.
1577                let mut g_style = base_style;
1578                if let Some(hl) = style_at(
1579                    &hl_spans,
1580                    grapheme_byte_offset.saturating_sub(line_start_byte),
1581                ) {
1582                    g_style = g_style.patch(&hl);
1583                }
1584                if let Some((sel_start, sel_end)) = sel_range
1585                    && grapheme_byte_offset >= sel_start
1586                    && grapheme_byte_offset < sel_end
1587                    && deg.apply_styling()
1588                {
1589                    g_style = g_style.patch(&self.selection_style);
1590                }
1591
1592                // Skip graphemes before horizontal scroll
1593                if visual_x + g_width <= scroll_left {
1594                    visual_x += g_width;
1595                    grapheme_byte_offset += g_byte_len;
1596                    continue;
1597                }
1598
1599                // Handle partial overlap at left edge
1600                if visual_x < scroll_left {
1601                    // Calculate visible width of the partially scrolled grapheme
1602                    let end_x = visual_x + g_width;
1603                    let visible_width = end_x.saturating_sub(scroll_left);
1604
1605                    // Render padding spaces for the visible portion to preserve background style
1606                    for i in 0..visible_width {
1607                        let screen_x = i; // Starts at 0 relative to text area
1608                        let px = text_area_x + screen_x as u16;
1609                        if px < area.right() {
1610                            draw_text_span(frame, px, y, " ", g_style, area.right());
1611                        }
1612                    }
1613
1614                    visual_x += g_width;
1615                    grapheme_byte_offset += g_byte_len;
1616                    continue;
1617                }
1618
1619                // Stop if past viewport
1620                let screen_x = visual_x.saturating_sub(scroll_left);
1621                if screen_x >= text_area_w {
1622                    break;
1623                }
1624
1625                let px = text_area_x + screen_x as u16;
1626
1627                // Write grapheme to buffer
1628                if g_width > 0 {
1629                    draw_text_span(frame, px, y, g, g_style, area.right());
1630                }
1631
1632                visual_x += g_width;
1633                grapheme_byte_offset += g_byte_len;
1634            }
1635        }
1636
1637        // Set cursor position if focused
1638        if self.focused {
1639            let cursor_row = cursor.line.saturating_sub(scroll_top_line);
1640            if cursor_row < vp_height {
1641                let cursor_screen_x = (cursor.visual_col.saturating_sub(scroll_left) as u16)
1642                    .saturating_add(text_area_x);
1643                let cursor_screen_y = area.y.saturating_add(cursor_row as u16);
1644                if cursor_screen_x < area.right() && cursor_screen_y < area.bottom() {
1645                    frame.set_cursor(Some((cursor_screen_x, cursor_screen_y)));
1646                }
1647            }
1648        }
1649    }
1650
1651    fn is_essential(&self) -> bool {
1652        true
1653    }
1654}
1655
1656impl ftui_a11y::Accessible for TextArea {
1657    fn accessibility_nodes(&self, area: Rect) -> Vec<ftui_a11y::node::A11yNodeInfo> {
1658        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState};
1659
1660        if area.is_empty() {
1661            return Vec::new();
1662        }
1663        let text = self.text();
1664        let name = if text.is_empty() {
1665            self.placeholder.clone()
1666        } else {
1667            text
1668        };
1669        vec![
1670            A11yNodeInfo::new(crate::a11y_node_id(area), A11yRole::TextInput, area)
1671                .with_name(name)
1672                .with_description("multi-line text input")
1673                .with_state(A11yState {
1674                    focused: self.focused,
1675                    ..A11yState::default()
1676                }),
1677        ]
1678    }
1679}
1680
1681impl StatefulWidget for TextArea {
1682    type State = TextAreaState;
1683
1684    fn render(&self, area: Rect, frame: &mut Frame, state: &mut Self::State) {
1685        state.last_viewport_height = area.height;
1686        state.last_viewport_width = area.width;
1687        Widget::render(self, area, frame);
1688    }
1689}
1690
1691#[cfg(test)]
1692mod tests {
1693    use super::*;
1694
1695    fn raw_row_text(frame: &Frame, y: u16, width: u16) -> String {
1696        (0..width)
1697            .map(|x| {
1698                frame
1699                    .buffer
1700                    .get(x, y)
1701                    .and_then(|cell| cell.content.as_char())
1702                    .unwrap_or(' ')
1703            })
1704            .collect()
1705    }
1706
1707    #[test]
1708    fn new_textarea_is_empty() {
1709        let ta = TextArea::new();
1710        assert!(ta.is_empty());
1711        assert_eq!(ta.text(), "");
1712        assert_eq!(ta.line_count(), 1); // empty rope has 1 line
1713    }
1714
1715    #[test]
1716    fn accessibility_preserves_multiline_content_and_focus() {
1717        use ftui_a11y::Accessible;
1718        use ftui_a11y::node::A11yRole;
1719
1720        let area = Rect::new(3, 4, 20, 2);
1721        let mut textarea = TextArea::new().with_text("first é\nsecond 日");
1722        let initial = textarea.accessibility_nodes(area);
1723        assert_eq!(initial.len(), 1);
1724        assert_eq!(initial[0].role, A11yRole::TextInput);
1725        assert_eq!(initial[0].name.as_deref(), Some("first é\nsecond 日"));
1726        assert!(!initial[0].state.focused);
1727        textarea.set_focused(true);
1728        let focused = textarea.accessibility_nodes(area);
1729        assert!(focused[0].state.focused);
1730        assert_eq!(focused[0].id, initial[0].id);
1731        assert_eq!(focused[0].bounds, area);
1732        assert!(
1733            textarea
1734                .accessibility_nodes(Rect::new(0, 0, 0, 2))
1735                .is_empty()
1736        );
1737        let empty = TextArea::new().with_placeholder("Write a message");
1738        assert_eq!(
1739            empty.accessibility_nodes(area)[0].name.as_deref(),
1740            Some("Write a message")
1741        );
1742    }
1743
1744    #[test]
1745    fn render_collects_textarea_accessibility_only_when_enabled() {
1746        use ftui_a11y::tree::A11yTreeBuilder;
1747        use ftui_render::grapheme_pool::GraphemePool;
1748
1749        let textarea = TextArea::new()
1750            .with_text("line one\nline two")
1751            .with_focus(true);
1752        let area = Rect::new(2, 1, 12, 2);
1753        let mut pool = GraphemePool::new();
1754        let mut frame = Frame::new(20, 5, &mut pool);
1755        Widget::render(&textarea, area, &mut frame);
1756        assert!(frame.a11y_order().is_empty());
1757
1758        let mut builder = A11yTreeBuilder::new();
1759        let mut frame = Frame::new(20, 5, &mut pool);
1760        frame.set_a11y(&mut builder);
1761        Widget::render(&textarea, area, &mut frame);
1762        frame.finish_a11y();
1763        drop(frame);
1764        let tree = builder.build();
1765        assert_eq!(tree.nodes().count(), 1);
1766        assert_eq!(
1767            tree.focused().and_then(|node| node.name.as_deref()),
1768            Some("line one\nline two")
1769        );
1770    }
1771
1772    #[test]
1773    fn with_text_builder() {
1774        let ta = TextArea::new().with_text("hello\nworld");
1775        assert_eq!(ta.text(), "hello\nworld");
1776        assert_eq!(ta.line_count(), 2);
1777    }
1778
1779    #[test]
1780    fn insert_text_and_newline() {
1781        let mut ta = TextArea::new();
1782        ta.insert_text("hello");
1783        ta.insert_newline();
1784        ta.insert_text("world");
1785        assert_eq!(ta.text(), "hello\nworld");
1786        assert_eq!(ta.line_count(), 2);
1787    }
1788
1789    #[test]
1790    fn delete_backward_works() {
1791        let mut ta = TextArea::new().with_text("hello");
1792        ta.move_to_document_end();
1793        ta.delete_backward();
1794        assert_eq!(ta.text(), "hell");
1795    }
1796
1797    #[test]
1798    fn cursor_movement() {
1799        let mut ta = TextArea::new().with_text("abc\ndef\nghi");
1800        ta.move_to_document_start();
1801        assert_eq!(ta.cursor().line, 0);
1802        assert_eq!(ta.cursor().grapheme, 0);
1803
1804        ta.move_down();
1805        assert_eq!(ta.cursor().line, 1);
1806
1807        ta.move_to_line_end();
1808        assert_eq!(ta.cursor().grapheme, 3);
1809
1810        ta.move_to_document_end();
1811        assert_eq!(ta.cursor().line, 2);
1812    }
1813
1814    #[test]
1815    fn undo_redo() {
1816        let mut ta = TextArea::new();
1817        ta.insert_text("abc");
1818        assert_eq!(ta.text(), "abc");
1819        ta.undo();
1820        assert_eq!(ta.text(), "");
1821        ta.redo();
1822        assert_eq!(ta.text(), "abc");
1823    }
1824
1825    #[test]
1826    fn selection_and_delete() {
1827        let mut ta = TextArea::new().with_text("hello world");
1828        ta.move_to_document_start();
1829        for _ in 0..5 {
1830            ta.select_right();
1831        }
1832        assert_eq!(ta.selected_text(), Some("hello".to_string()));
1833        ta.delete_backward();
1834        assert_eq!(ta.text(), " world");
1835    }
1836
1837    #[test]
1838    fn select_all() {
1839        let mut ta = TextArea::new().with_text("abc\ndef");
1840        ta.select_all();
1841        assert_eq!(ta.selected_text(), Some("abc\ndef".to_string()));
1842    }
1843
1844    #[test]
1845    fn set_text_resets() {
1846        let mut ta = TextArea::new().with_text("old");
1847        ta.insert_text(" stuff");
1848        ta.set_text("new");
1849        assert_eq!(ta.text(), "new");
1850    }
1851
1852    #[test]
1853    fn scroll_follows_cursor() {
1854        let mut ta = TextArea::new();
1855        // Insert many lines
1856        for i in 0..50 {
1857            ta.insert_text(&format!("line {}\n", i));
1858        }
1859        // Cursor should be at the bottom, scroll anchor adjusted.
1860        assert!(ta.scroll_anchor.get().0 > 0);
1861        assert!(ta.cursor().line >= 49);
1862
1863        // Move to top
1864        ta.move_to_document_start();
1865        assert_eq!(ta.scroll_anchor.get().0, 0);
1866    }
1867
1868    #[test]
1869    fn gutter_width_without_line_numbers() {
1870        let ta = TextArea::new();
1871        assert_eq!(ta.gutter_width(), 0);
1872    }
1873
1874    #[test]
1875    fn gutter_width_with_line_numbers() {
1876        let mut ta = TextArea::new().with_line_numbers(true);
1877        ta.insert_text("a\nb\nc");
1878        assert_eq!(ta.gutter_width(), 3); // 1 digit + space + separator
1879    }
1880
1881    #[test]
1882    fn gutter_width_many_lines() {
1883        let mut ta = TextArea::new().with_line_numbers(true);
1884        for i in 0..100 {
1885            ta.insert_text(&format!("line {}\n", i));
1886        }
1887        assert_eq!(ta.gutter_width(), 5); // 3 digits + space + separator
1888    }
1889
1890    #[test]
1891    fn focus_state() {
1892        let mut ta = TextArea::new();
1893        assert!(!ta.is_focused());
1894        ta.set_focused(true);
1895        assert!(ta.is_focused());
1896    }
1897
1898    #[test]
1899    fn word_movement() {
1900        let mut ta = TextArea::new().with_text("hello world foo");
1901        ta.move_to_document_start();
1902        ta.move_word_right();
1903        assert_eq!(ta.cursor().grapheme, 6);
1904        ta.move_word_left();
1905        assert_eq!(ta.cursor().grapheme, 0);
1906    }
1907
1908    #[test]
1909    fn page_up_down() {
1910        let mut ta = TextArea::new();
1911        for i in 0..50 {
1912            ta.insert_text(&format!("line {}\n", i));
1913        }
1914        ta.move_to_document_start();
1915        let state = TextAreaState {
1916            last_viewport_height: 10,
1917            last_viewport_width: 80,
1918        };
1919        ta.page_down(&state);
1920        assert!(ta.cursor().line >= 10);
1921        ta.page_up(&state);
1922        assert_eq!(ta.cursor().line, 0);
1923    }
1924
1925    #[test]
1926    fn insert_replaces_selection() {
1927        let mut ta = TextArea::new().with_text("hello world");
1928        ta.move_to_document_start();
1929        for _ in 0..5 {
1930            ta.select_right();
1931        }
1932        ta.insert_text("goodbye");
1933        assert_eq!(ta.text(), "goodbye world");
1934    }
1935
1936    #[test]
1937    fn insert_single_char() {
1938        let mut ta = TextArea::new();
1939        ta.insert_char('X');
1940        assert_eq!(ta.text(), "X");
1941        assert_eq!(ta.cursor().grapheme, 1);
1942    }
1943
1944    #[test]
1945    fn insert_multiline_text() {
1946        let mut ta = TextArea::new();
1947        ta.insert_text("line1\nline2\nline3");
1948        assert_eq!(ta.line_count(), 3);
1949        assert_eq!(ta.cursor().line, 2);
1950    }
1951
1952    #[test]
1953    fn delete_forward_works() {
1954        let mut ta = TextArea::new().with_text("hello");
1955        ta.move_to_document_start();
1956        ta.delete_forward();
1957        assert_eq!(ta.text(), "ello");
1958    }
1959
1960    #[test]
1961    fn delete_backward_at_line_start_joins_lines() {
1962        let mut ta = TextArea::new().with_text("abc\ndef");
1963        // Move to start of line 2
1964        ta.move_to_document_start();
1965        ta.move_down();
1966        ta.move_to_line_start();
1967        ta.delete_backward();
1968        assert_eq!(ta.text(), "abcdef");
1969        assert_eq!(ta.line_count(), 1);
1970    }
1971
1972    #[test]
1973    fn cursor_horizontal_movement() {
1974        let mut ta = TextArea::new().with_text("abc");
1975        ta.move_to_document_start();
1976        ta.move_right();
1977        assert_eq!(ta.cursor().grapheme, 1);
1978        ta.move_right();
1979        assert_eq!(ta.cursor().grapheme, 2);
1980        ta.move_left();
1981        assert_eq!(ta.cursor().grapheme, 1);
1982    }
1983
1984    #[test]
1985    fn cursor_vertical_maintains_column() {
1986        let mut ta = TextArea::new().with_text("abcde\nfg\nhijkl");
1987        ta.move_to_document_start();
1988        ta.move_to_line_end(); // col 5
1989        ta.move_down(); // line 1 only has 2 chars, should clamp
1990        assert_eq!(ta.cursor().line, 1);
1991        ta.move_down(); // line 2 has 5 chars, should restore col
1992        assert_eq!(ta.cursor().line, 2);
1993    }
1994
1995    #[test]
1996    fn selection_shift_arrow() {
1997        let mut ta = TextArea::new().with_text("abcdef");
1998        ta.move_to_document_start();
1999        ta.select_right();
2000        ta.select_right();
2001        ta.select_right();
2002        assert_eq!(ta.selected_text(), Some("abc".to_string()));
2003    }
2004
2005    #[test]
2006    fn selection_extends_up_down() {
2007        let mut ta = TextArea::new().with_text("line1\nline2\nline3");
2008        ta.move_to_document_start();
2009        ta.select_down();
2010        let sel = ta.selected_text().unwrap();
2011        assert!(sel.contains('\n'));
2012    }
2013
2014    #[test]
2015    fn undo_chain() {
2016        let mut ta = TextArea::new();
2017        ta.insert_text("a");
2018        ta.insert_text("b");
2019        ta.insert_text("c");
2020        assert_eq!(ta.text(), "abc");
2021        ta.undo();
2022        ta.undo();
2023        ta.undo();
2024        assert_eq!(ta.text(), "");
2025    }
2026
2027    #[test]
2028    fn redo_discarded_on_new_edit() {
2029        let mut ta = TextArea::new();
2030        ta.insert_text("abc");
2031        ta.undo();
2032        ta.insert_text("xyz");
2033        ta.redo(); // should be no-op
2034        assert_eq!(ta.text(), "xyz");
2035    }
2036
2037    #[test]
2038    fn clear_selection() {
2039        let mut ta = TextArea::new().with_text("hello");
2040        ta.select_all();
2041        assert!(ta.selection().is_some());
2042        ta.clear_selection();
2043        assert!(ta.selection().is_none());
2044    }
2045
2046    #[test]
2047    fn delete_word_backward() {
2048        let mut ta = TextArea::new().with_text("hello world");
2049        ta.move_to_document_end();
2050        ta.delete_word_backward();
2051        assert_eq!(ta.text(), "hello ");
2052    }
2053
2054    #[test]
2055    fn delete_to_end_of_line() {
2056        let mut ta = TextArea::new().with_text("hello world");
2057        ta.move_to_document_start();
2058        ta.move_right(); // after 'h'
2059        ta.delete_to_end_of_line();
2060        assert_eq!(ta.text(), "h");
2061    }
2062
2063    #[test]
2064    fn placeholder_builder() {
2065        let ta = TextArea::new().with_placeholder("Enter text...");
2066        assert!(ta.is_empty());
2067        assert_eq!(ta.placeholder, "Enter text...");
2068    }
2069
2070    #[test]
2071    fn soft_wrap_builder() {
2072        let ta = TextArea::new().with_soft_wrap(true);
2073        assert!(ta.soft_wrap);
2074    }
2075
2076    #[test]
2077    fn soft_wrap_renders_wrapped_lines() {
2078        use crate::Widget;
2079        use ftui_render::grapheme_pool::GraphemePool;
2080
2081        let ta = TextArea::new().with_soft_wrap(true).with_text("abcdef");
2082        let area = Rect::new(0, 0, 3, 2);
2083        let mut pool = GraphemePool::new();
2084        let mut frame = Frame::new(3, 2, &mut pool);
2085        Widget::render(&ta, area, &mut frame);
2086
2087        assert_eq!(frame.buffer.get(0, 0).unwrap().content.as_char(), Some('a'));
2088        assert_eq!(frame.buffer.get(2, 0).unwrap().content.as_char(), Some('c'));
2089        assert_eq!(frame.buffer.get(0, 1).unwrap().content.as_char(), Some('d'));
2090        assert_eq!(frame.buffer.get(2, 1).unwrap().content.as_char(), Some('f'));
2091    }
2092
2093    #[test]
2094    fn max_height_builder() {
2095        let ta = TextArea::new().with_max_height(10);
2096        assert_eq!(ta.max_height, 10);
2097    }
2098
2099    #[test]
2100    fn editor_access() {
2101        let mut ta = TextArea::new().with_text("test");
2102        assert_eq!(ta.editor().text(), "test");
2103        ta.editor_mut().insert_char('!');
2104        assert!(ta.text().contains('!'));
2105    }
2106
2107    #[test]
2108    fn move_to_line_start_and_end() {
2109        let mut ta = TextArea::new().with_text("hello world");
2110        ta.move_to_document_start();
2111        ta.move_to_line_end();
2112        assert_eq!(ta.cursor().grapheme, 11);
2113        ta.move_to_line_start();
2114        assert_eq!(ta.cursor().grapheme, 0);
2115    }
2116
2117    #[test]
2118    fn render_empty_with_placeholder() {
2119        use ftui_render::grapheme_pool::GraphemePool;
2120        let ta = TextArea::new()
2121            .with_placeholder("Type here")
2122            .with_focus(true);
2123        let mut pool = GraphemePool::new();
2124        let mut frame = Frame::new(20, 5, &mut pool);
2125        let area = Rect::new(0, 0, 20, 5);
2126        Widget::render(&ta, area, &mut frame);
2127        // Placeholder should be rendered
2128        let cell = frame.buffer.get(0, 0).unwrap();
2129        assert_eq!(cell.content.as_char(), Some('T'));
2130        // Cursor should be set
2131        assert!(frame.cursor_position.is_some());
2132    }
2133
2134    #[test]
2135    fn render_with_content() {
2136        use ftui_render::grapheme_pool::GraphemePool;
2137        let ta = TextArea::new().with_text("abc\ndef").with_focus(true);
2138        let mut pool = GraphemePool::new();
2139        let mut frame = Frame::new(20, 5, &mut pool);
2140        let area = Rect::new(0, 0, 20, 5);
2141        Widget::render(&ta, area, &mut frame);
2142        let cell = frame.buffer.get(0, 0).unwrap();
2143        assert_eq!(cell.content.as_char(), Some('a'));
2144    }
2145
2146    #[test]
2147    fn render_shorter_text_clears_stale_suffix_and_extra_lines() {
2148        use ftui_render::grapheme_pool::GraphemePool;
2149
2150        let area = Rect::new(0, 0, 8, 3);
2151        let mut pool = GraphemePool::new();
2152        let mut frame = Frame::new(8, 3, &mut pool);
2153
2154        Widget::render(
2155            &TextArea::new().with_text("abcdef\nghijkl"),
2156            area,
2157            &mut frame,
2158        );
2159        Widget::render(&TextArea::new().with_text("hi"), area, &mut frame);
2160
2161        assert_eq!(raw_row_text(&frame, 0, 8), "hi      ");
2162        assert_eq!(raw_row_text(&frame, 1, 8), "        ");
2163        assert_eq!(raw_row_text(&frame, 2, 8), "        ");
2164    }
2165
2166    #[test]
2167    fn render_line_numbers_without_styling() {
2168        use ftui_render::budget::DegradationLevel;
2169        use ftui_render::grapheme_pool::GraphemePool;
2170
2171        let ta = TextArea::new().with_text("a\nb").with_line_numbers(true);
2172        let mut pool = GraphemePool::new();
2173        let mut frame = Frame::new(8, 2, &mut pool);
2174        frame.set_degradation(DegradationLevel::NoStyling);
2175
2176        Widget::render(&ta, Rect::new(0, 0, 8, 2), &mut frame);
2177
2178        let cell = frame.buffer.get(0, 0).unwrap();
2179        assert_eq!(cell.content.as_char(), Some('1'));
2180    }
2181
2182    #[test]
2183    fn stateful_render_updates_viewport_state() {
2184        use ftui_render::grapheme_pool::GraphemePool;
2185
2186        let ta = TextArea::new();
2187        let mut state = TextAreaState::default();
2188        let mut pool = GraphemePool::new();
2189        let mut frame = Frame::new(10, 3, &mut pool);
2190        let area = Rect::new(0, 0, 10, 3);
2191
2192        StatefulWidget::render(&ta, area, &mut frame, &mut state);
2193
2194        assert_eq!(state.last_viewport_height, 3);
2195        assert_eq!(state.last_viewport_width, 10);
2196    }
2197
2198    #[test]
2199    fn render_zero_area_no_panic() {
2200        let ta = TextArea::new().with_text("test");
2201        use ftui_render::grapheme_pool::GraphemePool;
2202        let mut pool = GraphemePool::new();
2203        let mut frame = Frame::new(10, 10, &mut pool);
2204        Widget::render(&ta, Rect::new(0, 0, 0, 0), &mut frame);
2205    }
2206
2207    #[test]
2208    fn is_essential() {
2209        let ta = TextArea::new();
2210        assert!(Widget::is_essential(&ta));
2211    }
2212
2213    #[test]
2214    fn default_impl() {
2215        let ta = TextArea::default();
2216        assert!(ta.is_empty());
2217    }
2218
2219    #[test]
2220    fn insert_newline_splits_line() {
2221        let mut ta = TextArea::new().with_text("abcdef");
2222        ta.move_to_document_start();
2223        ta.move_right();
2224        ta.move_right();
2225        ta.move_right();
2226        ta.insert_newline();
2227        assert_eq!(ta.line_count(), 2);
2228        assert_eq!(ta.cursor().line, 1);
2229    }
2230
2231    #[test]
2232    fn unicode_grapheme_cluster() {
2233        let mut ta = TextArea::new();
2234        ta.insert_text("café");
2235        // 'é' is a single grapheme even if composed
2236        assert_eq!(ta.text(), "café");
2237    }
2238
2239    mod proptests {
2240        use super::*;
2241        use proptest::prelude::*;
2242
2243        proptest! {
2244            #[test]
2245            fn insert_delete_inverse(text in "[a-zA-Z0-9 ]{1,50}") {
2246                let mut ta = TextArea::new();
2247                ta.insert_text(&text);
2248                // Delete all characters backwards
2249                for _ in 0..text.len() {
2250                    ta.delete_backward();
2251                }
2252                prop_assert!(ta.is_empty() || ta.text().is_empty());
2253            }
2254
2255            #[test]
2256            fn undo_redo_inverse(text in "[a-zA-Z0-9]{1,30}") {
2257                let mut ta = TextArea::new();
2258                ta.insert_text(&text);
2259                let after_insert = ta.text();
2260                ta.undo();
2261                ta.redo();
2262                prop_assert_eq!(ta.text(), after_insert);
2263            }
2264
2265            #[test]
2266            fn cursor_always_valid(ops in proptest::collection::vec(0u8..10, 1..20)) {
2267                let mut ta = TextArea::new().with_text("abc\ndef\nghi\njkl");
2268                for op in ops {
2269                    match op {
2270                        0 => ta.move_left(),
2271                        1 => ta.move_right(),
2272                        2 => ta.move_up(),
2273                        3 => ta.move_down(),
2274                        4 => ta.move_to_line_start(),
2275                        5 => ta.move_to_line_end(),
2276                        6 => ta.move_to_document_start(),
2277                        7 => ta.move_to_document_end(),
2278                        8 => ta.move_word_left(),
2279                        _ => ta.move_word_right(),
2280                    }
2281                    let cursor = ta.cursor();
2282                    prop_assert!(cursor.line < ta.line_count(),
2283                        "cursor line {} >= line_count {}", cursor.line, ta.line_count());
2284                }
2285            }
2286
2287            #[test]
2288            fn selection_ordered(n in 1usize..20) {
2289                let mut ta = TextArea::new().with_text("hello world foo bar");
2290                ta.move_to_document_start();
2291                for _ in 0..n {
2292                    ta.select_right();
2293                }
2294                if let Some(sel) = ta.selection() {
2295                    // When selecting right from start, anchor should be at/before head
2296                    prop_assert!(sel.anchor.line <= sel.head.line
2297                        || (sel.anchor.line == sel.head.line
2298                            && sel.anchor.grapheme <= sel.head.grapheme));
2299                }
2300            }
2301        }
2302    }
2303
2304    mod highlighter_tests {
2305        use super::*;
2306        use ftui_render::cell::PackedRgba;
2307        use ftui_render::frame::Frame;
2308        use ftui_render::grapheme_pool::GraphemePool;
2309        use proptest::prelude::*;
2310
2311        fn render(ta: &TextArea, w: u16, h: u16, mut f: impl FnMut(&Frame)) {
2312            let mut pool = GraphemePool::new();
2313            let mut frame = Frame::new(w, h, &mut pool);
2314            Widget::render(ta, Rect::new(0, 0, w, h), &mut frame);
2315            f(&frame);
2316        }
2317
2318        #[test]
2319        fn highlighter_receives_each_visible_line_once() {
2320            let seen = Arc::new(std::sync::Mutex::new(Vec::<usize>::new()));
2321            let recorder = seen.clone();
2322            let ta = TextArea::new()
2323                .with_text("one\ntwo\nthree")
2324                .with_highlighter(Arc::new(move |line, _text| {
2325                    recorder.lock().unwrap().push(line);
2326                    Vec::new()
2327                }));
2328            assert!(ta.has_highlighter());
2329            render(&ta, 20, 3, |_| {});
2330            let mut lines = seen.lock().unwrap().clone();
2331            lines.sort_unstable();
2332            assert_eq!(lines, vec![0, 1, 2]);
2333        }
2334
2335        #[test]
2336        fn highlighter_ranges_style_graphemes() {
2337            let ta = TextArea::new()
2338                .with_text("abcdef")
2339                .with_highlighter(Arc::new(|_l, _t| {
2340                    vec![(0..3, Style::new().fg(PackedRgba::RED))]
2341                }));
2342            render(&ta, 10, 1, |frame| {
2343                for x in 0..3 {
2344                    assert_eq!(
2345                        frame.buffer.get(x, 0).unwrap().fg,
2346                        PackedRgba::RED,
2347                        "col {x}"
2348                    );
2349                }
2350                assert_ne!(frame.buffer.get(3, 0).unwrap().fg, PackedRgba::RED);
2351            });
2352        }
2353
2354        #[test]
2355        fn out_of_range_and_non_boundary_ranges_ignored() {
2356            // "café": c(0) a(1) f(2) é(3..5); len 5. All three ranges are
2357            // invalid (past end / splits 'é' / inverted) and are dropped.
2358            let ta = TextArea::new()
2359                .with_text("café")
2360                .with_highlighter(Arc::new(|_l, _t| {
2361                    // Struct literal so clippy does not flag the reversed range.
2362                    let inverted = Range { start: 5, end: 2 };
2363                    vec![
2364                        (0..100, Style::new().fg(PackedRgba::RED)),
2365                        (3..4, Style::new().fg(PackedRgba::GREEN)),
2366                        (inverted, Style::new().fg(PackedRgba::BLUE)),
2367                    ]
2368                }));
2369            assert!(ta.line_spans(0, "café", true).is_empty());
2370            render(&ta, 10, 1, |_| {}); // no panic
2371        }
2372
2373        #[test]
2374        fn multibyte_ranges_align_to_graphemes() {
2375            // Highlight only the 2-byte 'é' (bytes 3..5).
2376            let ta = TextArea::new()
2377                .with_text("café")
2378                .with_highlighter(Arc::new(|_l, _t| {
2379                    vec![(3..5, Style::new().fg(PackedRgba::RED))]
2380                }));
2381            assert_eq!(ta.line_spans(0, "café", true).len(), 1);
2382            render(&ta, 10, 1, |frame| {
2383                assert_eq!(frame.buffer.get(3, 0).unwrap().fg, PackedRgba::RED, "'é'");
2384                assert_ne!(frame.buffer.get(0, 0).unwrap().fg, PackedRgba::RED, "'c'");
2385            });
2386        }
2387
2388        #[test]
2389        fn selection_style_merges_over_highlight() {
2390            let mut ta = TextArea::new()
2391                .with_text("abcdef")
2392                .with_focus(true)
2393                .with_selection_style(Style::new().bg(PackedRgba::GREEN))
2394                .with_highlighter(Arc::new(|_l, _t| {
2395                    vec![(0..6, Style::new().bg(PackedRgba::RED).fg(PackedRgba::WHITE))]
2396                }));
2397            ta.move_to_document_start();
2398            ta.select_right();
2399            ta.select_right();
2400            ta.select_right();
2401            render(&ta, 10, 1, |frame| {
2402                let selected = frame.buffer.get(0, 0).unwrap();
2403                assert_eq!(
2404                    selected.bg,
2405                    PackedRgba::GREEN,
2406                    "selection bg wins over highlight"
2407                );
2408                assert_eq!(selected.fg, PackedRgba::WHITE, "highlight fg preserved");
2409                let highlighted = frame.buffer.get(3, 0).unwrap();
2410                assert_eq!(
2411                    highlighted.bg,
2412                    PackedRgba::RED,
2413                    "unselected cell keeps highlight bg"
2414                );
2415            });
2416        }
2417
2418        #[test]
2419        fn soft_wrap_applies_highlight_on_continuation_rows() {
2420            // 10 chars wrapped at width 5 -> row 0 "abcde", row 1 "fghij"; the
2421            // whole-line highlight must reach the continuation row.
2422            let ta = TextArea::new()
2423                .with_text("abcdefghij")
2424                .with_soft_wrap(true)
2425                .with_highlighter(Arc::new(|_l, _t| {
2426                    vec![(0..10, Style::new().fg(PackedRgba::RED))]
2427                }));
2428            render(&ta, 5, 2, |frame| {
2429                assert_eq!(
2430                    frame.buffer.get(0, 0).unwrap().fg,
2431                    PackedRgba::RED,
2432                    "first row"
2433                );
2434                assert_eq!(
2435                    frame.buffer.get(0, 1).unwrap().fg,
2436                    PackedRgba::RED,
2437                    "continuation row highlighted"
2438                );
2439            });
2440        }
2441
2442        proptest! {
2443            #![proptest_config(ProptestConfig::with_cases(512))]
2444
2445            /// `style_at` returns the last covering range's style and never
2446            /// panics for any byte offset.
2447            #[test]
2448            fn style_at_returns_last_covering_range(
2449                bounds in prop::collection::vec((0usize..20, 0usize..20), 0..6),
2450                byte in 0usize..25,
2451            ) {
2452                let spans: Vec<(Range<usize>, Style)> = bounds
2453                    .iter()
2454                    .filter(|(a, b)| a < b)
2455                    .enumerate()
2456                    .map(|(i, (a, b))| (*a..*b, Style::new().fg(PackedRgba::rgb((i * 30) as u8, 1, 2))))
2457                    .collect();
2458                let expected = spans.iter().rev().find(|(r, _)| r.contains(&byte)).map(|(_, s)| *s);
2459                prop_assert_eq!(style_at(&spans, byte), expected);
2460            }
2461        }
2462    }
2463}