Skip to main content

gpui_m3/components/
text_area.rs

1//! Multi-line text area that grows with its content.
2//!
3//! Shares the editing model of [`super::TextField`] (GPUI's `examples/input.rs`: keyboard
4//! editing, mouse selection, clipboard and IME) and adds soft wrapping, vertical caret
5//! movement, autosize between `min_rows` and `max_height`, and scrolling beyond that.
6//! It draws no background: the host paints the surrounding box (e.g. a composer).
7
8use std::ops::Range;
9use std::time::Instant;
10
11use gpui::{
12    App, AvailableSpace, Bounds, ClipboardItem, ContentMask, Context, CursorStyle, Element,
13    ElementId, ElementInputHandler, Entity, EntityInputHandler, EventEmitter, FocusHandle,
14    Focusable, FontWeight, GlobalElementId, KeyBinding, LayoutId, MouseButton, MouseDownEvent,
15    MouseMoveEvent, MouseUpEvent, Pixels, Point, Render, ScrollWheelEvent, SharedString, Style,
16    TextAlign, TextRun, UTF16Selection, UnderlineStyle, Window, WrappedLine, div, fill, point,
17    prelude::*, px, relative, size,
18};
19use unicode_segmentation::UnicodeSegmentation;
20
21use super::text_field::{
22    counter_text, fit_to_limit, grapheme_count, has_supporting_row, is_over_limit,
23    supporting_content, supporting_row,
24};
25use crate::motion::continuous_at;
26use crate::theme::{Theme, alpha, font_family};
27
28/// Kept private so they do not clash with the [`super::TextField`] actions.
29mod keys {
30    gpui::actions!(
31        m3_text_area,
32        [
33            Backspace,
34            Delete,
35            Left,
36            Right,
37            Up,
38            Down,
39            SelectLeft,
40            SelectRight,
41            SelectUp,
42            SelectDown,
43            SelectAll,
44            Home,
45            End,
46            SelectHome,
47            SelectEnd,
48            Paste,
49            Cut,
50            Copy,
51            Submit,
52            Newline,
53            Cancel
54        ]
55    );
56}
57use keys::*;
58
59const KEY_CONTEXT: &str = "M3TextArea";
60
61/// Registers the text area key bindings. Called by [`crate::init`].
62pub fn bind_text_area_keys(cx: &mut App) {
63    cx.bind_keys(text_area_bindings());
64}
65
66pub(crate) fn text_area_bindings() -> Vec<KeyBinding> {
67    let ctx = Some(KEY_CONTEXT);
68    vec![
69        KeyBinding::new("backspace", Backspace, ctx),
70        KeyBinding::new("delete", Delete, ctx),
71        KeyBinding::new("left", Left, ctx),
72        KeyBinding::new("right", Right, ctx),
73        KeyBinding::new("up", Up, ctx),
74        KeyBinding::new("down", Down, ctx),
75        KeyBinding::new("shift-left", SelectLeft, ctx),
76        KeyBinding::new("shift-right", SelectRight, ctx),
77        KeyBinding::new("shift-up", SelectUp, ctx),
78        KeyBinding::new("shift-down", SelectDown, ctx),
79        KeyBinding::new("secondary-a", SelectAll, ctx),
80        KeyBinding::new("secondary-v", Paste, ctx),
81        KeyBinding::new("secondary-c", Copy, ctx),
82        KeyBinding::new("secondary-x", Cut, ctx),
83        KeyBinding::new("home", Home, ctx),
84        KeyBinding::new("end", End, ctx),
85        KeyBinding::new("shift-home", SelectHome, ctx),
86        KeyBinding::new("shift-end", SelectEnd, ctx),
87        KeyBinding::new("enter", Submit, ctx),
88        KeyBinding::new("shift-enter", Newline, ctx),
89        KeyBinding::new("escape", Cancel, ctx),
90    ]
91}
92
93/// Events emitted by a [`TextArea`]. Subscribe with `cx.subscribe(&area, ...)`.
94#[derive(Clone, Debug)]
95pub enum TextAreaEvent {
96    /// The text changed (typing, paste, cut, [`TextArea::set_text`], [`TextArea::replace_range`]).
97    Changed(SharedString),
98    /// Enter was pressed.
99    Submit(SharedString),
100    /// Shift+Enter inserted a line break.
101    Newline,
102    /// The user pasted. Emitted before the text is inserted; items without text (such as
103    /// images) are not inserted, so the host can turn them into attachments.
104    Paste(ClipboardItem),
105    /// Escape was pressed.
106    Cancelled,
107}
108
109/// A multi-line text area. Create it once and keep the entity in your view:
110///
111/// ```ignore
112/// let draft = cx.new(|cx| TextArea::new(cx).placeholder("Ask anything").min_rows(2));
113/// ```
114pub struct TextArea {
115    focus_handle: FocusHandle,
116    content: SharedString,
117    placeholder: SharedString,
118    min_rows: usize,
119    max_height: Pixels,
120    error: Option<SharedString>,
121    supporting_text: Option<SharedString>,
122    max_length: Option<usize>,
123    hard_limit: bool,
124    selected_range: Range<usize>,
125    selection_reversed: bool,
126    marked_range: Option<Range<usize>>,
127    layout: Option<Layout>,
128    last_bounds: Option<Bounds<Pixels>>,
129    scroll_y: Pixels,
130    scroll_to_cursor: bool,
131    is_selecting: bool,
132    last_edit: Instant,
133    suggesting: bool,
134}
135
136impl EventEmitter<TextAreaEvent> for TextArea {}
137
138impl Focusable for TextArea {
139    fn focus_handle(&self, _: &App) -> FocusHandle {
140        self.focus_handle.clone()
141    }
142}
143
144impl TextArea {
145    pub fn new(cx: &mut Context<Self>) -> Self {
146        Self {
147            focus_handle: cx.focus_handle(),
148            content: SharedString::default(),
149            placeholder: SharedString::default(),
150            min_rows: 1,
151            max_height: px(240.),
152            error: None,
153            supporting_text: None,
154            max_length: None,
155            hard_limit: false,
156            selected_range: 0..0,
157            selection_reversed: false,
158            marked_range: None,
159            layout: None,
160            last_bounds: None,
161            scroll_y: px(0.),
162            scroll_to_cursor: false,
163            is_selecting: false,
164            last_edit: Instant::now(),
165            suggesting: false,
166        }
167    }
168
169    /// Marks that a suggestion list is open for this input: while on, ↑ ↓ Enter Tab Esc dispatch
170    /// the [`super::SuggestionList`] actions instead of their usual editing behavior.
171    pub fn set_suggesting(&mut self, suggesting: bool, cx: &mut Context<Self>) {
172        if self.suggesting != suggesting {
173            self.suggesting = suggesting;
174            cx.notify();
175        }
176    }
177
178    pub fn is_suggesting(&self) -> bool {
179        self.suggesting
180    }
181
182    fn key_context(&self) -> gpui::KeyContext {
183        let mut context = gpui::KeyContext::default();
184        context.add(KEY_CONTEXT);
185        if self.suggesting {
186            context.add(super::SUGGESTING_CONTEXT);
187        }
188        context
189    }
190
191    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
192        self.placeholder = placeholder.into();
193        self
194    }
195
196    /// Minimum height in text rows (1 by default).
197    pub fn min_rows(mut self, rows: usize) -> Self {
198        self.min_rows = rows.max(1);
199        self
200    }
201
202    /// Height at which it stops growing and scrolls (240 px by default).
203    pub fn max_height(mut self, max_height: Pixels) -> Self {
204        self.max_height = max_height;
205        self
206    }
207
208    /// Error state: the caret and the supporting row turn `error` and the message replaces the
209    /// supporting text. The host paints the box, so it can follow with [`Self::is_invalid`].
210    pub fn error(mut self, error: Option<SharedString>) -> Self {
211        self.error = error;
212        self
213    }
214
215    pub fn set_error(&mut self, error: Option<SharedString>, cx: &mut Context<Self>) {
216        if self.error != error {
217            self.error = error;
218            cx.notify();
219        }
220    }
221
222    /// 12 px line under the text. Setting it reserves the line's height, so an error message
223    /// taking its place does not move what is below.
224    pub fn supporting_text(mut self, text: impl Into<SharedString>) -> Self {
225        self.supporting_text = Some(text.into());
226        self
227    }
228
229    /// Shows a "12 / 50" counter at the end of the supporting line. It only flags: past the
230    /// limit it turns `error` and typing still works (see [`Self::hard_limit`]).
231    pub fn max_length(mut self, max: usize) -> Self {
232        self.max_length = Some(max);
233        self
234    }
235
236    /// With [`Self::max_length`], typing, pasting and IME input are cut at the limit.
237    /// [`Self::set_text`] and [`Self::replace_range`] are not.
238    pub fn hard_limit(mut self, hard: bool) -> Self {
239        self.hard_limit = hard;
240        self
241    }
242
243    /// An error was set or the text is past `max_length`.
244    pub fn is_invalid(&self) -> bool {
245        self.error.is_some() || is_over_limit(grapheme_count(&self.content), self.max_length)
246    }
247
248    /// `new_text` cut so that replacing `range` respects the hard limit.
249    fn within_limit<'a>(&self, range: &Range<usize>, new_text: &'a str) -> &'a str {
250        let max = if self.hard_limit {
251            self.max_length
252        } else {
253            None
254        };
255        if max.is_none() {
256            return new_text;
257        }
258        let kept = grapheme_count(&self.content[..range.start])
259            + grapheme_count(&self.content[range.end..]);
260        fit_to_limit(kept, new_text, max)
261    }
262
263    pub fn text(&self) -> &SharedString {
264        &self.content
265    }
266
267    /// Replaces the whole text and puts the caret at the end.
268    pub fn set_text(&mut self, text: impl Into<SharedString>, cx: &mut Context<Self>) {
269        self.content = text.into();
270        self.selected_range = self.content.len()..self.content.len();
271        self.marked_range = None;
272        self.changed(cx);
273    }
274
275    pub fn clear(&mut self, cx: &mut Context<Self>) {
276        self.set_text("", cx);
277    }
278
279    /// Caret position, in UTF-8 bytes.
280    pub fn cursor_offset(&self) -> usize {
281        if self.selection_reversed {
282            self.selected_range.start
283        } else {
284            self.selected_range.end
285        }
286    }
287
288    /// Replaces a byte range (e.g. an `@query` with the chosen mention) and puts the caret after
289    /// the inserted text.
290    pub fn replace_range(&mut self, range: Range<usize>, text: &str, cx: &mut Context<Self>) {
291        let end = range.end.min(self.content.len());
292        let start = range.start.min(end);
293        self.content = (self.content[..start].to_owned() + text + &self.content[end..]).into();
294        self.selected_range = start + text.len()..start + text.len();
295        self.selection_reversed = false;
296        self.marked_range = None;
297        self.changed(cx);
298    }
299
300    pub fn focus(&self, window: &mut Window) {
301        window.focus(&self.focus_handle);
302    }
303
304    pub fn is_focused(&self, window: &Window) -> bool {
305        self.focus_handle.is_focused(window)
306    }
307
308    fn changed(&mut self, cx: &mut Context<Self>) {
309        self.last_edit = Instant::now();
310        self.scroll_to_cursor = true;
311        cx.emit(TextAreaEvent::Changed(self.content.clone()));
312        cx.notify();
313    }
314
315    fn left(&mut self, _: &Left, _: &mut Window, cx: &mut Context<Self>) {
316        if self.selected_range.is_empty() {
317            self.move_to(self.previous_boundary(self.cursor_offset()), cx);
318        } else {
319            self.move_to(self.selected_range.start, cx)
320        }
321    }
322
323    fn right(&mut self, _: &Right, _: &mut Window, cx: &mut Context<Self>) {
324        if self.selected_range.is_empty() {
325            self.move_to(self.next_boundary(self.selected_range.end), cx);
326        } else {
327            self.move_to(self.selected_range.end, cx)
328        }
329    }
330
331    fn up(&mut self, _: &Up, _: &mut Window, cx: &mut Context<Self>) {
332        let offset = self.vertical_offset(-1.);
333        self.move_to(offset, cx);
334    }
335
336    fn down(&mut self, _: &Down, _: &mut Window, cx: &mut Context<Self>) {
337        let offset = self.vertical_offset(1.);
338        self.move_to(offset, cx);
339    }
340
341    fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
342        self.select_to(self.previous_boundary(self.cursor_offset()), cx);
343    }
344
345    fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
346        self.select_to(self.next_boundary(self.cursor_offset()), cx);
347    }
348
349    fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
350        self.select_to(self.vertical_offset(-1.), cx);
351    }
352
353    fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
354        self.select_to(self.vertical_offset(1.), cx);
355    }
356
357    fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
358        self.move_to(0, cx);
359        self.select_to(self.content.len(), cx)
360    }
361
362    fn home(&mut self, _: &Home, _: &mut Window, cx: &mut Context<Self>) {
363        self.move_to(self.row_edge(false), cx);
364    }
365
366    fn end(&mut self, _: &End, _: &mut Window, cx: &mut Context<Self>) {
367        self.move_to(self.row_edge(true), cx);
368    }
369
370    fn select_home(&mut self, _: &SelectHome, _: &mut Window, cx: &mut Context<Self>) {
371        self.select_to(self.row_edge(false), cx);
372    }
373
374    fn select_end(&mut self, _: &SelectEnd, _: &mut Window, cx: &mut Context<Self>) {
375        self.select_to(self.row_edge(true), cx);
376    }
377
378    fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
379        if self.selected_range.is_empty() {
380            self.select_to(self.previous_boundary(self.cursor_offset()), cx)
381        }
382        self.replace_text_in_range(None, "", window, cx)
383    }
384
385    fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
386        if self.selected_range.is_empty() {
387            self.select_to(self.next_boundary(self.cursor_offset()), cx)
388        }
389        self.replace_text_in_range(None, "", window, cx)
390    }
391
392    fn submit(&mut self, _: &Submit, _: &mut Window, cx: &mut Context<Self>) {
393        cx.emit(TextAreaEvent::Submit(self.content.clone()));
394    }
395
396    fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
397        self.replace_text_in_range(None, "\n", window, cx);
398        cx.emit(TextAreaEvent::Newline);
399    }
400
401    fn cancel(&mut self, _: &Cancel, _: &mut Window, cx: &mut Context<Self>) {
402        cx.emit(TextAreaEvent::Cancelled);
403    }
404
405    fn on_mouse_down(
406        &mut self,
407        event: &MouseDownEvent,
408        window: &mut Window,
409        cx: &mut Context<Self>,
410    ) {
411        window.focus(&self.focus_handle);
412        self.is_selecting = true;
413        let offset = self.index_for_mouse_position(event.position);
414        if event.modifiers.shift {
415            self.select_to(offset, cx);
416        } else {
417            self.move_to(offset, cx)
418        }
419    }
420
421    fn on_mouse_up(&mut self, _: &MouseUpEvent, _: &mut Window, _: &mut Context<Self>) {
422        self.is_selecting = false;
423    }
424
425    fn on_mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {
426        if self.is_selecting {
427            self.select_to(self.index_for_mouse_position(event.position), cx);
428        }
429    }
430
431    fn on_scroll_wheel(
432        &mut self,
433        event: &ScrollWheelEvent,
434        window: &mut Window,
435        cx: &mut Context<Self>,
436    ) {
437        let Some(layout) = self.layout.as_ref() else {
438            return;
439        };
440        let overflow = (layout.height() - self.max_height).max(px(0.));
441        if overflow <= px(0.) {
442            return;
443        }
444        let delta = event.delta.pixel_delta(window.line_height()).y;
445        self.scroll_y = (self.scroll_y - delta).clamp(px(0.), overflow);
446        self.scroll_to_cursor = false;
447        cx.stop_propagation();
448        cx.notify();
449    }
450
451    fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
452        let Some(item) = cx.read_from_clipboard() else {
453            return;
454        };
455        cx.emit(TextAreaEvent::Paste(item.clone()));
456        if let Some(text) = item.text() {
457            self.replace_text_in_range(None, &text.replace("\r\n", "\n"), window, cx);
458        }
459    }
460
461    fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
462        if !self.selected_range.is_empty() {
463            cx.write_to_clipboard(ClipboardItem::new_string(
464                self.content[self.selected_range.clone()].to_string(),
465            ));
466        }
467    }
468
469    fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
470        if !self.selected_range.is_empty() {
471            cx.write_to_clipboard(ClipboardItem::new_string(
472                self.content[self.selected_range.clone()].to_string(),
473            ));
474            self.replace_text_in_range(None, "", window, cx)
475        }
476    }
477
478    fn move_to(&mut self, offset: usize, cx: &mut Context<Self>) {
479        self.selected_range = offset..offset;
480        self.selection_reversed = false;
481        self.last_edit = Instant::now();
482        self.scroll_to_cursor = true;
483        cx.notify()
484    }
485
486    fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
487        if self.selection_reversed {
488            self.selected_range.start = offset
489        } else {
490            self.selected_range.end = offset
491        };
492        if self.selected_range.end < self.selected_range.start {
493            self.selection_reversed = !self.selection_reversed;
494            self.selected_range = self.selected_range.end..self.selected_range.start;
495        }
496        self.scroll_to_cursor = true;
497        cx.notify()
498    }
499
500    /// Offset one visual row above (`-1.`) or below (`1.`) the caret, keeping its x.
501    fn vertical_offset(&self, direction: f32) -> usize {
502        let cursor = self.cursor_offset();
503        let Some(layout) = self.layout.as_ref() else {
504            return cursor;
505        };
506        let position = layout.position_for_offset(cursor);
507        let y = position.y + layout.line_height * (direction + 0.5);
508        if y < px(0.) {
509            0
510        } else if y >= layout.height() {
511            self.content.len()
512        } else {
513            layout.offset_for_position(point(position.x, y))
514        }
515    }
516
517    /// Start or end of the caret's visual row.
518    fn row_edge(&self, end: bool) -> usize {
519        let cursor = self.cursor_offset();
520        let Some(layout) = self.layout.as_ref() else {
521            return if end { self.content.len() } else { 0 };
522        };
523        let y = layout.position_for_offset(cursor).y + layout.line_height * 0.5;
524        let x = if end { Pixels::MAX / 2. } else { px(0.) };
525        layout.offset_for_position(point(x, y))
526    }
527
528    fn index_for_mouse_position(&self, position: Point<Pixels>) -> usize {
529        let (Some(bounds), Some(layout)) = (self.last_bounds.as_ref(), self.layout.as_ref()) else {
530            return 0;
531        };
532        if self.content.is_empty() {
533            return 0;
534        }
535        let local = position - bounds.origin + point(px(0.), self.scroll_y);
536        if local.y < px(0.) {
537            return 0;
538        }
539        if local.y >= layout.height() {
540            return self.content.len();
541        }
542        layout.offset_for_position(local)
543    }
544
545    fn offset_from_utf16(&self, offset: usize) -> usize {
546        let mut utf8_offset = 0;
547        let mut utf16_count = 0;
548        for ch in self.content.chars() {
549            if utf16_count >= offset {
550                break;
551            }
552            utf16_count += ch.len_utf16();
553            utf8_offset += ch.len_utf8();
554        }
555        utf8_offset
556    }
557
558    fn offset_to_utf16(&self, offset: usize) -> usize {
559        let mut utf16_offset = 0;
560        let mut utf8_count = 0;
561        for ch in self.content.chars() {
562            if utf8_count >= offset {
563                break;
564            }
565            utf8_count += ch.len_utf8();
566            utf16_offset += ch.len_utf16();
567        }
568        utf16_offset
569    }
570
571    fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
572        self.offset_to_utf16(range.start)..self.offset_to_utf16(range.end)
573    }
574
575    fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
576        self.offset_from_utf16(range_utf16.start)..self.offset_from_utf16(range_utf16.end)
577    }
578
579    fn previous_boundary(&self, offset: usize) -> usize {
580        self.content
581            .grapheme_indices(true)
582            .rev()
583            .find_map(|(idx, _)| (idx < offset).then_some(idx))
584            .unwrap_or(0)
585    }
586
587    fn next_boundary(&self, offset: usize) -> usize {
588        self.content
589            .grapheme_indices(true)
590            .find_map(|(idx, _)| (idx > offset).then_some(idx))
591            .unwrap_or(self.content.len())
592    }
593}
594
595impl EntityInputHandler for TextArea {
596    fn text_for_range(
597        &mut self,
598        range_utf16: Range<usize>,
599        actual_range: &mut Option<Range<usize>>,
600        _: &mut Window,
601        _: &mut Context<Self>,
602    ) -> Option<String> {
603        let range = self.range_from_utf16(&range_utf16);
604        actual_range.replace(self.range_to_utf16(&range));
605        Some(self.content[range].to_string())
606    }
607
608    fn selected_text_range(
609        &mut self,
610        _: bool,
611        _: &mut Window,
612        _: &mut Context<Self>,
613    ) -> Option<UTF16Selection> {
614        Some(UTF16Selection {
615            range: self.range_to_utf16(&self.selected_range),
616            reversed: self.selection_reversed,
617        })
618    }
619
620    fn marked_text_range(&self, _: &mut Window, _: &mut Context<Self>) -> Option<Range<usize>> {
621        self.marked_range
622            .as_ref()
623            .map(|range| self.range_to_utf16(range))
624    }
625
626    fn unmark_text(&mut self, _: &mut Window, _: &mut Context<Self>) {
627        self.marked_range = None;
628    }
629
630    fn replace_text_in_range(
631        &mut self,
632        range_utf16: Option<Range<usize>>,
633        new_text: &str,
634        _: &mut Window,
635        cx: &mut Context<Self>,
636    ) {
637        let range = range_utf16
638            .as_ref()
639            .map(|range_utf16| self.range_from_utf16(range_utf16))
640            .or(self.marked_range.clone())
641            .unwrap_or(self.selected_range.clone());
642        let new_text = self.within_limit(&range, new_text);
643        self.content =
644            (self.content[0..range.start].to_owned() + new_text + &self.content[range.end..])
645                .into();
646        self.selected_range = range.start + new_text.len()..range.start + new_text.len();
647        self.selection_reversed = false;
648        self.marked_range.take();
649        self.changed(cx);
650    }
651
652    fn replace_and_mark_text_in_range(
653        &mut self,
654        range_utf16: Option<Range<usize>>,
655        new_text: &str,
656        new_selected_range_utf16: Option<Range<usize>>,
657        _: &mut Window,
658        cx: &mut Context<Self>,
659    ) {
660        let range = range_utf16
661            .as_ref()
662            .map(|range_utf16| self.range_from_utf16(range_utf16))
663            .or(self.marked_range.clone())
664            .unwrap_or(self.selected_range.clone());
665        let new_text = self.within_limit(&range, new_text);
666        self.content =
667            (self.content[0..range.start].to_owned() + new_text + &self.content[range.end..])
668                .into();
669        self.marked_range =
670            (!new_text.is_empty()).then(|| range.start..range.start + new_text.len());
671        self.selected_range = new_selected_range_utf16
672            .as_ref()
673            .map(|range_utf16| self.range_from_utf16(range_utf16))
674            .map(|new_range| new_range.start + range.start..new_range.end + range.end)
675            .unwrap_or_else(|| range.start + new_text.len()..range.start + new_text.len());
676        let end = self.content.len();
677        self.selected_range = self.selected_range.start.min(end)..self.selected_range.end.min(end);
678        self.changed(cx);
679    }
680
681    fn bounds_for_range(
682        &mut self,
683        range_utf16: Range<usize>,
684        bounds: Bounds<Pixels>,
685        _: &mut Window,
686        _: &mut Context<Self>,
687    ) -> Option<Bounds<Pixels>> {
688        let layout = self.layout.as_ref()?;
689        let range = self.range_from_utf16(&range_utf16);
690        let origin = bounds.origin - point(px(0.), self.scroll_y);
691        let start = layout.position_for_offset(range.start);
692        let end = layout.position_for_offset(range.end);
693        Some(Bounds::from_corners(
694            origin + start,
695            origin + point(end.x, end.y + layout.line_height),
696        ))
697    }
698
699    fn character_index_for_point(
700        &mut self,
701        point: Point<Pixels>,
702        _: &mut Window,
703        _: &mut Context<Self>,
704    ) -> Option<usize> {
705        let bounds = self.last_bounds?;
706        let layout = self.layout.as_ref()?;
707        let local = point - bounds.origin + gpui::point(px(0.), self.scroll_y);
708        Some(self.offset_to_utf16(layout.offset_for_position(local)))
709    }
710}
711
712/// The wrapped lines of the text (or the placeholder), one per hard line.
713#[derive(Clone)]
714struct Layout {
715    /// Byte offset where each hard line starts, and its wrapped layout.
716    lines: Vec<(usize, WrappedLine)>,
717    line_height: Pixels,
718}
719
720impl Layout {
721    fn shape(
722        text: SharedString,
723        runs: &[TextRun],
724        font_size: Pixels,
725        line_height: Pixels,
726        wrap_width: Option<Pixels>,
727        window: &Window,
728    ) -> Self {
729        let wrapped = window
730            .text_system()
731            .shape_text(text, font_size, runs, wrap_width, None)
732            .unwrap_or_default();
733        let mut start = 0;
734        let lines = wrapped
735            .into_iter()
736            .map(|line| {
737                let line_start = start;
738                start += line.len() + 1;
739                (line_start, line)
740            })
741            .collect();
742        Self { lines, line_height }
743    }
744
745    fn rows(line: &WrappedLine) -> usize {
746        line.wrap_boundaries().len() + 1
747    }
748
749    fn height(&self) -> Pixels {
750        let rows: usize = self.lines.iter().map(|(_, line)| Self::rows(line)).sum();
751        self.line_height * rows.max(1) as f32
752    }
753
754    /// Top-left of the caret for `offset`, relative to the text origin.
755    fn position_for_offset(&self, offset: usize) -> Point<Pixels> {
756        let mut y = px(0.);
757        for (start, line) in &self.lines {
758            if offset <= start + line.len() {
759                let local = offset.saturating_sub(*start);
760                let position = line
761                    .position_for_index(local, self.line_height)
762                    .unwrap_or_default();
763                return point(position.x, y + position.y);
764            }
765            y += self.line_height * Self::rows(line) as f32;
766        }
767        point(px(0.), y)
768    }
769
770    /// Closest offset to a position relative to the text origin.
771    fn offset_for_position(&self, position: Point<Pixels>) -> usize {
772        let mut y = px(0.);
773        let last = self.lines.len().saturating_sub(1);
774        for (i, (start, line)) in self.lines.iter().enumerate() {
775            let height = self.line_height * Self::rows(line) as f32;
776            if position.y < y + height || i == last {
777                let local = point(
778                    position.x.max(px(0.)),
779                    (position.y - y).clamp(px(0.), height - px(1.)),
780                );
781                let index = match line.closest_index_for_position(local, self.line_height) {
782                    Ok(index) | Err(index) => index,
783                };
784                return start + index.min(line.len());
785            }
786            y += height;
787        }
788        0
789    }
790}
791
792/// Text runs of the shaped text, underlining the IME composition.
793fn text_runs(len: usize, run: TextRun, marked: Option<&Range<usize>>) -> Vec<TextRun> {
794    let Some(marked) = marked else {
795        return vec![run];
796    };
797    vec![
798        TextRun {
799            len: marked.start,
800            ..run.clone()
801        },
802        TextRun {
803            len: marked.end - marked.start,
804            underline: Some(UnderlineStyle {
805                color: Some(run.color),
806                thickness: px(1.),
807                wavy: false,
808            }),
809            ..run.clone()
810        },
811        TextRun {
812            len: len - marked.end,
813            ..run
814        },
815    ]
816    .into_iter()
817    .filter(|run| run.len > 0)
818    .collect()
819}
820
821/// Shapes, sizes and paints the text, selection and caret.
822struct TextBody {
823    area: Entity<TextArea>,
824}
825
826struct BodyPaint {
827    layout: Layout,
828    selection: Vec<Bounds<Pixels>>,
829    cursor: Option<Bounds<Pixels>>,
830}
831
832impl IntoElement for TextBody {
833    type Element = Self;
834
835    fn into_element(self) -> Self::Element {
836        self
837    }
838}
839
840impl TextBody {
841    /// Text to shape (the placeholder when empty) and its runs.
842    fn source(&self, window: &Window, cx: &App) -> (SharedString, Vec<TextRun>) {
843        let s = Theme::of(cx);
844        let area = self.area.read(cx);
845        let style = window.text_style();
846        let (text, color) = if area.content.is_empty() {
847            (area.placeholder.clone(), s.outline)
848        } else {
849            (area.content.clone(), style.color)
850        };
851        let run = TextRun {
852            len: text.len(),
853            font: style.font(),
854            color,
855            background_color: None,
856            underline: None,
857            strikethrough: None,
858        };
859        let marked = if area.content.is_empty() {
860            None
861        } else {
862            area.marked_range.as_ref()
863        };
864        let runs = text_runs(text.len(), run, marked);
865        (text, runs)
866    }
867}
868
869impl Element for TextBody {
870    type RequestLayoutState = ();
871    type PrepaintState = BodyPaint;
872
873    fn id(&self) -> Option<ElementId> {
874        None
875    }
876
877    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
878        None
879    }
880
881    fn request_layout(
882        &mut self,
883        _: Option<&GlobalElementId>,
884        _: Option<&gpui::InspectorElementId>,
885        window: &mut Window,
886        cx: &mut App,
887    ) -> (LayoutId, Self::RequestLayoutState) {
888        let (text, runs) = self.source(window, cx);
889        let (min_rows, max_height) = {
890            let area = self.area.read(cx);
891            (area.min_rows, area.max_height)
892        };
893        let font_size = window.text_style().font_size.to_pixels(window.rem_size());
894        let line_height = window.line_height();
895        let mut style = Style::default();
896        style.size.width = relative(1.).into();
897        let layout_id =
898            window.request_measured_layout(style, move |known, available, window, _| {
899                let width = known.width.or(match available.width {
900                    AvailableSpace::Definite(width) => Some(width),
901                    _ => None,
902                });
903                let layout =
904                    Layout::shape(text.clone(), &runs, font_size, line_height, width, window);
905                let height = layout
906                    .height()
907                    .max(line_height * min_rows as f32)
908                    .min(max_height);
909                size(width.unwrap_or(px(0.)), height)
910            });
911        (layout_id, ())
912    }
913
914    fn prepaint(
915        &mut self,
916        _: Option<&GlobalElementId>,
917        _: Option<&gpui::InspectorElementId>,
918        bounds: Bounds<Pixels>,
919        _: &mut Self::RequestLayoutState,
920        window: &mut Window,
921        cx: &mut App,
922    ) -> Self::PrepaintState {
923        let (text, runs) = self.source(window, cx);
924        let font_size = window.text_style().font_size.to_pixels(window.rem_size());
925        let line_height = window.line_height();
926        let layout = Layout::shape(
927            text,
928            &runs,
929            font_size,
930            line_height,
931            Some(bounds.size.width),
932            window,
933        );
934
935        let (selected_range, cursor, scroll_to_cursor, mut scroll_y, empty) = {
936            let area = self.area.read(cx);
937            (
938                area.selected_range.clone(),
939                area.cursor_offset(),
940                area.scroll_to_cursor,
941                area.scroll_y,
942                area.content.is_empty(),
943            )
944        };
945        // Keep the caret visible after edits and keyboard moves; otherwise only clamp.
946        let overflow = (layout.height() - bounds.size.height).max(px(0.));
947        let caret = layout.position_for_offset(if empty { 0 } else { cursor });
948        if scroll_to_cursor {
949            if caret.y < scroll_y {
950                scroll_y = caret.y;
951            } else if caret.y + line_height > scroll_y + bounds.size.height {
952                scroll_y = caret.y + line_height - bounds.size.height;
953            }
954        }
955        let scroll_y = scroll_y.clamp(px(0.), overflow);
956        self.area.update(cx, |area, _| {
957            area.scroll_y = scroll_y;
958            area.scroll_to_cursor = false;
959        });
960        let origin = bounds.origin - point(px(0.), scroll_y);
961
962        let mut selection = Vec::new();
963        let cursor = if selected_range.is_empty() || empty {
964            Some(Bounds::new(origin + caret, size(px(2.), line_height)))
965        } else {
966            let start = layout.position_for_offset(selected_range.start);
967            let end = layout.position_for_offset(selected_range.end);
968            let right = bounds.size.width;
969            if start.y == end.y {
970                selection.push(Bounds::from_corners(
971                    origin + start,
972                    origin + point(end.x, end.y + line_height),
973                ));
974            } else {
975                selection.push(Bounds::from_corners(
976                    origin + start,
977                    origin + point(right, start.y + line_height),
978                ));
979                if end.y > start.y + line_height {
980                    selection.push(Bounds::from_corners(
981                        origin + point(px(0.), start.y + line_height),
982                        origin + point(right, end.y),
983                    ));
984                }
985                selection.push(Bounds::from_corners(
986                    origin + point(px(0.), end.y),
987                    origin + point(end.x, end.y + line_height),
988                ));
989            }
990            None
991        };
992        BodyPaint {
993            layout,
994            selection,
995            cursor,
996        }
997    }
998
999    fn paint(
1000        &mut self,
1001        _: Option<&GlobalElementId>,
1002        _: Option<&gpui::InspectorElementId>,
1003        bounds: Bounds<Pixels>,
1004        _: &mut Self::RequestLayoutState,
1005        prepaint: &mut Self::PrepaintState,
1006        window: &mut Window,
1007        cx: &mut App,
1008    ) {
1009        let s = *Theme::of(cx);
1010        let (focus_handle, last_edit, scroll_y, invalid) = {
1011            let area = self.area.read(cx);
1012            (
1013                area.focus_handle.clone(),
1014                area.last_edit,
1015                area.scroll_y,
1016                area.is_invalid(),
1017            )
1018        };
1019        window.handle_input(
1020            &focus_handle,
1021            ElementInputHandler::new(bounds, self.area.clone()),
1022            cx,
1023        );
1024        let line_height = prepaint.layout.line_height;
1025        window.with_content_mask(Some(ContentMask { bounds }), |window| {
1026            for selection in prepaint.selection.drain(..) {
1027                window.paint_quad(fill(selection, alpha(s.primary, 0.3)));
1028            }
1029            let mut y = bounds.top() - scroll_y;
1030            for (_, line) in &prepaint.layout.lines {
1031                let height = line_height * Layout::rows(line) as f32;
1032                if y + height >= bounds.top() && y <= bounds.bottom() {
1033                    line.paint(
1034                        point(bounds.left(), y),
1035                        line_height,
1036                        TextAlign::Left,
1037                        Some(bounds),
1038                        window,
1039                        cx,
1040                    )
1041                    .ok();
1042                }
1043                y += height;
1044            }
1045            // The caret stays solid while typing and blinks every 0.53 s after that.
1046            if focus_handle.is_focused(window)
1047                && let Some(cursor) = prepaint.cursor.take()
1048            {
1049                let since_edit = last_edit.elapsed().as_secs_f32();
1050                if since_edit < 0.5 || ((since_edit / 0.53) as u32).is_multiple_of(2) {
1051                    window.paint_quad(fill(cursor, if invalid { s.error } else { s.primary }));
1052                }
1053            }
1054        });
1055        let layout = prepaint.layout.clone();
1056        self.area.update(cx, |area, _| {
1057            area.layout = Some(layout);
1058            area.last_bounds = Some(bounds);
1059        });
1060    }
1061}
1062
1063impl Render for TextArea {
1064    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1065        let s = *Theme::of(cx);
1066        if self.focus_handle.is_focused(window) {
1067            // Caret blink: a few frames per second is enough.
1068            continuous_at(4., window, cx);
1069        }
1070        div()
1071            .id(("m3-text-area", cx.entity_id().as_u64()))
1072            .key_context(self.key_context())
1073            .track_focus(&self.focus_handle)
1074            .cursor(CursorStyle::IBeam)
1075            .on_action(cx.listener(Self::backspace))
1076            .on_action(cx.listener(Self::delete))
1077            .on_action(cx.listener(Self::left))
1078            .on_action(cx.listener(Self::right))
1079            .on_action(cx.listener(Self::up))
1080            .on_action(cx.listener(Self::down))
1081            .on_action(cx.listener(Self::select_left))
1082            .on_action(cx.listener(Self::select_right))
1083            .on_action(cx.listener(Self::select_up))
1084            .on_action(cx.listener(Self::select_down))
1085            .on_action(cx.listener(Self::select_all))
1086            .on_action(cx.listener(Self::home))
1087            .on_action(cx.listener(Self::end))
1088            .on_action(cx.listener(Self::select_home))
1089            .on_action(cx.listener(Self::select_end))
1090            .on_action(cx.listener(Self::paste))
1091            .on_action(cx.listener(Self::cut))
1092            .on_action(cx.listener(Self::copy))
1093            .on_action(cx.listener(Self::submit))
1094            .on_action(cx.listener(Self::newline))
1095            .on_action(cx.listener(Self::cancel))
1096            .on_mouse_down(MouseButton::Left, cx.listener(Self::on_mouse_down))
1097            .on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up))
1098            .on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up))
1099            .on_mouse_move(cx.listener(Self::on_mouse_move))
1100            .on_scroll_wheel(cx.listener(Self::on_scroll_wheel))
1101            .w_full()
1102            .text_color(s.on_surface)
1103            .font_family(font_family())
1104            .text_size(px(13.5))
1105            .font_weight(FontWeight(400.))
1106            .line_height(relative(1.5))
1107            .child(TextBody { area: cx.entity() })
1108            .children(
1109                has_supporting_row(
1110                    self.supporting_text.as_ref(),
1111                    self.max_length,
1112                    self.error.as_ref(),
1113                )
1114                .then(|| {
1115                    let count = grapheme_count(&self.content);
1116                    let content =
1117                        supporting_content(self.error.as_ref(), self.supporting_text.as_ref())
1118                            .map(|(text, error)| (text.clone(), error));
1119                    let counter = self
1120                        .max_length
1121                        .map(|max| (counter_text(count, max), is_over_limit(count, Some(max))));
1122                    supporting_row(content, counter, 0., &s)
1123                }),
1124            )
1125    }
1126}