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