Skip to main content

fc_ui/capabilities/controls/
textarea_state.rs

1//! Textarea state management for multi-line text input
2//!
3//! Architecture mirrors InputState: Entity-based state with EntityInputHandler,
4//! Focusable, EventEmitter, and a custom Element for text rendering.
5
6use crate::capabilities::foundation::theme::use_theme;
7use gpui::{prelude::*, *};
8use std::ops::Range;
9
10use crate::capabilities::controls::text_util;
11use crate::capabilities::controls::validation;
12pub use crate::capabilities::controls::validation::{ValidationError, ValidationRules};
13use crate::capabilities::foundation::edit;
14
15pub fn init(cx: &mut App) {
16    if !crate::capabilities::foundation::initialization::begin(cx, "textarea-state") {
17        return;
18    }
19    cx.bind_keys([
20        KeyBinding::new("backspace", Backspace, Some("Textarea")),
21        KeyBinding::new("delete", Delete, Some("Textarea")),
22        KeyBinding::new("left", Left, Some("Textarea")),
23        KeyBinding::new("right", Right, Some("Textarea")),
24        KeyBinding::new("up", Up, Some("Textarea")),
25        KeyBinding::new("down", Down, Some("Textarea")),
26        KeyBinding::new("shift-left", SelectLeft, Some("Textarea")),
27        KeyBinding::new("shift-right", SelectRight, Some("Textarea")),
28        KeyBinding::new("shift-up", SelectUp, Some("Textarea")),
29        KeyBinding::new("shift-down", SelectDown, Some("Textarea")),
30        KeyBinding::new("home", Home, Some("Textarea")),
31        KeyBinding::new("end", End, Some("Textarea")),
32        KeyBinding::new("enter", Enter, Some("Textarea")),
33        KeyBinding::new("shift-enter", ShiftEnter, Some("Textarea")),
34        KeyBinding::new("tab", Tab, Some("Textarea")),
35        KeyBinding::new("shift-tab", ShiftTab, Some("Textarea")),
36        #[cfg(target_os = "macos")]
37        KeyBinding::new("cmd-a", SelectAll, Some("Textarea")),
38        #[cfg(not(target_os = "macos"))]
39        KeyBinding::new("ctrl-a", SelectAll, Some("Textarea")),
40        #[cfg(target_os = "macos")]
41        KeyBinding::new("cmd-c", Copy, Some("Textarea")),
42        #[cfg(not(target_os = "macos"))]
43        KeyBinding::new("ctrl-c", Copy, Some("Textarea")),
44        #[cfg(target_os = "macos")]
45        KeyBinding::new("cmd-x", Cut, Some("Textarea")),
46        #[cfg(not(target_os = "macos"))]
47        KeyBinding::new("ctrl-x", Cut, Some("Textarea")),
48        #[cfg(target_os = "macos")]
49        KeyBinding::new("cmd-v", Paste, Some("Textarea")),
50        #[cfg(not(target_os = "macos"))]
51        KeyBinding::new("ctrl-v", Paste, Some("Textarea")),
52        KeyBinding::new("escape", Escape, Some("Textarea")),
53        #[cfg(target_os = "macos")]
54        KeyBinding::new("alt-left", WordLeft, Some("Textarea")),
55        #[cfg(target_os = "macos")]
56        KeyBinding::new("alt-right", WordRight, Some("Textarea")),
57        #[cfg(not(target_os = "macos"))]
58        KeyBinding::new("ctrl-left", WordLeft, Some("Textarea")),
59        #[cfg(not(target_os = "macos"))]
60        KeyBinding::new("ctrl-right", WordRight, Some("Textarea")),
61        #[cfg(target_os = "macos")]
62        KeyBinding::new("alt-shift-left", SelectWordLeft, Some("Textarea")),
63        #[cfg(target_os = "macos")]
64        KeyBinding::new("alt-shift-right", SelectWordRight, Some("Textarea")),
65        #[cfg(not(target_os = "macos"))]
66        KeyBinding::new("ctrl-shift-left", SelectWordLeft, Some("Textarea")),
67        #[cfg(not(target_os = "macos"))]
68        KeyBinding::new("ctrl-shift-right", SelectWordRight, Some("Textarea")),
69    ]);
70}
71
72actions!(
73    textarea_state,
74    [
75        Backspace,
76        Delete,
77        Left,
78        Right,
79        Up,
80        Down,
81        SelectLeft,
82        SelectRight,
83        SelectUp,
84        SelectDown,
85        SelectAll,
86        Home,
87        End,
88        Copy,
89        Cut,
90        Paste,
91        Enter,
92        ShiftEnter,
93        Tab,
94        ShiftTab,
95        Escape,
96        WordLeft,
97        WordRight,
98        SelectWordLeft,
99        SelectWordRight,
100    ]
101);
102
103/// Events emitted by TextareaState
104#[derive(Clone, Debug)]
105pub enum TextareaEvent {
106    Change,
107    Focus,
108    Blur,
109    Enter,
110    ShiftEnter,
111    Tab,
112    ShiftTab,
113    Validate(Result<(), ValidationError>),
114}
115
116impl EventEmitter<TextareaEvent> for TextareaState {}
117
118/// Multi-line text input state with cursor management
119pub struct TextareaState {
120    focus_handle: FocusHandle,
121    pub scroll_handle: ScrollHandle,
122    pub content: SharedString,
123    pub placeholder: SharedString,
124    pub disabled: bool,
125    pub initialized: bool,
126    selected_range: Range<usize>,
127    selection_reversed: bool,
128    marked_range: Option<Range<usize>>,
129    last_layouts: Vec<WrappedLine>,
130    last_bounds: Option<Bounds<Pixels>>,
131    last_visual_line_count: usize,
132    last_line_height: Pixels,
133    is_selecting: bool,
134    was_focused: bool,
135    cursor_visible: bool,
136    _blink_task: Option<Task<()>>,
137    event_subscription: Option<Subscription>,
138
139    // Validation (shared machinery with `InputState`)
140    pub validation_rules: ValidationRules,
141    pub validation_error: Option<ValidationError>,
142    pub success_message: Option<SharedString>,
143    pub validate_on_blur: bool,
144    pub validate_on_change: bool,
145}
146
147#[derive(Clone, Copy)]
148struct VisualLineInfo {
149    logical_line_idx: usize,
150    logical_start: usize,
151    local_start: usize,
152    local_end: usize,
153    origin_y: Pixels,
154}
155
156impl TextareaState {
157    pub fn new(cx: &mut Context<Self>) -> Self {
158        Self {
159            focus_handle: cx.focus_handle(),
160            scroll_handle: ScrollHandle::new(),
161            content: "".into(),
162            placeholder: "".into(),
163            disabled: false,
164            initialized: false,
165            selected_range: 0..0,
166            selection_reversed: false,
167            marked_range: None,
168            last_layouts: Vec::new(),
169            last_bounds: None,
170            last_visual_line_count: 1,
171            last_line_height: px(20.0),
172            is_selecting: false,
173            was_focused: false,
174            cursor_visible: true,
175            _blink_task: None,
176            event_subscription: None,
177            validation_rules: ValidationRules::default(),
178            validation_error: None,
179            success_message: None,
180            validate_on_blur: true,
181            validate_on_change: false,
182        }
183    }
184
185    pub(super) fn replace_event_subscription(&mut self, subscription: Option<Subscription>) {
186        self.event_subscription = subscription;
187    }
188
189    /// Set the placeholder text.
190    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
191        self.placeholder = placeholder.into();
192        self
193    }
194
195    /// Set the initial value.
196    ///
197    /// Equivalent to assigning `content` directly, but leaves the caret at
198    /// the end of the text. This is raw initialization: it bypasses
199    /// validation rules and `max_length` truncation. To replace the value
200    /// later with truncation, validation, and a `Change` event, use
201    /// [`TextareaState::set_value`].
202    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
203        self.content = value.into();
204        let len = self.content.len();
205        self.selected_range = len..len;
206        self
207    }
208
209    /// Set whether user interaction is disabled.
210    pub fn disabled(mut self, disabled: bool) -> Self {
211        self.disabled = disabled;
212        self
213    }
214
215    pub fn content(&self) -> &str {
216        &self.content
217    }
218
219    pub fn visual_line_count_for_layout(&self) -> usize {
220        self.visual_line_count()
221    }
222
223    pub fn set_value(
224        &mut self,
225        value: impl Into<SharedString>,
226        _window: &mut Window,
227        cx: &mut Context<Self>,
228    ) {
229        let value = self.truncate_to_max_length(value.into());
230        if self.content != value {
231            self.content = value;
232            let len = self.content.len();
233            self.selected_range = len..len;
234            self.marked_range.take();
235            self.selection_reversed = false;
236            self.invalidate_layout_cache();
237            if self.should_auto_validate(self.validate_on_change) {
238                self.validate(cx).ok();
239            }
240            cx.emit(TextareaEvent::Change);
241            cx.notify();
242        }
243    }
244
245    /// Whether an IME composition is currently in progress.
246    ///
247    /// While composing, the in-flight text is displayed but not committed:
248    /// validation and `max_length` truncation only apply on commit.
249    pub fn is_composing(&self) -> bool {
250        // An empty marked range is still an active composition.
251        self.marked_range.is_some()
252    }
253
254    /// Number of characters in the in-flight IME composition (0 when not
255    /// composing). `content()` includes these characters, so the committed
256    /// length is `content().chars().count() - composition_char_count()`.
257    pub fn composition_char_count(&self) -> usize {
258        // `content` is a public field: a direct external write can leave
259        // `marked_range` stale, so slice defensively instead of panicking.
260        self.marked_range
261            .as_ref()
262            .and_then(|range| self.content.get(range.clone()))
263            .map(|marked| marked.chars().count())
264            .unwrap_or(0)
265    }
266
267    /// Set validation rules
268    pub fn validation_rules(mut self, rules: ValidationRules) -> Self {
269        self.validation_rules = rules;
270        self
271    }
272
273    /// Set minimum length
274    pub fn min_length(mut self, min: usize) -> Self {
275        self.validation_rules.min_length = Some(min);
276        self
277    }
278
279    /// Set maximum length
280    pub fn max_length(mut self, max: usize) -> Self {
281        self.validation_rules.max_length = Some(max);
282        self
283    }
284
285    /// Mark field as required
286    pub fn required(mut self, required: bool) -> Self {
287        self.validation_rules.required = required;
288        self
289    }
290
291    fn truncate_to_max_length(&self, value: SharedString) -> SharedString {
292        self.validation_rules
293            .max_length
294            .map(|max_length| value.chars().take(max_length).collect::<String>().into())
295            .unwrap_or(value)
296    }
297
298    /// Whether automatic (blur/change-triggered) validation should run.
299    ///
300    /// Automatic validation only kicks in once rules exist, so a plain
301    /// textarea never sprouts a "Valid input" footer just because focus left
302    /// the field. Explicit `validate()` calls (e.g. from `Form`) always run.
303    fn should_auto_validate(&self, enabled: bool) -> bool {
304        let rules = &self.validation_rules;
305        enabled
306            && (rules.required
307                || rules.min_length.is_some()
308                || rules.max_length.is_some()
309                || rules.pattern.is_some()
310                || rules.custom_validator.is_some())
311    }
312
313    /// Validate the current value against the configured rules.
314    pub fn validate(&mut self, cx: &mut Context<Self>) -> Result<(), ValidationError> {
315        let value = self.committed_content();
316
317        if let Some(result) =
318            validation::check_required_empty(self.validation_rules.required, &value, None)
319        {
320            if result.is_ok() {
321                // Optional empty value: clear any stale messages without
322                // reporting success.
323                self.validation_error = None;
324                self.success_message = None;
325                cx.emit(TextareaEvent::Validate(Ok(())));
326                cx.notify();
327                return Ok(());
328            }
329            return self.finish_validation(result, cx);
330        }
331
332        let result = validation::check_constraints(&self.validation_rules, &value, None);
333        self.finish_validation(result, cx)
334    }
335
336    fn finish_validation(
337        &mut self,
338        result: Result<(), ValidationError>,
339        cx: &mut Context<Self>,
340    ) -> Result<(), ValidationError> {
341        match &result {
342            Ok(()) => {
343                self.validation_error = None;
344                self.success_message = Some("Valid input".into());
345            }
346            Err(error) => {
347                self.validation_error = Some(error.clone());
348            }
349        }
350        cx.emit(TextareaEvent::Validate(result.clone()));
351        cx.notify();
352        result
353    }
354
355    fn committed_content(&self) -> String {
356        let Some(range) = self.marked_range.as_ref() else {
357            return self.content.to_string();
358        };
359        let Some(_) = self.content.get(range.clone()) else {
360            return self.content.to_string();
361        };
362        let mut committed = self.content.to_string();
363        committed.replace_range(range.clone(), "");
364        committed
365    }
366
367    // ── Line helpers ────────────────────────────────────────────────
368
369    /// Returns byte offsets where each line starts (always includes 0).
370    fn line_start_offsets(&self) -> Vec<usize> {
371        let mut offsets = vec![0usize];
372        for (i, ch) in self.content.char_indices() {
373            if ch == '\n' {
374                offsets.push(i + ch.len_utf8());
375            }
376        }
377        offsets
378    }
379
380    fn logical_line_for_offset(&self, offset: usize) -> usize {
381        let starts = self.line_start_offsets();
382        let mut line = 0;
383        for (i, &start) in starts.iter().enumerate() {
384            if start <= offset {
385                line = i;
386            } else {
387                break;
388            }
389        }
390        line
391    }
392
393    /// Get the byte offset of the start of the line containing `offset`.
394    fn line_start_for_offset(&self, offset: usize) -> usize {
395        let starts = self.line_start_offsets();
396        let line = self.logical_line_for_offset(offset);
397        starts[line]
398    }
399
400    /// Get the byte offset of the end of the line containing `offset` (before \n).
401    fn line_end_for_offset(&self, offset: usize) -> usize {
402        let starts = self.line_start_offsets();
403        let line = self.logical_line_for_offset(offset);
404        if line + 1 < starts.len() {
405            starts[line + 1] - 1
406        } else {
407            self.content.len()
408        }
409    }
410
411    fn visual_line_count(&self) -> usize {
412        self.last_visual_line_count.max(1)
413    }
414
415    /// Split content into lines (the text of each line, without trailing \n).
416    fn lines(&self) -> Vec<&str> {
417        if self.content.is_empty() {
418            return vec![""];
419        }
420        let s: &str = &self.content;
421        let mut result: Vec<&str> = s.split('\n').collect();
422        // If content ends with \n, split produces an extra empty string which is correct
423        if result.is_empty() {
424            result.push("");
425        }
426        result
427    }
428
429    fn visual_lines_for_layouts(
430        &self,
431        layouts: &[WrappedLine],
432        line_height: Pixels,
433    ) -> Vec<VisualLineInfo> {
434        let starts = self.line_start_offsets();
435        let mut visual_lines = Vec::new();
436        let mut current_y = Pixels::ZERO;
437
438        for (logical_line_idx, wrapped_line) in layouts.iter().enumerate() {
439            let logical_start = starts.get(logical_line_idx).copied().unwrap_or(0);
440            let mut local_start = 0;
441            let mut visual_line_idx = 0;
442
443            for wrap_boundary in wrapped_line.wrap_boundaries() {
444                let glyph =
445                    &wrapped_line.runs()[wrap_boundary.run_ix].glyphs[wrap_boundary.glyph_ix];
446                let local_end = glyph.index;
447                visual_lines.push(VisualLineInfo {
448                    logical_line_idx,
449                    logical_start,
450                    local_start,
451                    local_end,
452                    origin_y: current_y + line_height * visual_line_idx as f32,
453                });
454                local_start = local_end;
455                visual_line_idx += 1;
456            }
457
458            visual_lines.push(VisualLineInfo {
459                logical_line_idx,
460                logical_start,
461                local_start,
462                local_end: wrapped_line.text.len(),
463                origin_y: current_y + line_height * visual_line_idx as f32,
464            });
465
466            current_y += line_height * (visual_line_idx + 1) as f32;
467        }
468
469        if visual_lines.is_empty() {
470            visual_lines.push(VisualLineInfo {
471                logical_line_idx: 0,
472                logical_start: 0,
473                local_start: 0,
474                local_end: 0,
475                origin_y: Pixels::ZERO,
476            });
477        }
478
479        visual_lines
480    }
481
482    fn visual_lines(&self, line_height: Pixels) -> Vec<VisualLineInfo> {
483        self.visual_lines_for_layouts(&self.last_layouts, line_height)
484    }
485
486    fn point_for_offset_in_layouts(
487        &self,
488        layouts: &[WrappedLine],
489        offset: usize,
490        line_height: Pixels,
491    ) -> Option<(usize, Point<Pixels>)> {
492        let logical_line_idx = self.logical_line_for_offset(offset);
493        let logical_start = *self.line_start_offsets().get(logical_line_idx)?;
494        let wrapped_line = layouts.get(logical_line_idx)?;
495        let local_offset = offset
496            .saturating_sub(logical_start)
497            .min(wrapped_line.text.len());
498        wrapped_line
499            .position_for_index(local_offset, line_height)
500            .map(|point| (logical_line_idx, point))
501    }
502
503    fn point_for_offset(
504        &self,
505        offset: usize,
506        line_height: Pixels,
507    ) -> Option<(usize, Point<Pixels>)> {
508        self.point_for_offset_in_layouts(&self.last_layouts, offset, line_height)
509    }
510
511    fn vertical_navigation_target(
512        &self,
513        offset: usize,
514        delta: isize,
515        line_height: Pixels,
516    ) -> Option<usize> {
517        if self.last_layouts.is_empty() {
518            return None;
519        }
520
521        let (logical_line_idx, cursor_point) = self.point_for_offset(offset, line_height)?;
522        let visual_lines = self.visual_lines(line_height);
523        let logical_line_origin_y = visual_lines
524            .iter()
525            .find(|line| line.logical_line_idx == logical_line_idx)?
526            .origin_y;
527        let cursor_visual_y = logical_line_origin_y + cursor_point.y;
528        let current_visual_line_idx = visual_lines.iter().position(|line| {
529            cursor_visual_y >= line.origin_y && cursor_visual_y < line.origin_y + line_height
530        })?;
531
532        let target_visual_line_idx = current_visual_line_idx as isize + delta;
533        if target_visual_line_idx < 0 || target_visual_line_idx >= visual_lines.len() as isize {
534            return None;
535        }
536
537        let target_line = visual_lines[target_visual_line_idx as usize];
538        let target_wrapped_line = self.last_layouts.get(target_line.logical_line_idx)?;
539        let logical_line_origin_y = visual_lines
540            .iter()
541            .find(|line| line.logical_line_idx == target_line.logical_line_idx)?
542            .origin_y;
543        let target_local_y = target_line.origin_y - logical_line_origin_y;
544        let target_local_x = cursor_point.x;
545        let target_local_offset = target_wrapped_line
546            .closest_index_for_position(gpui::point(target_local_x, target_local_y), line_height)
547            .unwrap_or_else(|boundary| boundary);
548        Some(target_line.logical_start + target_local_offset)
549    }
550
551    // ── Cursor / Selection ──────────────────────────────────────────
552
553    fn cursor_offset(&self) -> usize {
554        text_util::cursor_offset(&self.selected_range, self.selection_reversed)
555    }
556
557    fn move_to(&mut self, offset: usize, cx: &mut Context<Self>) {
558        let offset = self.clamp_offset(offset);
559        self.selected_range = offset..offset;
560        self.selection_reversed = false;
561        self.reset_blink(cx);
562        cx.notify();
563    }
564
565    fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
566        let offset = self.clamp_offset(offset);
567        (self.selected_range, self.selection_reversed) = text_util::extend_selection(
568            self.selected_range.clone(),
569            self.selection_reversed,
570            offset,
571        );
572        self.reset_blink(cx);
573        cx.notify();
574    }
575
576    fn clamp_offset(&self, offset: usize) -> usize {
577        text_util::clamp_offset(&self.content, offset)
578    }
579
580    // ── Grapheme boundaries ─────────────────────────────────────────
581
582    fn previous_boundary(&self, offset: usize) -> usize {
583        text_util::previous_grapheme_boundary(&self.content, offset)
584    }
585
586    fn next_boundary(&self, offset: usize) -> usize {
587        text_util::next_grapheme_boundary(&self.content, offset)
588    }
589
590    fn previous_word_boundary(&self, offset: usize) -> usize {
591        text_util::previous_word_boundary(&self.content, offset)
592    }
593
594    fn next_word_boundary(&self, offset: usize) -> usize {
595        text_util::next_word_boundary(&self.content, offset)
596    }
597
598    // ── UTF-16 conversion (for EntityInputHandler) ──────────────────
599
600    fn offset_to_utf16(&self, offset: usize) -> usize {
601        crate::capabilities::controls::text_util::offset_to_utf16(&self.content, offset)
602    }
603
604    fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
605        crate::capabilities::controls::text_util::range_to_utf16(&self.content, range)
606    }
607
608    fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
609        crate::capabilities::controls::text_util::range_from_utf16(&self.content, range_utf16)
610    }
611
612    // ── Layout cache ────────────────────────────────────────────────
613
614    fn invalidate_layout_cache(&mut self) {
615        self.last_layouts.clear();
616        self.last_bounds = None;
617        self.last_visual_line_count = 1;
618    }
619
620    // ── Blink ───────────────────────────────────────────────────────
621
622    fn start_blink(&mut self, cx: &mut Context<Self>) {
623        self._blink_task = None;
624        self.cursor_visible = true;
625        self._blink_task = Some(edit::spawn_caret_blink(cx, |this, cx| {
626            this.cursor_visible = !this.cursor_visible;
627            cx.notify();
628        }));
629    }
630
631    fn stop_blink(&mut self) {
632        self._blink_task = None;
633        self.cursor_visible = true;
634    }
635
636    fn reset_blink(&mut self, cx: &mut Context<Self>) {
637        self.stop_blink();
638        self.start_blink(cx);
639    }
640
641    fn sync_focus_state(&mut self, is_focused: bool, _window: &mut Window, cx: &mut Context<Self>) {
642        if self.was_focused == is_focused {
643            return;
644        }
645
646        self.was_focused = is_focused;
647        if is_focused {
648            self.start_blink(cx);
649            cx.emit(TextareaEvent::Focus);
650        } else {
651            self.stop_blink();
652            self.is_selecting = false;
653            if self.should_auto_validate(self.validate_on_blur) {
654                self.validate(cx).ok();
655            }
656            cx.emit(TextareaEvent::Blur);
657        }
658        cx.notify();
659    }
660
661    // ── Mouse ───────────────────────────────────────────────────────
662
663    fn on_mouse_down(
664        &mut self,
665        event: &MouseDownEvent,
666        _window: &mut Window,
667        cx: &mut Context<Self>,
668    ) {
669        self.is_selecting = true;
670        let idx = self.index_for_mouse_position(event.position);
671        if event.click_count == 2 {
672            let start = self.previous_word_boundary(idx);
673            let end = self.next_word_boundary(idx);
674            self.selected_range = start..end;
675            self.selection_reversed = false;
676            self.reset_blink(cx);
677            cx.notify();
678        } else if event.modifiers.shift {
679            self.select_to(idx, cx);
680        } else {
681            self.move_to(idx, cx);
682        }
683    }
684
685    fn on_mouse_up(&mut self, _: &MouseUpEvent, _: &mut Window, _cx: &mut Context<Self>) {
686        self.is_selecting = false;
687    }
688
689    fn on_mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {
690        if self.is_selecting {
691            let idx = self.index_for_mouse_position(event.position);
692            self.select_to(idx, cx);
693        }
694    }
695
696    fn index_for_mouse_position(&self, position: Point<Pixels>) -> usize {
697        if self.content.is_empty() {
698            return 0;
699        }
700        let Some(bounds) = self.last_bounds.as_ref() else {
701            return 0;
702        };
703        if self.last_layouts.is_empty() {
704            return 0;
705        }
706
707        let relative_y = position.y - bounds.top();
708        if relative_y <= Pixels::ZERO {
709            return 0;
710        }
711        if position.y >= bounds.bottom() {
712            return self.content.len();
713        }
714
715        let line_height = self.last_line_height;
716        let visual_lines = self.visual_lines(line_height);
717        let relative_x = (position.x - bounds.left()).max(Pixels::ZERO);
718
719        for visual_line in &visual_lines {
720            if relative_y >= visual_line.origin_y && relative_y < visual_line.origin_y + line_height
721            {
722                let Some(wrapped_line) = self.last_layouts.get(visual_line.logical_line_idx) else {
723                    return self.content.len();
724                };
725                let logical_line_origin_y = visual_lines
726                    .iter()
727                    .find(|line| line.logical_line_idx == visual_line.logical_line_idx)
728                    .map(|line| line.origin_y)
729                    .unwrap_or(Pixels::ZERO);
730                let local_y = relative_y - logical_line_origin_y;
731                let local_offset = wrapped_line
732                    .closest_index_for_position(gpui::point(relative_x, local_y), line_height)
733                    .unwrap_or_else(|boundary| boundary);
734                return visual_line.logical_start + local_offset;
735            }
736        }
737
738        self.content.len()
739    }
740
741    // ── Action handlers ─────────────────────────────────────────────
742
743    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
744        if self.selected_range.is_empty() {
745            self.select_to(self.previous_boundary(self.cursor_offset()), cx);
746        }
747        self.replace_text_in_range(None, "", window, cx);
748    }
749
750    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
751        if self.selected_range.is_empty() {
752            self.select_to(self.next_boundary(self.cursor_offset()), cx);
753        }
754        self.replace_text_in_range(None, "", window, cx);
755    }
756
757    pub fn left(&mut self, _: &Left, _: &mut Window, cx: &mut Context<Self>) {
758        if self.selected_range.is_empty() {
759            self.move_to(self.previous_boundary(self.cursor_offset()), cx);
760        } else {
761            self.move_to(self.selected_range.start, cx);
762        }
763    }
764
765    pub fn right(&mut self, _: &Right, _: &mut Window, cx: &mut Context<Self>) {
766        if self.selected_range.is_empty() {
767            self.move_to(self.next_boundary(self.cursor_offset()), cx);
768        } else {
769            self.move_to(self.selected_range.end, cx);
770        }
771    }
772
773    pub fn up(&mut self, _: &Up, _: &mut Window, cx: &mut Context<Self>) {
774        if !self.selected_range.is_empty() {
775            self.move_to(self.selected_range.start, cx);
776            return;
777        }
778        let line_height = self.last_line_height;
779        if let Some(new_offset) =
780            self.vertical_navigation_target(self.cursor_offset(), -1, line_height)
781        {
782            self.move_to(new_offset, cx);
783        }
784    }
785
786    pub fn down(&mut self, _: &Down, _: &mut Window, cx: &mut Context<Self>) {
787        if !self.selected_range.is_empty() {
788            self.move_to(self.selected_range.end, cx);
789            return;
790        }
791        let line_height = self.last_line_height;
792        if let Some(new_offset) =
793            self.vertical_navigation_target(self.cursor_offset(), 1, line_height)
794        {
795            self.move_to(new_offset, cx);
796        }
797    }
798
799    pub fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
800        self.select_to(self.previous_boundary(self.cursor_offset()), cx);
801    }
802
803    pub fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
804        self.select_to(self.next_boundary(self.cursor_offset()), cx);
805    }
806
807    pub fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
808        let line_height = self.last_line_height;
809        if let Some(new_offset) =
810            self.vertical_navigation_target(self.cursor_offset(), -1, line_height)
811        {
812            self.select_to(new_offset, cx);
813        }
814    }
815
816    pub fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
817        let line_height = self.last_line_height;
818        if let Some(new_offset) =
819            self.vertical_navigation_target(self.cursor_offset(), 1, line_height)
820        {
821            self.select_to(new_offset, cx);
822        }
823    }
824
825    pub fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
826        self.selected_range = 0..self.content.len();
827        self.selection_reversed = false;
828        self.reset_blink(cx);
829        cx.notify();
830    }
831
832    pub fn home(&mut self, _: &Home, _: &mut Window, cx: &mut Context<Self>) {
833        let line_start = self.line_start_for_offset(self.cursor_offset());
834        self.move_to(line_start, cx);
835    }
836
837    pub fn end(&mut self, _: &End, _: &mut Window, cx: &mut Context<Self>) {
838        let line_end = self.line_end_for_offset(self.cursor_offset());
839        self.move_to(line_end, cx);
840    }
841
842    pub fn word_left(&mut self, _: &WordLeft, _: &mut Window, cx: &mut Context<Self>) {
843        let offset = self.previous_word_boundary(self.cursor_offset());
844        if self.selected_range.is_empty() {
845            self.move_to(offset, cx);
846        } else {
847            self.move_to(self.selected_range.start.min(offset), cx);
848        }
849    }
850
851    pub fn word_right(&mut self, _: &WordRight, _: &mut Window, cx: &mut Context<Self>) {
852        let offset = self.next_word_boundary(self.cursor_offset());
853        if self.selected_range.is_empty() {
854            self.move_to(offset, cx);
855        } else {
856            self.move_to(self.selected_range.end.max(offset), cx);
857        }
858    }
859
860    pub fn select_word_left(&mut self, _: &SelectWordLeft, _: &mut Window, cx: &mut Context<Self>) {
861        self.select_to(self.previous_word_boundary(self.cursor_offset()), cx);
862    }
863
864    pub fn select_word_right(
865        &mut self,
866        _: &SelectWordRight,
867        _: &mut Window,
868        cx: &mut Context<Self>,
869    ) {
870        self.select_to(self.next_word_boundary(self.cursor_offset()), cx);
871    }
872
873    pub fn enter(&mut self, _: &Enter, window: &mut Window, cx: &mut Context<Self>) {
874        self.replace_text_in_range(None, "\n", window, cx);
875        cx.emit(TextareaEvent::Enter);
876    }
877
878    pub fn shift_enter(&mut self, _: &ShiftEnter, _window: &mut Window, cx: &mut Context<Self>) {
879        cx.emit(TextareaEvent::ShiftEnter);
880    }
881
882    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
883        self.replace_text_in_range(None, "    ", window, cx);
884        cx.emit(TextareaEvent::Tab);
885    }
886
887    pub fn shift_tab(&mut self, _: &ShiftTab, _window: &mut Window, cx: &mut Context<Self>) {
888        cx.emit(TextareaEvent::ShiftTab);
889    }
890
891    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
892        if !self.selected_range.is_empty() {
893            cx.write_to_clipboard(ClipboardItem::new_string(
894                self.content[self.selected_range.clone()].to_string(),
895            ));
896        }
897    }
898
899    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
900        if !self.selected_range.is_empty() {
901            cx.write_to_clipboard(ClipboardItem::new_string(
902                self.content[self.selected_range.clone()].to_string(),
903            ));
904            self.replace_text_in_range(None, "", window, cx);
905        }
906    }
907
908    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
909        if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) {
910            self.replace_text_in_range(None, &text, window, cx);
911        }
912    }
913
914    pub fn escape(&mut self, _: &Escape, _window: &mut Window, cx: &mut Context<Self>) {
915        self.selected_range = self.content.len()..self.content.len();
916        cx.notify();
917    }
918}
919
920// ── EntityInputHandler ──────────────────────────────────────────────
921
922impl EntityInputHandler for TextareaState {
923    fn text_for_range(
924        &mut self,
925        range_utf16: Range<usize>,
926        actual_range: &mut Option<Range<usize>>,
927        _window: &mut Window,
928        _cx: &mut Context<Self>,
929    ) -> Option<String> {
930        let range = self.range_from_utf16(&range_utf16);
931        actual_range.replace(self.range_to_utf16(&range));
932        Some(self.content[range].to_string())
933    }
934
935    fn selected_text_range(
936        &mut self,
937        _ignore_disabled_input: bool,
938        _window: &mut Window,
939        _cx: &mut Context<Self>,
940    ) -> Option<UTF16Selection> {
941        Some(UTF16Selection {
942            range: self.range_to_utf16(&self.selected_range),
943            reversed: self.selection_reversed,
944        })
945    }
946
947    fn marked_text_range(
948        &self,
949        _window: &mut Window,
950        _cx: &mut Context<Self>,
951    ) -> Option<Range<usize>> {
952        self.marked_range
953            .as_ref()
954            .map(|range| self.range_to_utf16(range))
955    }
956
957    fn unmark_text(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
958        self.marked_range = None;
959        self.invalidate_layout_cache();
960        if self.should_auto_validate(self.validate_on_change) {
961            self.validate(cx).ok();
962        }
963    }
964
965    fn replace_text_in_range(
966        &mut self,
967        range_utf16: Option<Range<usize>>,
968        new_text: &str,
969        window: &mut Window,
970        cx: &mut Context<Self>,
971    ) {
972        let had_marked_text = self.marked_range.is_some();
973        let range = range_utf16
974            .as_ref()
975            .map(|r| self.range_from_utf16(r))
976            .or(self.marked_range.clone())
977            .unwrap_or(self.selected_range.clone());
978
979        let new_text = if let Some(max_length) = self.validation_rules.max_length {
980            let retained_chars =
981                self.content.chars().count() - self.content[range.clone()].chars().count();
982            let allowed_chars = max_length.saturating_sub(retained_chars);
983            new_text.chars().take(allowed_chars).collect::<String>()
984        } else {
985            new_text.to_owned()
986        };
987
988        let next_content: SharedString =
989            (self.content[0..range.start].to_owned() + &new_text + &self.content[range.end..])
990                .into();
991        let content_changed = self.content != next_content;
992        self.content = next_content;
993        self.selected_range = range.start + new_text.len()..range.start + new_text.len();
994        self.marked_range.take();
995        self.selection_reversed = false;
996        if self.focus_handle.is_focused(window) {
997            self.reset_blink(cx);
998        }
999        self.invalidate_layout_cache();
1000        if (content_changed || had_marked_text)
1001            && self.should_auto_validate(self.validate_on_change)
1002        {
1003            self.validate(cx).ok();
1004        }
1005        if content_changed || had_marked_text {
1006            cx.emit(TextareaEvent::Change);
1007        }
1008        cx.notify();
1009    }
1010
1011    fn replace_and_mark_text_in_range(
1012        &mut self,
1013        range_utf16: Option<Range<usize>>,
1014        new_text: &str,
1015        new_selected_range_utf16: Option<Range<usize>>,
1016        window: &mut Window,
1017        cx: &mut Context<Self>,
1018    ) {
1019        let range = range_utf16
1020            .as_ref()
1021            .map(|r| self.range_from_utf16(r))
1022            .or(self.marked_range.clone())
1023            .unwrap_or(self.selected_range.clone());
1024
1025        self.content =
1026            (self.content[0..range.start].to_owned() + new_text + &self.content[range.end..])
1027                .into();
1028        if !new_text.is_empty() {
1029            self.marked_range = Some(range.start..range.start + new_text.len());
1030        } else {
1031            self.marked_range = None;
1032        }
1033        self.selected_range = text_util::selection_after_replacement(
1034            new_text,
1035            new_selected_range_utf16.as_ref(),
1036            range.start,
1037        );
1038
1039        self.selection_reversed = false;
1040        if self.focus_handle.is_focused(window) {
1041            self.reset_blink(cx);
1042        }
1043        self.invalidate_layout_cache();
1044        cx.notify();
1045    }
1046
1047    fn bounds_for_range(
1048        &mut self,
1049        range_utf16: Range<usize>,
1050        bounds: Bounds<Pixels>,
1051        _window: &mut Window,
1052        _cx: &mut Context<Self>,
1053    ) -> Option<Bounds<Pixels>> {
1054        if self.last_layouts.is_empty() {
1055            return None;
1056        }
1057
1058        let range = self.range_from_utf16(&range_utf16);
1059        let line_height = bounds.size.height / self.visual_line_count() as f32;
1060        let visual_lines = self.visual_lines(line_height);
1061
1062        let (start_logical_line_idx, start_point) =
1063            self.point_for_offset(range.start, line_height)?;
1064        let (end_logical_line_idx, end_point) = self.point_for_offset(range.end, line_height)?;
1065        let start_logical_origin_y = visual_lines
1066            .iter()
1067            .find(|line| line.logical_line_idx == start_logical_line_idx)?
1068            .origin_y;
1069        let end_logical_origin_y = visual_lines
1070            .iter()
1071            .find(|line| line.logical_line_idx == end_logical_line_idx)?
1072            .origin_y;
1073
1074        Some(Bounds::from_corners(
1075            point(
1076                bounds.left() + start_point.x,
1077                bounds.top() + start_logical_origin_y + start_point.y,
1078            ),
1079            point(
1080                bounds.left() + end_point.x,
1081                bounds.top() + end_logical_origin_y + end_point.y + line_height,
1082            ),
1083        ))
1084    }
1085
1086    fn character_index_for_point(
1087        &mut self,
1088        point: Point<Pixels>,
1089        _window: &mut Window,
1090        _cx: &mut Context<Self>,
1091    ) -> Option<usize> {
1092        let bounds = self.last_bounds.as_ref()?;
1093        bounds.localize(&point)?;
1094        if self.last_layouts.is_empty() {
1095            return None;
1096        }
1097
1098        let byte_offset = self.index_for_mouse_position(point);
1099        Some(self.offset_to_utf16(byte_offset))
1100    }
1101}
1102
1103// ── Render ───────────────────────────────────────────────────────────
1104
1105impl Render for TextareaState {
1106    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1107        let entity = cx.entity();
1108        div()
1109            .w_full()
1110            .on_mouse_down(MouseButton::Left, {
1111                let entity = entity.clone();
1112                move |event: &MouseDownEvent, window: &mut Window, cx: &mut App| {
1113                    entity.update(cx, |state, cx| {
1114                        state.on_mouse_down(event, window, cx);
1115                    });
1116                }
1117            })
1118            .on_mouse_up(MouseButton::Left, {
1119                let entity = entity.clone();
1120                move |event: &MouseUpEvent, window: &mut Window, cx: &mut App| {
1121                    entity.update(cx, |state, cx| {
1122                        state.on_mouse_up(event, window, cx);
1123                    });
1124                }
1125            })
1126            .on_mouse_up_out(MouseButton::Left, {
1127                let entity = entity.clone();
1128                move |event: &MouseUpEvent, window: &mut Window, cx: &mut App| {
1129                    entity.update(cx, |state, cx| {
1130                        state.on_mouse_up(event, window, cx);
1131                    });
1132                }
1133            })
1134            .on_mouse_move({
1135                let entity = entity.clone();
1136                move |event: &MouseMoveEvent, window: &mut Window, cx: &mut App| {
1137                    entity.update(cx, |state, cx| {
1138                        state.on_mouse_move(event, window, cx);
1139                    });
1140                }
1141            })
1142            .child(TextareaTextElement {
1143                state: entity.clone(),
1144            })
1145    }
1146}
1147
1148impl Focusable for TextareaState {
1149    fn focus_handle(&self, _: &App) -> FocusHandle {
1150        self.focus_handle.clone()
1151    }
1152}
1153
1154// ── Custom Element for multi-line text rendering ─────────────────────
1155
1156struct TextareaTextElement {
1157    state: Entity<TextareaState>,
1158}
1159
1160struct TextareaPrepaintState {
1161    lines: Vec<WrappedLine>,
1162    cursor: Option<PaintQuad>,
1163    selections: Vec<PaintQuad>,
1164}
1165
1166impl IntoElement for TextareaTextElement {
1167    type Element = Self;
1168    fn into_element(self) -> Self::Element {
1169        self
1170    }
1171}
1172
1173impl Element for TextareaTextElement {
1174    type RequestLayoutState = ();
1175    type PrepaintState = TextareaPrepaintState;
1176
1177    fn id(&self) -> Option<ElementId> {
1178        None
1179    }
1180
1181    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
1182        None
1183    }
1184
1185    fn request_layout(
1186        &mut self,
1187        _id: Option<&GlobalElementId>,
1188        _inspector_id: Option<&InspectorElementId>,
1189        window: &mut Window,
1190        cx: &mut App,
1191    ) -> (LayoutId, Self::RequestLayoutState) {
1192        let state = self.state.read(cx);
1193        let line_count = state.visual_line_count();
1194        let line_height = window.line_height();
1195        let mut style = Style::default();
1196        style.size.width = relative(1.).into();
1197        style.size.height = (line_height * line_count as f32).into();
1198        (window.request_layout(style, [], cx), ())
1199    }
1200
1201    fn prepaint(
1202        &mut self,
1203        _id: Option<&GlobalElementId>,
1204        _inspector_id: Option<&InspectorElementId>,
1205        bounds: Bounds<Pixels>,
1206        _request_layout: &mut Self::RequestLayoutState,
1207        window: &mut Window,
1208        cx: &mut App,
1209    ) -> Self::PrepaintState {
1210        let input = self.state.read(cx);
1211        let text_style = window.text_style();
1212        let theme = use_theme(cx);
1213        let font_size = text_style.font_size.to_pixels(window.rem_size());
1214        let line_height = window.line_height();
1215
1216        let content_lines = input.lines();
1217        let starts = input.line_start_offsets();
1218        let selected_range = input.selected_range.clone();
1219        let cursor_offset = input.cursor_offset();
1220        let is_empty = input.content.is_empty();
1221        let placeholder = input.placeholder.clone();
1222        let marked_range = input.marked_range.clone();
1223        let wrap_width = Some(bounds.size.width.max(px(1.0)));
1224
1225        let mut wrapped_lines = Vec::with_capacity(content_lines.len().max(1));
1226        for (line_idx, line_text) in content_lines.iter().enumerate() {
1227            let (display_text, text_color) = if is_empty && line_idx == 0 {
1228                (placeholder.clone(), theme.tokens.muted_foreground)
1229            } else if is_empty {
1230                (SharedString::from(""), text_style.color)
1231            } else {
1232                (SharedString::from(line_text.to_string()), text_style.color)
1233            };
1234
1235            let base_run = TextRun {
1236                len: display_text.len(),
1237                font: text_style.font(),
1238                color: text_color,
1239                background_color: None,
1240                underline: None,
1241                strikethrough: None,
1242            };
1243
1244            // Handle IME marked range within this line
1245            let runs = if !is_empty {
1246                if let Some(ref marked) = marked_range {
1247                    let line_start = starts[line_idx];
1248                    let line_end = line_start + line_text.len();
1249                    let mark_start = marked.start.max(line_start).saturating_sub(line_start);
1250                    let mark_end = marked.end.min(line_end).saturating_sub(line_start);
1251                    if mark_start < mark_end && mark_start < display_text.len() {
1252                        vec![
1253                            TextRun {
1254                                len: mark_start,
1255                                ..base_run.clone()
1256                            },
1257                            TextRun {
1258                                len: mark_end - mark_start,
1259                                underline: Some(UnderlineStyle {
1260                                    color: Some(base_run.color),
1261                                    thickness: edit::IME_UNDERLINE_THICKNESS,
1262                                    wavy: false,
1263                                }),
1264                                ..base_run.clone()
1265                            },
1266                            TextRun {
1267                                len: display_text.len() - mark_end,
1268                                ..base_run.clone()
1269                            },
1270                        ]
1271                        .into_iter()
1272                        .filter(|r| r.len > 0)
1273                        .collect()
1274                    } else {
1275                        vec![base_run]
1276                    }
1277                } else {
1278                    vec![base_run]
1279                }
1280            } else {
1281                vec![base_run]
1282            };
1283
1284            let mut shaped = window
1285                .text_system()
1286                .shape_text(display_text, font_size, &runs, wrap_width, None)
1287                .unwrap_or_default();
1288            wrapped_lines.push(shaped.pop().unwrap_or_default());
1289        }
1290
1291        let visual_lines = input.visual_lines_for_layouts(&wrapped_lines, line_height);
1292        let mut cursor_quad = None;
1293        let mut selection_quads = Vec::new();
1294
1295        if selected_range.is_empty() {
1296            if let Some((logical_line_idx, cursor_point)) =
1297                input.point_for_offset_in_layouts(&wrapped_lines, cursor_offset, line_height)
1298            {
1299                let logical_line_origin_y = visual_lines
1300                    .iter()
1301                    .find(|line| line.logical_line_idx == logical_line_idx)
1302                    .map(|line| line.origin_y)
1303                    .unwrap_or(Pixels::ZERO);
1304                cursor_quad = Some(fill(
1305                    Bounds::new(
1306                        point(
1307                            bounds.left() + cursor_point.x,
1308                            bounds.top() + logical_line_origin_y + cursor_point.y,
1309                        ),
1310                        size(edit::CARET_WIDTH, line_height),
1311                    ),
1312                    theme.tokens.primary,
1313                ));
1314            }
1315        } else if !is_empty {
1316            for visual_line in &visual_lines {
1317                let visual_start = visual_line.logical_start + visual_line.local_start;
1318                let visual_end = visual_line.logical_start + visual_line.local_end;
1319                let overlaps_text =
1320                    selected_range.start < visual_end && selected_range.end > visual_start;
1321                let spans_newline = selected_range.end > visual_end
1322                    && visual_line.local_end
1323                        == wrapped_lines
1324                            .get(visual_line.logical_line_idx)
1325                            .map(|line| line.text.len())
1326                            .unwrap_or(0);
1327
1328                if !overlaps_text && !spans_newline {
1329                    continue;
1330                }
1331
1332                let Some(wrapped_line) = wrapped_lines.get(visual_line.logical_line_idx) else {
1333                    continue;
1334                };
1335                let local_start = selected_range
1336                    .start
1337                    .max(visual_start)
1338                    .saturating_sub(visual_line.logical_start)
1339                    .min(wrapped_line.text.len());
1340                let local_end = selected_range
1341                    .end
1342                    .min(visual_end)
1343                    .saturating_sub(visual_line.logical_start)
1344                    .min(wrapped_line.text.len());
1345                let Some(start_point) = wrapped_line.position_for_index(local_start, line_height)
1346                else {
1347                    continue;
1348                };
1349                let end_point = wrapped_line
1350                    .position_for_index(local_end, line_height)
1351                    .unwrap_or(start_point);
1352                let logical_line_origin_y = visual_lines
1353                    .iter()
1354                    .find(|line| line.logical_line_idx == visual_line.logical_line_idx)
1355                    .map(|line| line.origin_y)
1356                    .unwrap_or(Pixels::ZERO);
1357                let x_end = if spans_newline {
1358                    wrapped_line.width().max(end_point.x + px(4.0))
1359                } else {
1360                    end_point.x
1361                };
1362
1363                selection_quads.push(fill(
1364                    Bounds::from_corners(
1365                        point(
1366                            bounds.left() + start_point.x,
1367                            bounds.top() + logical_line_origin_y + start_point.y,
1368                        ),
1369                        point(
1370                            bounds.left() + x_end,
1371                            bounds.top() + logical_line_origin_y + end_point.y + line_height,
1372                        ),
1373                    ),
1374                    theme
1375                        .tokens
1376                        .primary
1377                        .opacity(edit::SELECTION_HIGHLIGHT_OPACITY),
1378                ));
1379            }
1380        }
1381        TextareaPrepaintState {
1382            lines: wrapped_lines,
1383            cursor: cursor_quad,
1384            selections: selection_quads,
1385        }
1386    }
1387
1388    fn paint(
1389        &mut self,
1390        _id: Option<&GlobalElementId>,
1391        _inspector_id: Option<&InspectorElementId>,
1392        bounds: Bounds<Pixels>,
1393        _request_layout: &mut Self::RequestLayoutState,
1394        prepaint: &mut Self::PrepaintState,
1395        window: &mut Window,
1396        cx: &mut App,
1397    ) {
1398        let focus_handle = self.state.read(cx).focus_handle.clone();
1399        let disabled = self.state.read(cx).disabled;
1400        let line_height = window.line_height();
1401
1402        // Register input handler — this is THE KEY to receiving keyboard input
1403        if !disabled {
1404            window.handle_input(
1405                &focus_handle,
1406                ElementInputHandler::new(bounds, self.state.clone()),
1407                cx,
1408            );
1409        }
1410
1411        // Paint selections
1412        for selection in prepaint.selections.drain(..) {
1413            window.paint_quad(selection);
1414        }
1415
1416        // Paint each line
1417        let lines = std::mem::take(&mut prepaint.lines);
1418        let mut painted_lines = Vec::with_capacity(lines.len());
1419        let mut current_y = Pixels::ZERO;
1420        for line in lines.into_iter() {
1421            let origin = point(bounds.left(), bounds.top() + current_y);
1422            let _ = line.paint(
1423                origin,
1424                line_height,
1425                TextAlign::default(),
1426                Some(bounds),
1427                window,
1428                cx,
1429            );
1430            current_y += line.size(line_height).height;
1431            painted_lines.push(line);
1432        }
1433
1434        // Paint cursor
1435        let is_focused = focus_handle.is_focused(window);
1436        if is_focused {
1437            let cursor_visible = self.state.read(cx).cursor_visible;
1438            if cursor_visible {
1439                if let Some(cursor) = prepaint.cursor.take() {
1440                    window.paint_quad(cursor);
1441                }
1442            }
1443        }
1444
1445        // Store layouts for hit-testing
1446        self.state.update(cx, |state, cx| {
1447            let visual_line_count = painted_lines
1448                .iter()
1449                .map(|line| line.wrap_boundaries().len() + 1)
1450                .sum::<usize>()
1451                .max(1);
1452            state.last_layouts = painted_lines;
1453            state.last_bounds = Some(bounds);
1454            state.last_line_height = line_height;
1455            if state.last_visual_line_count != visual_line_count {
1456                state.last_visual_line_count = visual_line_count;
1457                cx.notify();
1458            }
1459            state.sync_focus_state(is_focused, window, cx);
1460        });
1461    }
1462}
1463
1464/// Wire a bare [`TextareaState`] into a custom container with full keyboard
1465/// editing, using the same wiring the `Textarea` component applies to its
1466/// shell.
1467///
1468/// `TextareaState` renders only the text body (text, caret, selection, IME
1469/// underline). The editing keys are key bindings scoped to the `"Textarea"`
1470/// context and are attached by the `Textarea` component's container — a
1471/// container an application renders itself must reproduce that wiring, or
1472/// every editing key except plain text insertion silently does nothing.
1473/// This helper attaches:
1474///
1475/// - the `"Textarea"` key context the key bindings are filtered on,
1476/// - focus tracking for the state's focus handle and scroll tracking for
1477///   its scroll handle,
1478/// - click-to-focus and all 25 keyboard actions, unless the state is
1479///   [`TextareaState::disabled`].
1480///
1481/// The returned div is an unstyled, vertically scrollable container; style
1482/// it and add the state as its child:
1483///
1484/// ```rust,ignore
1485/// use fc_ui::components::textarea_state::wire_actions;
1486///
1487/// fn render(state: &Entity<TextareaState>, window: &mut Window, cx: &App) -> impl IntoElement {
1488///     wire_actions(state, window, cx)
1489///         .h(px(96.0))
1490///         .px(px(12.0))
1491///         .rounded(px(8.0))
1492///         .child(state.clone())
1493/// }
1494/// ```
1495///
1496/// The key bindings are registered by `components::textarea::init`, which
1497/// `fc_ui::init` calls at startup; applications that skip crate init
1498/// must call it themselves or no keystroke will match an action.
1499pub fn wire_actions(state: &Entity<TextareaState>, window: &mut Window, cx: &App) -> Stateful<Div> {
1500    let disabled = state.read(cx).disabled;
1501    let focus_handle = state.read(cx).focus_handle(cx);
1502    let scroll_handle = state.read(cx).scroll_handle.clone();
1503    let focus_handle_for_mouse = focus_handle.clone();
1504
1505    div()
1506        .id(("textarea", state.entity_id()))
1507        .key_context("Textarea")
1508        .track_focus(&focus_handle.tab_index(0).tab_stop(true))
1509        .track_scroll(&scroll_handle)
1510        .overflow_y_scroll()
1511        .when(!disabled, |this| {
1512            this.on_mouse_down(MouseButton::Left, move |_event, window, _cx| {
1513                window.focus(&focus_handle_for_mouse);
1514            })
1515            .on_action(window.listener_for(state, TextareaState::backspace))
1516            .on_action(window.listener_for(state, TextareaState::delete))
1517            .on_action(window.listener_for(state, TextareaState::left))
1518            .on_action(window.listener_for(state, TextareaState::right))
1519            .on_action(window.listener_for(state, TextareaState::up))
1520            .on_action(window.listener_for(state, TextareaState::down))
1521            .on_action(window.listener_for(state, TextareaState::select_left))
1522            .on_action(window.listener_for(state, TextareaState::select_right))
1523            .on_action(window.listener_for(state, TextareaState::select_up))
1524            .on_action(window.listener_for(state, TextareaState::select_down))
1525            .on_action(window.listener_for(state, TextareaState::select_all))
1526            .on_action(window.listener_for(state, TextareaState::home))
1527            .on_action(window.listener_for(state, TextareaState::end))
1528            .on_action(window.listener_for(state, TextareaState::copy))
1529            .on_action(window.listener_for(state, TextareaState::cut))
1530            .on_action(window.listener_for(state, TextareaState::paste))
1531            .on_action(window.listener_for(state, TextareaState::enter))
1532            .on_action(window.listener_for(state, TextareaState::shift_enter))
1533            .on_action(window.listener_for(state, TextareaState::tab))
1534            .on_action(window.listener_for(state, TextareaState::shift_tab))
1535            .on_action(window.listener_for(state, TextareaState::escape))
1536            .on_action(window.listener_for(state, TextareaState::word_left))
1537            .on_action(window.listener_for(state, TextareaState::word_right))
1538            .on_action(window.listener_for(state, TextareaState::select_word_left))
1539            .on_action(window.listener_for(state, TextareaState::select_word_right))
1540        })
1541}
1542
1543#[cfg(test)]
1544mod tests {
1545    use super::*;
1546    use crate::capabilities::foundation::theme::{install_theme, Theme};
1547
1548    struct TestView {
1549        state: Entity<TextareaState>,
1550    }
1551
1552    #[gpui::test]
1553    fn builders_configure_common_state_options() {
1554        let mut app = TestApp::new();
1555        app.update(|cx| install_theme(cx, Theme::light()));
1556        let state = app.update(|cx| {
1557            cx.new(|cx| {
1558                TextareaState::new(cx)
1559                    .value("hello")
1560                    .placeholder("p")
1561                    .disabled(true)
1562            })
1563        });
1564
1565        app.update(|cx| {
1566            let state = state.read(cx);
1567            assert_eq!(state.content(), "hello");
1568            assert_eq!(state.placeholder, "p");
1569            assert!(state.disabled);
1570        });
1571    }
1572
1573    impl Render for TestView {
1574        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1575            div()
1576        }
1577    }
1578
1579    #[gpui::test]
1580    fn word_left_moves_cursor_to_previous_word_boundary() {
1581        let mut app = TestApp::new();
1582        app.update(|cx| install_theme(cx, Theme::light()));
1583        let state = app.update(|cx| cx.new(TextareaState::new));
1584        let mut window = app.open_window(|_, _| TestView {
1585            state: state.clone(),
1586        });
1587
1588        let text = "foo bar baz";
1589        window.update(|view, window, cx| {
1590            view.state.update(cx, |state, cx| {
1591                state.set_value(text, window, cx);
1592                // set_value places cursor at end (11)
1593                state.word_left(&WordLeft, window, cx);
1594                assert_eq!(state.selected_range, 8..8, "should stop before baz");
1595                state.word_left(&WordLeft, window, cx);
1596                assert_eq!(state.selected_range, 4..4, "should stop before bar");
1597                state.word_left(&WordLeft, window, cx);
1598                assert_eq!(state.selected_range, 0..0, "should reach start");
1599            });
1600        });
1601    }
1602
1603    #[gpui::test]
1604    fn word_right_moves_cursor_to_next_word_boundary() {
1605        let mut app = TestApp::new();
1606        app.update(|cx| install_theme(cx, Theme::light()));
1607        let state = app.update(|cx| cx.new(TextareaState::new));
1608        let mut window = app.open_window(|_, _| TestView {
1609            state: state.clone(),
1610        });
1611
1612        window.update(|view, window, cx| {
1613            view.state.update(cx, |state, cx| {
1614                state.set_value("foo bar baz", window, cx);
1615                state.selected_range = 0..0;
1616                state.word_right(&WordRight, window, cx);
1617                assert_eq!(state.selected_range, 4..4, "should stop at bar start");
1618                state.word_right(&WordRight, window, cx);
1619                assert_eq!(state.selected_range, 8..8, "should stop at baz start");
1620                state.word_right(&WordRight, window, cx);
1621                assert_eq!(state.selected_range, 11..11, "should reach end");
1622            });
1623        });
1624    }
1625
1626    #[gpui::test]
1627    fn word_movement_handles_unicode() {
1628        let mut app = TestApp::new();
1629        app.update(|cx| install_theme(cx, Theme::light()));
1630        let state = app.update(|cx| cx.new(TextareaState::new));
1631        let mut window = app.open_window(|_, _| TestView {
1632            state: state.clone(),
1633        });
1634
1635        let text = "中文 test";
1636        window.update(|view, window, cx| {
1637            view.state.update(cx, |state, cx| {
1638                state.set_value(text, window, cx);
1639                // set_value places cursor at end (11)
1640                state.word_left(&WordLeft, window, cx);
1641                assert_eq!(state.selected_range, 7..7, "should stop before test");
1642                state.word_left(&WordLeft, window, cx);
1643                assert_eq!(state.selected_range, 0..0, "should reach start");
1644            });
1645        });
1646    }
1647
1648    #[gpui::test]
1649    fn grapheme_deletion_removes_whole_unicode_clusters() {
1650        let mut app = TestApp::new();
1651        app.update(|cx| install_theme(cx, Theme::light()));
1652        let state = app.update(|cx| cx.new(TextareaState::new));
1653        let mut window = app.open_window(|_, _| TestView {
1654            state: state.clone(),
1655        });
1656
1657        window.update(|view, window, cx| {
1658            view.state.update(cx, |state, cx| {
1659                state.set_value("a👩‍💻e\u{301}b", window, cx);
1660                state.backspace(&Backspace, window, cx);
1661                assert_eq!(state.content(), "a👩‍💻e\u{301}");
1662                assert_eq!(
1663                    state.selected_range,
1664                    state.content().len()..state.content().len()
1665                );
1666
1667                state.backspace(&Backspace, window, cx);
1668                assert_eq!(state.content(), "a👩‍💻");
1669                assert_eq!(
1670                    state.selected_range,
1671                    state.content().len()..state.content().len()
1672                );
1673
1674                state.selected_range = "a".len().."a".len();
1675                state.selection_reversed = false;
1676                state.delete(&Delete, window, cx);
1677                assert_eq!(state.content(), "a");
1678                assert_eq!(state.selected_range, "a".len().."a".len());
1679            });
1680        });
1681    }
1682
1683    #[gpui::test]
1684    fn selection_direction_flips_when_crossing_the_anchor() {
1685        let mut app = TestApp::new();
1686        app.update(|cx| install_theme(cx, Theme::light()));
1687        let state = app.update(|cx| cx.new(TextareaState::new));
1688        let mut window = app.open_window(|_, _| TestView {
1689            state: state.clone(),
1690        });
1691
1692        window.update(|view, window, cx| {
1693            view.state.update(cx, |state, cx| {
1694                let text = "a😀b";
1695                let emoji_start = "a".len();
1696                let emoji_end = "a😀".len();
1697
1698                state.set_value(text, window, cx);
1699                state.selected_range = emoji_start..emoji_start;
1700                state.selection_reversed = false;
1701                state.select_right(&SelectRight, window, cx);
1702                assert_eq!(state.selected_range, emoji_start..emoji_end);
1703                assert!(!state.selection_reversed);
1704
1705                state.select_left(&SelectLeft, window, cx);
1706                assert_eq!(state.selected_range, emoji_start..emoji_start);
1707                assert!(!state.selection_reversed);
1708                state.select_left(&SelectLeft, window, cx);
1709                assert_eq!(state.selected_range, 0..emoji_start);
1710                assert!(state.selection_reversed);
1711
1712                state.selected_range = emoji_end..emoji_end;
1713                state.selection_reversed = false;
1714                state.select_left(&SelectLeft, window, cx);
1715                assert_eq!(state.selected_range, emoji_start..emoji_end);
1716                assert!(state.selection_reversed);
1717                state.select_right(&SelectRight, window, cx);
1718                assert_eq!(state.selected_range, emoji_end..emoji_end);
1719                assert!(state.selection_reversed);
1720                state.select_right(&SelectRight, window, cx);
1721                assert_eq!(state.selected_range, emoji_end..text.len());
1722                assert!(!state.selection_reversed);
1723            });
1724        });
1725    }
1726
1727    #[gpui::test]
1728    fn utf16_ranges_preserve_astral_character_boundaries() {
1729        let mut app = TestApp::new();
1730        app.update(|cx| install_theme(cx, Theme::light()));
1731        let state = app.update(|cx| cx.new(TextareaState::new));
1732        let mut window = app.open_window(|_, _| TestView {
1733            state: state.clone(),
1734        });
1735
1736        window.update(|view, window, cx| {
1737            view.state.update(cx, |state, cx| {
1738                state.set_value("a😀b", window, cx);
1739                let mut actual_range = None;
1740                assert_eq!(
1741                    state.text_for_range(1..3, &mut actual_range, window, cx),
1742                    Some("😀".to_string())
1743                );
1744                assert_eq!(actual_range, Some(1..3));
1745
1746                state.selected_range = "a".len().."a😀".len();
1747                let selected = state
1748                    .selected_text_range(false, window, cx)
1749                    .expect("selection should be available");
1750                assert_eq!(selected.range, 1..3);
1751                assert!(!selected.reversed);
1752
1753                state.replace_text_in_range(Some(1..3), "", window, cx);
1754                assert_eq!(state.content(), "ab");
1755                assert_eq!(state.selected_range, 1..1);
1756            });
1757        });
1758    }
1759    #[gpui::test]
1760    fn validate_required_fails_on_empty() {
1761        let mut app = TestApp::new();
1762        app.update(|cx| install_theme(cx, Theme::light()));
1763        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).required(true)));
1764        app.update(|cx| {
1765            let result = state.update(cx, |state, cx| state.validate(cx));
1766            assert!(result.is_err());
1767            assert_eq!(
1768                state
1769                    .read(cx)
1770                    .validation_error
1771                    .as_ref()
1772                    .unwrap()
1773                    .message
1774                    .as_ref(),
1775                "This field is required"
1776            );
1777        });
1778    }
1779
1780    #[gpui::test]
1781    fn validate_enforces_min_and_max_length() {
1782        let mut app = TestApp::new();
1783        app.update(|cx| install_theme(cx, Theme::light()));
1784
1785        let state = app.update(|cx| {
1786            cx.new(|cx| {
1787                TextareaState::new(cx)
1788                    .min_length(2)
1789                    .max_length(3)
1790                    .value("a")
1791            })
1792        });
1793        app.update(|cx| {
1794            let result = state.update(cx, |state, cx| state.validate(cx));
1795            assert!(result.is_err());
1796            assert_eq!(
1797                state
1798                    .read(cx)
1799                    .validation_error
1800                    .as_ref()
1801                    .unwrap()
1802                    .message
1803                    .as_ref(),
1804                "Must be at least 2 characters"
1805            );
1806        });
1807
1808        let state =
1809            app.update(|cx| cx.new(|cx| TextareaState::new(cx).max_length(3).value("abcd")));
1810        app.update(|cx| {
1811            let result = state.update(cx, |state, cx| state.validate(cx));
1812            assert!(result.is_err());
1813        });
1814
1815        let state = app.update(|cx| {
1816            cx.new(|cx| {
1817                TextareaState::new(cx)
1818                    .min_length(2)
1819                    .max_length(3)
1820                    .value("abc")
1821            })
1822        });
1823        app.update(|cx| {
1824            let result = state.update(cx, |state, cx| state.validate(cx));
1825            assert!(result.is_ok());
1826            assert!(state.read(cx).validation_error.is_none());
1827            assert_eq!(
1828                state.read(cx).success_message.as_ref().unwrap().as_ref(),
1829                "Valid input"
1830            );
1831        });
1832    }
1833
1834    #[gpui::test]
1835    fn validate_optional_empty_clears_stale_messages() {
1836        let mut app = TestApp::new();
1837        app.update(|cx| install_theme(cx, Theme::light()));
1838        let state = app.update(|cx| cx.new(TextareaState::new));
1839        app.update(|cx| {
1840            state.update(cx, |state, cx| {
1841                state.validation_error = Some(ValidationError {
1842                    message: "stale".into(),
1843                    field_name: None,
1844                });
1845                state.success_message = Some("stale".into());
1846                let result = state.validate(cx);
1847                assert!(result.is_ok());
1848                assert!(state.validation_error.is_none());
1849                assert!(state.success_message.is_none());
1850            });
1851        });
1852    }
1853
1854    #[gpui::test]
1855    fn validate_runs_custom_validator() {
1856        let mut app = TestApp::new();
1857        app.update(|cx| install_theme(cx, Theme::light()));
1858        let state = app.update(|cx| {
1859            cx.new(|cx| {
1860                TextareaState::new(cx)
1861                    .value("forbidden")
1862                    .validation_rules(ValidationRules {
1863                        custom_validator: Some(std::sync::Arc::new(|value| {
1864                            if value.contains("forbidden") {
1865                                Err(ValidationError {
1866                                    message: "Contains forbidden word".into(),
1867                                    field_name: None,
1868                                })
1869                            } else {
1870                                Ok(())
1871                            }
1872                        })),
1873                        ..Default::default()
1874                    })
1875            })
1876        });
1877        app.update(|cx| {
1878            let result = state.update(cx, |state, cx| state.validate(cx));
1879            assert!(result.is_err());
1880            assert_eq!(
1881                state
1882                    .read(cx)
1883                    .validation_error
1884                    .as_ref()
1885                    .unwrap()
1886                    .message
1887                    .as_ref(),
1888                "Contains forbidden word"
1889            );
1890        });
1891    }
1892
1893    #[gpui::test]
1894    fn validate_emits_event_with_result() {
1895        let mut app = TestApp::new();
1896        app.update(|cx| install_theme(cx, Theme::light()));
1897        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).required(true)));
1898        let outcomes = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
1899        let outcomes_for_sub = outcomes.clone();
1900        app.update(|cx| {
1901            cx.subscribe(&state, move |_, event: &TextareaEvent, _| {
1902                if let TextareaEvent::Validate(result) = event {
1903                    outcomes_for_sub.borrow_mut().push(result.is_err());
1904                }
1905            })
1906            .detach();
1907        });
1908        app.update(|cx| {
1909            state.update(cx, |state, cx| state.validate(cx)).ok();
1910        });
1911        assert_eq!(outcomes.borrow().as_slice(), &[true]);
1912    }
1913    #[gpui::test]
1914    fn ime_composition_state_is_queryable() {
1915        let mut app = TestApp::new();
1916        app.update(|cx| install_theme(cx, Theme::light()));
1917        let state = app.update(|cx| cx.new(TextareaState::new));
1918        let mut window = app.open_window(|_, _| TestView {
1919            state: state.clone(),
1920        });
1921
1922        window.update(|view, window, cx| {
1923            view.state.update(cx, |state, cx| {
1924                state.set_value("hello", window, cx);
1925                assert!(!state.is_composing());
1926                assert_eq!(state.composition_char_count(), 0);
1927
1928                state.replace_and_mark_text_in_range(None, "nihao", None, window, cx);
1929                assert!(state.is_composing());
1930                assert_eq!(state.composition_char_count(), 5);
1931                assert_eq!(
1932                    state.content().chars().count() - state.composition_char_count(),
1933                    5
1934                );
1935            });
1936        });
1937
1938        window.update(|view, window, cx| {
1939            view.state.update(cx, |state, cx| {
1940                state.replace_text_in_range(None, "你好", window, cx);
1941                assert!(!state.is_composing());
1942                assert_eq!(state.composition_char_count(), 0);
1943                assert_eq!(state.content(), "hello你好");
1944            });
1945        });
1946    }
1947
1948    #[gpui::test]
1949    fn max_length_commit_does_not_count_inflight_composition() {
1950        let mut app = TestApp::new();
1951        app.update(|cx| install_theme(cx, Theme::light()));
1952        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).max_length(7)));
1953        let mut window = app.open_window(|_, _| TestView {
1954            state: state.clone(),
1955        });
1956
1957        window.update(|view, window, cx| {
1958            view.state.update(cx, |state, cx| {
1959                state.set_value("hello", window, cx);
1960                // Compose 5 extra chars; they are in-flight and must not count
1961                // against the limit.
1962                state.replace_and_mark_text_in_range(None, "nihao", None, window, cx);
1963                // Commit 2 chars: 5 committed + 2 == max 7, so nothing is cut.
1964                // If the in-flight text were counted, the commit would be
1965                // truncated to nothing.
1966                state.replace_text_in_range(None, "你好", window, cx);
1967                assert_eq!(state.content(), "hello你好");
1968            });
1969        });
1970    }
1971    #[gpui::test]
1972    fn validate_ignores_inflight_ime_text() {
1973        let mut app = TestApp::new();
1974        app.update(|cx| install_theme(cx, Theme::light()));
1975        let state = app.update(|cx| cx.new(|cx| TextareaState::new(cx).min_length(6)));
1976        let mut window = app.open_window(|_, _| TestView {
1977            state: state.clone(),
1978        });
1979
1980        window.update(|view, window, cx| {
1981            view.state.update(cx, |state, cx| {
1982                state.set_value("hello", window, cx);
1983                state.replace_and_mark_text_in_range(None, "nihao", None, window, cx);
1984
1985                // Composition in flight: validation uses only the committed
1986                // text, not the transient composition text.
1987                let result = state.validate(cx);
1988                assert!(result.is_err());
1989                assert!(state.validation_error.is_some());
1990
1991                // Once committed, validation includes the committed text.
1992                state.replace_text_in_range(None, "", window, cx);
1993                let result = state.validate(cx);
1994                assert!(result.is_err());
1995                assert!(state.validation_error.is_some());
1996            });
1997        });
1998    }
1999}