1use crate::capabilities::foundation::theme::use_theme;
7use gpui::{prelude::*, *};
8use std::ops::Range;
9
10use crate::capabilities::controls::text_util;
11
12pub fn init(cx: &mut App) {
13 if !crate::capabilities::foundation::initialization::begin(cx, "textarea-state") {
14 return;
15 }
16 cx.bind_keys([
17 KeyBinding::new("backspace", Backspace, Some("Textarea")),
18 KeyBinding::new("delete", Delete, Some("Textarea")),
19 KeyBinding::new("left", Left, Some("Textarea")),
20 KeyBinding::new("right", Right, Some("Textarea")),
21 KeyBinding::new("up", Up, Some("Textarea")),
22 KeyBinding::new("down", Down, Some("Textarea")),
23 KeyBinding::new("shift-left", SelectLeft, Some("Textarea")),
24 KeyBinding::new("shift-right", SelectRight, Some("Textarea")),
25 KeyBinding::new("shift-up", SelectUp, Some("Textarea")),
26 KeyBinding::new("shift-down", SelectDown, Some("Textarea")),
27 KeyBinding::new("home", Home, Some("Textarea")),
28 KeyBinding::new("end", End, Some("Textarea")),
29 KeyBinding::new("enter", Enter, Some("Textarea")),
30 KeyBinding::new("shift-enter", ShiftEnter, Some("Textarea")),
31 KeyBinding::new("tab", Tab, Some("Textarea")),
32 KeyBinding::new("shift-tab", ShiftTab, Some("Textarea")),
33 #[cfg(target_os = "macos")]
34 KeyBinding::new("cmd-a", SelectAll, Some("Textarea")),
35 #[cfg(not(target_os = "macos"))]
36 KeyBinding::new("ctrl-a", SelectAll, Some("Textarea")),
37 #[cfg(target_os = "macos")]
38 KeyBinding::new("cmd-c", Copy, Some("Textarea")),
39 #[cfg(not(target_os = "macos"))]
40 KeyBinding::new("ctrl-c", Copy, Some("Textarea")),
41 #[cfg(target_os = "macos")]
42 KeyBinding::new("cmd-x", Cut, Some("Textarea")),
43 #[cfg(not(target_os = "macos"))]
44 KeyBinding::new("ctrl-x", Cut, Some("Textarea")),
45 #[cfg(target_os = "macos")]
46 KeyBinding::new("cmd-v", Paste, Some("Textarea")),
47 #[cfg(not(target_os = "macos"))]
48 KeyBinding::new("ctrl-v", Paste, Some("Textarea")),
49 KeyBinding::new("escape", Escape, Some("Textarea")),
50 #[cfg(target_os = "macos")]
51 KeyBinding::new("alt-left", WordLeft, Some("Textarea")),
52 #[cfg(target_os = "macos")]
53 KeyBinding::new("alt-right", WordRight, Some("Textarea")),
54 #[cfg(not(target_os = "macos"))]
55 KeyBinding::new("ctrl-left", WordLeft, Some("Textarea")),
56 #[cfg(not(target_os = "macos"))]
57 KeyBinding::new("ctrl-right", WordRight, Some("Textarea")),
58 #[cfg(target_os = "macos")]
59 KeyBinding::new("alt-shift-left", SelectWordLeft, Some("Textarea")),
60 #[cfg(target_os = "macos")]
61 KeyBinding::new("alt-shift-right", SelectWordRight, Some("Textarea")),
62 #[cfg(not(target_os = "macos"))]
63 KeyBinding::new("ctrl-shift-left", SelectWordLeft, Some("Textarea")),
64 #[cfg(not(target_os = "macos"))]
65 KeyBinding::new("ctrl-shift-right", SelectWordRight, Some("Textarea")),
66 ]);
67}
68
69actions!(
70 textarea_state,
71 [
72 Backspace,
73 Delete,
74 Left,
75 Right,
76 Up,
77 Down,
78 SelectLeft,
79 SelectRight,
80 SelectUp,
81 SelectDown,
82 SelectAll,
83 Home,
84 End,
85 Copy,
86 Cut,
87 Paste,
88 Enter,
89 ShiftEnter,
90 Tab,
91 ShiftTab,
92 Escape,
93 WordLeft,
94 WordRight,
95 SelectWordLeft,
96 SelectWordRight,
97 ]
98);
99
100#[derive(Clone, Debug)]
102pub enum TextareaEvent {
103 Change,
104 Focus,
105 Blur,
106 Enter,
107 ShiftEnter,
108 Tab,
109 ShiftTab,
110}
111
112impl EventEmitter<TextareaEvent> for TextareaState {}
113
114pub struct TextareaState {
116 focus_handle: FocusHandle,
117 pub scroll_handle: ScrollHandle,
118 pub content: SharedString,
119 pub placeholder: SharedString,
120 pub disabled: bool,
121 pub initialized: bool,
122 selected_range: Range<usize>,
123 selection_reversed: bool,
124 marked_range: Option<Range<usize>>,
125 last_layouts: Vec<WrappedLine>,
126 last_bounds: Option<Bounds<Pixels>>,
127 last_visual_line_count: usize,
128 last_line_height: Pixels,
129 is_selecting: bool,
130 was_focused: bool,
131 cursor_visible: bool,
132 _blink_task: Option<Task<()>>,
133 event_subscription: Option<Subscription>,
134}
135
136#[derive(Clone, Copy)]
137struct VisualLineInfo {
138 logical_line_idx: usize,
139 logical_start: usize,
140 local_start: usize,
141 local_end: usize,
142 origin_y: Pixels,
143}
144
145impl TextareaState {
146 pub fn new(cx: &mut Context<Self>) -> Self {
147 Self {
148 focus_handle: cx.focus_handle(),
149 scroll_handle: ScrollHandle::new(),
150 content: "".into(),
151 placeholder: "".into(),
152 disabled: false,
153 initialized: false,
154 selected_range: 0..0,
155 selection_reversed: false,
156 marked_range: None,
157 last_layouts: Vec::new(),
158 last_bounds: None,
159 last_visual_line_count: 1,
160 last_line_height: px(20.0),
161 is_selecting: false,
162 was_focused: false,
163 cursor_visible: true,
164 _blink_task: None,
165 event_subscription: None,
166 }
167 }
168
169 pub(super) fn replace_event_subscription(&mut self, subscription: Option<Subscription>) {
170 self.event_subscription = subscription;
171 }
172
173 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
175 self.placeholder = placeholder.into();
176 self
177 }
178
179 pub fn value(mut self, value: impl Into<SharedString>) -> Self {
185 self.content = value.into();
186 let len = self.content.len();
187 self.selected_range = len..len;
188 self
189 }
190
191 pub fn disabled(mut self, disabled: bool) -> Self {
193 self.disabled = disabled;
194 self
195 }
196
197 pub fn content(&self) -> &str {
198 &self.content
199 }
200
201 pub fn visual_line_count_for_layout(&self) -> usize {
202 self.visual_line_count()
203 }
204
205 pub fn set_value(
206 &mut self,
207 value: impl Into<SharedString>,
208 _window: &mut Window,
209 cx: &mut Context<Self>,
210 ) {
211 let value = value.into();
212 if self.content != value {
213 self.content = value;
214 let len = self.content.len();
215 self.selected_range = len..len;
216 self.marked_range.take();
217 self.selection_reversed = false;
218 self.invalidate_layout_cache();
219 cx.emit(TextareaEvent::Change);
220 cx.notify();
221 }
222 }
223
224 fn line_start_offsets(&self) -> Vec<usize> {
228 let mut offsets = vec![0usize];
229 for (i, ch) in self.content.char_indices() {
230 if ch == '\n' {
231 offsets.push(i + ch.len_utf8());
232 }
233 }
234 offsets
235 }
236
237 fn logical_line_for_offset(&self, offset: usize) -> usize {
238 let starts = self.line_start_offsets();
239 let mut line = 0;
240 for (i, &start) in starts.iter().enumerate() {
241 if start <= offset {
242 line = i;
243 } else {
244 break;
245 }
246 }
247 line
248 }
249
250 fn line_start_for_offset(&self, offset: usize) -> usize {
252 let starts = self.line_start_offsets();
253 let line = self.logical_line_for_offset(offset);
254 starts[line]
255 }
256
257 fn line_end_for_offset(&self, offset: usize) -> usize {
259 let starts = self.line_start_offsets();
260 let line = self.logical_line_for_offset(offset);
261 if line + 1 < starts.len() {
262 starts[line + 1] - 1
263 } else {
264 self.content.len()
265 }
266 }
267
268 fn visual_line_count(&self) -> usize {
269 self.last_visual_line_count.max(1)
270 }
271
272 fn lines(&self) -> Vec<&str> {
274 if self.content.is_empty() {
275 return vec![""];
276 }
277 let s: &str = &self.content;
278 let mut result: Vec<&str> = s.split('\n').collect();
279 if result.is_empty() {
281 result.push("");
282 }
283 result
284 }
285
286 fn visual_lines_for_layouts(
287 &self,
288 layouts: &[WrappedLine],
289 line_height: Pixels,
290 ) -> Vec<VisualLineInfo> {
291 let starts = self.line_start_offsets();
292 let mut visual_lines = Vec::new();
293 let mut current_y = Pixels::ZERO;
294
295 for (logical_line_idx, wrapped_line) in layouts.iter().enumerate() {
296 let logical_start = starts.get(logical_line_idx).copied().unwrap_or(0);
297 let mut local_start = 0;
298 let mut visual_line_idx = 0;
299
300 for wrap_boundary in wrapped_line.wrap_boundaries() {
301 let glyph =
302 &wrapped_line.runs()[wrap_boundary.run_ix].glyphs[wrap_boundary.glyph_ix];
303 let local_end = glyph.index;
304 visual_lines.push(VisualLineInfo {
305 logical_line_idx,
306 logical_start,
307 local_start,
308 local_end,
309 origin_y: current_y + line_height * visual_line_idx as f32,
310 });
311 local_start = local_end;
312 visual_line_idx += 1;
313 }
314
315 visual_lines.push(VisualLineInfo {
316 logical_line_idx,
317 logical_start,
318 local_start,
319 local_end: wrapped_line.text.len(),
320 origin_y: current_y + line_height * visual_line_idx as f32,
321 });
322
323 current_y += line_height * (visual_line_idx + 1) as f32;
324 }
325
326 if visual_lines.is_empty() {
327 visual_lines.push(VisualLineInfo {
328 logical_line_idx: 0,
329 logical_start: 0,
330 local_start: 0,
331 local_end: 0,
332 origin_y: Pixels::ZERO,
333 });
334 }
335
336 visual_lines
337 }
338
339 fn visual_lines(&self, line_height: Pixels) -> Vec<VisualLineInfo> {
340 self.visual_lines_for_layouts(&self.last_layouts, line_height)
341 }
342
343 fn point_for_offset_in_layouts(
344 &self,
345 layouts: &[WrappedLine],
346 offset: usize,
347 line_height: Pixels,
348 ) -> Option<(usize, Point<Pixels>)> {
349 let logical_line_idx = self.logical_line_for_offset(offset);
350 let logical_start = *self.line_start_offsets().get(logical_line_idx)?;
351 let wrapped_line = layouts.get(logical_line_idx)?;
352 let local_offset = offset
353 .saturating_sub(logical_start)
354 .min(wrapped_line.text.len());
355 wrapped_line
356 .position_for_index(local_offset, line_height)
357 .map(|point| (logical_line_idx, point))
358 }
359
360 fn point_for_offset(
361 &self,
362 offset: usize,
363 line_height: Pixels,
364 ) -> Option<(usize, Point<Pixels>)> {
365 self.point_for_offset_in_layouts(&self.last_layouts, offset, line_height)
366 }
367
368 fn vertical_navigation_target(
369 &self,
370 offset: usize,
371 delta: isize,
372 line_height: Pixels,
373 ) -> Option<usize> {
374 if self.last_layouts.is_empty() {
375 return None;
376 }
377
378 let (logical_line_idx, cursor_point) = self.point_for_offset(offset, line_height)?;
379 let visual_lines = self.visual_lines(line_height);
380 let logical_line_origin_y = visual_lines
381 .iter()
382 .find(|line| line.logical_line_idx == logical_line_idx)?
383 .origin_y;
384 let cursor_visual_y = logical_line_origin_y + cursor_point.y;
385 let current_visual_line_idx = visual_lines.iter().position(|line| {
386 cursor_visual_y >= line.origin_y && cursor_visual_y < line.origin_y + line_height
387 })?;
388
389 let target_visual_line_idx = current_visual_line_idx as isize + delta;
390 if target_visual_line_idx < 0 || target_visual_line_idx >= visual_lines.len() as isize {
391 return None;
392 }
393
394 let target_line = visual_lines[target_visual_line_idx as usize];
395 let target_wrapped_line = self.last_layouts.get(target_line.logical_line_idx)?;
396 let logical_line_origin_y = visual_lines
397 .iter()
398 .find(|line| line.logical_line_idx == target_line.logical_line_idx)?
399 .origin_y;
400 let target_local_y = target_line.origin_y - logical_line_origin_y;
401 let target_local_x = cursor_point.x;
402 let target_local_offset = target_wrapped_line
403 .closest_index_for_position(gpui::point(target_local_x, target_local_y), line_height)
404 .unwrap_or_else(|boundary| boundary);
405 Some(target_line.logical_start + target_local_offset)
406 }
407
408 fn cursor_offset(&self) -> usize {
411 text_util::cursor_offset(&self.selected_range, self.selection_reversed)
412 }
413
414 fn move_to(&mut self, offset: usize, cx: &mut Context<Self>) {
415 let offset = self.clamp_offset(offset);
416 self.selected_range = offset..offset;
417 self.selection_reversed = false;
418 self.reset_blink(cx);
419 cx.notify();
420 }
421
422 fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
423 let offset = self.clamp_offset(offset);
424 (self.selected_range, self.selection_reversed) = text_util::extend_selection(
425 self.selected_range.clone(),
426 self.selection_reversed,
427 offset,
428 );
429 self.reset_blink(cx);
430 cx.notify();
431 }
432
433 fn clamp_offset(&self, offset: usize) -> usize {
434 text_util::clamp_offset(&self.content, offset)
435 }
436
437 fn previous_boundary(&self, offset: usize) -> usize {
440 text_util::previous_grapheme_boundary(&self.content, offset)
441 }
442
443 fn next_boundary(&self, offset: usize) -> usize {
444 text_util::next_grapheme_boundary(&self.content, offset)
445 }
446
447 fn previous_word_boundary(&self, offset: usize) -> usize {
448 text_util::previous_word_boundary(&self.content, offset)
449 }
450
451 fn next_word_boundary(&self, offset: usize) -> usize {
452 text_util::next_word_boundary(&self.content, offset)
453 }
454
455 fn offset_to_utf16(&self, offset: usize) -> usize {
458 crate::capabilities::controls::text_util::offset_to_utf16(&self.content, offset)
459 }
460
461 fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
462 crate::capabilities::controls::text_util::range_to_utf16(&self.content, range)
463 }
464
465 fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
466 crate::capabilities::controls::text_util::range_from_utf16(&self.content, range_utf16)
467 }
468
469 fn invalidate_layout_cache(&mut self) {
472 self.last_layouts.clear();
473 self.last_bounds = None;
474 self.last_visual_line_count = 1;
475 }
476
477 fn start_blink(&mut self, cx: &mut Context<Self>) {
480 self._blink_task = None;
481 self.cursor_visible = true;
482 self._blink_task = Some(cx.spawn(async |this, cx| loop {
483 cx.background_executor()
484 .timer(std::time::Duration::from_millis(500))
485 .await;
486 let ok = this.update(cx, |this: &mut Self, cx: &mut Context<Self>| {
487 this.cursor_visible = !this.cursor_visible;
488 cx.notify();
489 });
490 if ok.is_err() {
491 break;
492 }
493 }));
494 }
495
496 fn stop_blink(&mut self) {
497 self._blink_task = None;
498 self.cursor_visible = true;
499 }
500
501 fn reset_blink(&mut self, cx: &mut Context<Self>) {
502 self.stop_blink();
503 self.start_blink(cx);
504 }
505
506 fn sync_focus_state(&mut self, is_focused: bool, _window: &mut Window, cx: &mut Context<Self>) {
507 if self.was_focused == is_focused {
508 return;
509 }
510
511 self.was_focused = is_focused;
512 if is_focused {
513 self.start_blink(cx);
514 cx.emit(TextareaEvent::Focus);
515 } else {
516 self.stop_blink();
517 self.is_selecting = false;
518 cx.emit(TextareaEvent::Blur);
519 }
520 cx.notify();
521 }
522
523 fn on_mouse_down(
526 &mut self,
527 event: &MouseDownEvent,
528 _window: &mut Window,
529 cx: &mut Context<Self>,
530 ) {
531 self.is_selecting = true;
532 let idx = self.index_for_mouse_position(event.position);
533 if event.click_count == 2 {
534 let start = self.previous_word_boundary(idx);
535 let end = self.next_word_boundary(idx);
536 self.selected_range = start..end;
537 self.selection_reversed = false;
538 self.reset_blink(cx);
539 cx.notify();
540 } else if event.modifiers.shift {
541 self.select_to(idx, cx);
542 } else {
543 self.move_to(idx, cx);
544 }
545 }
546
547 fn on_mouse_up(&mut self, _: &MouseUpEvent, _: &mut Window, _cx: &mut Context<Self>) {
548 self.is_selecting = false;
549 }
550
551 fn on_mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {
552 if self.is_selecting {
553 let idx = self.index_for_mouse_position(event.position);
554 self.select_to(idx, cx);
555 }
556 }
557
558 fn index_for_mouse_position(&self, position: Point<Pixels>) -> usize {
559 if self.content.is_empty() {
560 return 0;
561 }
562 let Some(bounds) = self.last_bounds.as_ref() else {
563 return 0;
564 };
565 if self.last_layouts.is_empty() {
566 return 0;
567 }
568
569 let relative_y = position.y - bounds.top();
570 if relative_y <= Pixels::ZERO {
571 return 0;
572 }
573 if position.y >= bounds.bottom() {
574 return self.content.len();
575 }
576
577 let line_height = self.last_line_height;
578 let visual_lines = self.visual_lines(line_height);
579 let relative_x = (position.x - bounds.left()).max(Pixels::ZERO);
580
581 for visual_line in &visual_lines {
582 if relative_y >= visual_line.origin_y && relative_y < visual_line.origin_y + line_height
583 {
584 let Some(wrapped_line) = self.last_layouts.get(visual_line.logical_line_idx) else {
585 return self.content.len();
586 };
587 let logical_line_origin_y = visual_lines
588 .iter()
589 .find(|line| line.logical_line_idx == visual_line.logical_line_idx)
590 .map(|line| line.origin_y)
591 .unwrap_or(Pixels::ZERO);
592 let local_y = relative_y - logical_line_origin_y;
593 let local_offset = wrapped_line
594 .closest_index_for_position(gpui::point(relative_x, local_y), line_height)
595 .unwrap_or_else(|boundary| boundary);
596 return visual_line.logical_start + local_offset;
597 }
598 }
599
600 self.content.len()
601 }
602
603 pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
606 if self.selected_range.is_empty() {
607 self.select_to(self.previous_boundary(self.cursor_offset()), cx);
608 }
609 self.replace_text_in_range(None, "", window, cx);
610 }
611
612 pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
613 if self.selected_range.is_empty() {
614 self.select_to(self.next_boundary(self.cursor_offset()), cx);
615 }
616 self.replace_text_in_range(None, "", window, cx);
617 }
618
619 pub fn left(&mut self, _: &Left, _: &mut Window, cx: &mut Context<Self>) {
620 if self.selected_range.is_empty() {
621 self.move_to(self.previous_boundary(self.cursor_offset()), cx);
622 } else {
623 self.move_to(self.selected_range.start, cx);
624 }
625 }
626
627 pub fn right(&mut self, _: &Right, _: &mut Window, cx: &mut Context<Self>) {
628 if self.selected_range.is_empty() {
629 self.move_to(self.next_boundary(self.cursor_offset()), cx);
630 } else {
631 self.move_to(self.selected_range.end, cx);
632 }
633 }
634
635 pub fn up(&mut self, _: &Up, _: &mut Window, cx: &mut Context<Self>) {
636 if !self.selected_range.is_empty() {
637 self.move_to(self.selected_range.start, cx);
638 return;
639 }
640 let line_height = self.last_line_height;
641 if let Some(new_offset) =
642 self.vertical_navigation_target(self.cursor_offset(), -1, line_height)
643 {
644 self.move_to(new_offset, cx);
645 }
646 }
647
648 pub fn down(&mut self, _: &Down, _: &mut Window, cx: &mut Context<Self>) {
649 if !self.selected_range.is_empty() {
650 self.move_to(self.selected_range.end, cx);
651 return;
652 }
653 let line_height = self.last_line_height;
654 if let Some(new_offset) =
655 self.vertical_navigation_target(self.cursor_offset(), 1, line_height)
656 {
657 self.move_to(new_offset, cx);
658 }
659 }
660
661 pub fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
662 self.select_to(self.previous_boundary(self.cursor_offset()), cx);
663 }
664
665 pub fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
666 self.select_to(self.next_boundary(self.cursor_offset()), cx);
667 }
668
669 pub fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
670 let line_height = self.last_line_height;
671 if let Some(new_offset) =
672 self.vertical_navigation_target(self.cursor_offset(), -1, line_height)
673 {
674 self.select_to(new_offset, cx);
675 }
676 }
677
678 pub fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
679 let line_height = self.last_line_height;
680 if let Some(new_offset) =
681 self.vertical_navigation_target(self.cursor_offset(), 1, line_height)
682 {
683 self.select_to(new_offset, cx);
684 }
685 }
686
687 pub fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
688 self.selected_range = 0..self.content.len();
689 self.selection_reversed = false;
690 self.reset_blink(cx);
691 cx.notify();
692 }
693
694 pub fn home(&mut self, _: &Home, _: &mut Window, cx: &mut Context<Self>) {
695 let line_start = self.line_start_for_offset(self.cursor_offset());
696 self.move_to(line_start, cx);
697 }
698
699 pub fn end(&mut self, _: &End, _: &mut Window, cx: &mut Context<Self>) {
700 let line_end = self.line_end_for_offset(self.cursor_offset());
701 self.move_to(line_end, cx);
702 }
703
704 pub fn word_left(&mut self, _: &WordLeft, _: &mut Window, cx: &mut Context<Self>) {
705 let offset = self.previous_word_boundary(self.cursor_offset());
706 if self.selected_range.is_empty() {
707 self.move_to(offset, cx);
708 } else {
709 self.move_to(self.selected_range.start.min(offset), cx);
710 }
711 }
712
713 pub fn word_right(&mut self, _: &WordRight, _: &mut Window, cx: &mut Context<Self>) {
714 let offset = self.next_word_boundary(self.cursor_offset());
715 if self.selected_range.is_empty() {
716 self.move_to(offset, cx);
717 } else {
718 self.move_to(self.selected_range.end.max(offset), cx);
719 }
720 }
721
722 pub fn select_word_left(&mut self, _: &SelectWordLeft, _: &mut Window, cx: &mut Context<Self>) {
723 self.select_to(self.previous_word_boundary(self.cursor_offset()), cx);
724 }
725
726 pub fn select_word_right(
727 &mut self,
728 _: &SelectWordRight,
729 _: &mut Window,
730 cx: &mut Context<Self>,
731 ) {
732 self.select_to(self.next_word_boundary(self.cursor_offset()), cx);
733 }
734
735 pub fn enter(&mut self, _: &Enter, window: &mut Window, cx: &mut Context<Self>) {
736 self.replace_text_in_range(None, "\n", window, cx);
737 cx.emit(TextareaEvent::Enter);
738 }
739
740 pub fn shift_enter(&mut self, _: &ShiftEnter, _window: &mut Window, cx: &mut Context<Self>) {
741 cx.emit(TextareaEvent::ShiftEnter);
742 }
743
744 pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
745 self.replace_text_in_range(None, " ", window, cx);
746 cx.emit(TextareaEvent::Tab);
747 }
748
749 pub fn shift_tab(&mut self, _: &ShiftTab, _window: &mut Window, cx: &mut Context<Self>) {
750 cx.emit(TextareaEvent::ShiftTab);
751 }
752
753 pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
754 if !self.selected_range.is_empty() {
755 cx.write_to_clipboard(ClipboardItem::new_string(
756 self.content[self.selected_range.clone()].to_string(),
757 ));
758 }
759 }
760
761 pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
762 if !self.selected_range.is_empty() {
763 cx.write_to_clipboard(ClipboardItem::new_string(
764 self.content[self.selected_range.clone()].to_string(),
765 ));
766 self.replace_text_in_range(None, "", window, cx);
767 }
768 }
769
770 pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
771 if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) {
772 self.replace_text_in_range(None, &text, window, cx);
773 }
774 }
775
776 pub fn escape(&mut self, _: &Escape, _window: &mut Window, cx: &mut Context<Self>) {
777 self.selected_range = self.content.len()..self.content.len();
778 cx.notify();
779 }
780}
781
782impl EntityInputHandler for TextareaState {
785 fn text_for_range(
786 &mut self,
787 range_utf16: Range<usize>,
788 actual_range: &mut Option<Range<usize>>,
789 _window: &mut Window,
790 _cx: &mut Context<Self>,
791 ) -> Option<String> {
792 let range = self.range_from_utf16(&range_utf16);
793 actual_range.replace(self.range_to_utf16(&range));
794 Some(self.content[range].to_string())
795 }
796
797 fn selected_text_range(
798 &mut self,
799 _ignore_disabled_input: bool,
800 _window: &mut Window,
801 _cx: &mut Context<Self>,
802 ) -> Option<UTF16Selection> {
803 Some(UTF16Selection {
804 range: self.range_to_utf16(&self.selected_range),
805 reversed: self.selection_reversed,
806 })
807 }
808
809 fn marked_text_range(
810 &self,
811 _window: &mut Window,
812 _cx: &mut Context<Self>,
813 ) -> Option<Range<usize>> {
814 self.marked_range
815 .as_ref()
816 .map(|range| self.range_to_utf16(range))
817 }
818
819 fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
820 self.marked_range = None;
821 self.invalidate_layout_cache();
822 }
823
824 fn replace_text_in_range(
825 &mut self,
826 range_utf16: Option<Range<usize>>,
827 new_text: &str,
828 window: &mut Window,
829 cx: &mut Context<Self>,
830 ) {
831 let range = range_utf16
832 .as_ref()
833 .map(|r| self.range_from_utf16(r))
834 .or(self.marked_range.clone())
835 .unwrap_or(self.selected_range.clone());
836
837 self.content =
838 (self.content[0..range.start].to_owned() + new_text + &self.content[range.end..])
839 .into();
840 self.selected_range = range.start + new_text.len()..range.start + new_text.len();
841 self.marked_range.take();
842 self.selection_reversed = false;
843 if self.focus_handle.is_focused(window) {
844 self.reset_blink(cx);
845 }
846 self.invalidate_layout_cache();
847 cx.emit(TextareaEvent::Change);
848 cx.notify();
849 }
850
851 fn replace_and_mark_text_in_range(
852 &mut self,
853 range_utf16: Option<Range<usize>>,
854 new_text: &str,
855 new_selected_range_utf16: Option<Range<usize>>,
856 window: &mut Window,
857 cx: &mut Context<Self>,
858 ) {
859 let range = range_utf16
860 .as_ref()
861 .map(|r| self.range_from_utf16(r))
862 .or(self.marked_range.clone())
863 .unwrap_or(self.selected_range.clone());
864
865 self.content =
866 (self.content[0..range.start].to_owned() + new_text + &self.content[range.end..])
867 .into();
868 if !new_text.is_empty() {
869 self.marked_range = Some(range.start..range.start + new_text.len());
870 } else {
871 self.marked_range = None;
872 }
873 self.selected_range = new_selected_range_utf16
874 .as_ref()
875 .map(|r| text_util::range_from_utf16(new_text, r))
876 .map(|new_range| new_range.start + range.start..new_range.end + range.start)
877 .unwrap_or_else(|| range.start + new_text.len()..range.start + new_text.len());
878
879 self.selection_reversed = false;
880 if self.focus_handle.is_focused(window) {
881 self.reset_blink(cx);
882 }
883 self.invalidate_layout_cache();
884 cx.notify();
885 }
886
887 fn bounds_for_range(
888 &mut self,
889 range_utf16: Range<usize>,
890 bounds: Bounds<Pixels>,
891 _window: &mut Window,
892 _cx: &mut Context<Self>,
893 ) -> Option<Bounds<Pixels>> {
894 if self.last_layouts.is_empty() {
895 return None;
896 }
897
898 let range = self.range_from_utf16(&range_utf16);
899 let line_height = bounds.size.height / self.visual_line_count() as f32;
900 let visual_lines = self.visual_lines(line_height);
901
902 let (start_logical_line_idx, start_point) =
903 self.point_for_offset(range.start, line_height)?;
904 let (end_logical_line_idx, end_point) = self.point_for_offset(range.end, line_height)?;
905 let start_logical_origin_y = visual_lines
906 .iter()
907 .find(|line| line.logical_line_idx == start_logical_line_idx)?
908 .origin_y;
909 let end_logical_origin_y = visual_lines
910 .iter()
911 .find(|line| line.logical_line_idx == end_logical_line_idx)?
912 .origin_y;
913
914 Some(Bounds::from_corners(
915 point(
916 bounds.left() + start_point.x,
917 bounds.top() + start_logical_origin_y + start_point.y,
918 ),
919 point(
920 bounds.left() + end_point.x,
921 bounds.top() + end_logical_origin_y + end_point.y + line_height,
922 ),
923 ))
924 }
925
926 fn character_index_for_point(
927 &mut self,
928 point: Point<Pixels>,
929 _window: &mut Window,
930 _cx: &mut Context<Self>,
931 ) -> Option<usize> {
932 let bounds = self.last_bounds.as_ref()?;
933 bounds.localize(&point)?;
934 if self.last_layouts.is_empty() {
935 return None;
936 }
937
938 let byte_offset = self.index_for_mouse_position(point);
939 Some(self.offset_to_utf16(byte_offset))
940 }
941}
942
943impl Render for TextareaState {
946 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
947 let entity = cx.entity();
948 div()
949 .w_full()
950 .on_mouse_down(MouseButton::Left, {
951 let entity = entity.clone();
952 move |event: &MouseDownEvent, window: &mut Window, cx: &mut App| {
953 entity.update(cx, |state, cx| {
954 state.on_mouse_down(event, window, cx);
955 });
956 }
957 })
958 .on_mouse_up(MouseButton::Left, {
959 let entity = entity.clone();
960 move |event: &MouseUpEvent, window: &mut Window, cx: &mut App| {
961 entity.update(cx, |state, cx| {
962 state.on_mouse_up(event, window, cx);
963 });
964 }
965 })
966 .on_mouse_up_out(MouseButton::Left, {
967 let entity = entity.clone();
968 move |event: &MouseUpEvent, window: &mut Window, cx: &mut App| {
969 entity.update(cx, |state, cx| {
970 state.on_mouse_up(event, window, cx);
971 });
972 }
973 })
974 .on_mouse_move({
975 let entity = entity.clone();
976 move |event: &MouseMoveEvent, window: &mut Window, cx: &mut App| {
977 entity.update(cx, |state, cx| {
978 state.on_mouse_move(event, window, cx);
979 });
980 }
981 })
982 .child(TextareaTextElement {
983 state: entity.clone(),
984 })
985 }
986}
987
988impl Focusable for TextareaState {
989 fn focus_handle(&self, _: &App) -> FocusHandle {
990 self.focus_handle.clone()
991 }
992}
993
994struct TextareaTextElement {
997 state: Entity<TextareaState>,
998}
999
1000struct TextareaPrepaintState {
1001 lines: Vec<WrappedLine>,
1002 cursor: Option<PaintQuad>,
1003 selections: Vec<PaintQuad>,
1004}
1005
1006impl IntoElement for TextareaTextElement {
1007 type Element = Self;
1008 fn into_element(self) -> Self::Element {
1009 self
1010 }
1011}
1012
1013impl Element for TextareaTextElement {
1014 type RequestLayoutState = ();
1015 type PrepaintState = TextareaPrepaintState;
1016
1017 fn id(&self) -> Option<ElementId> {
1018 None
1019 }
1020
1021 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
1022 None
1023 }
1024
1025 fn request_layout(
1026 &mut self,
1027 _id: Option<&GlobalElementId>,
1028 _inspector_id: Option<&InspectorElementId>,
1029 window: &mut Window,
1030 cx: &mut App,
1031 ) -> (LayoutId, Self::RequestLayoutState) {
1032 let state = self.state.read(cx);
1033 let line_count = state.visual_line_count();
1034 let line_height = window.line_height();
1035 let mut style = Style::default();
1036 style.size.width = relative(1.).into();
1037 style.size.height = (line_height * line_count as f32).into();
1038 (window.request_layout(style, [], cx), ())
1039 }
1040
1041 fn prepaint(
1042 &mut self,
1043 _id: Option<&GlobalElementId>,
1044 _inspector_id: Option<&InspectorElementId>,
1045 bounds: Bounds<Pixels>,
1046 _request_layout: &mut Self::RequestLayoutState,
1047 window: &mut Window,
1048 cx: &mut App,
1049 ) -> Self::PrepaintState {
1050 let input = self.state.read(cx);
1051 let text_style = window.text_style();
1052 let theme = use_theme(cx);
1053 let font_size = text_style.font_size.to_pixels(window.rem_size());
1054 let line_height = window.line_height();
1055
1056 let content_lines = input.lines();
1057 let starts = input.line_start_offsets();
1058 let selected_range = input.selected_range.clone();
1059 let cursor_offset = input.cursor_offset();
1060 let is_empty = input.content.is_empty();
1061 let placeholder = input.placeholder.clone();
1062 let marked_range = input.marked_range.clone();
1063 let wrap_width = Some(bounds.size.width.max(px(1.0)));
1064
1065 let mut wrapped_lines = Vec::with_capacity(content_lines.len().max(1));
1066 for (line_idx, line_text) in content_lines.iter().enumerate() {
1067 let (display_text, text_color) = if is_empty && line_idx == 0 {
1068 (placeholder.clone(), theme.tokens.muted_foreground)
1069 } else if is_empty {
1070 (SharedString::from(""), text_style.color)
1071 } else {
1072 (SharedString::from(line_text.to_string()), text_style.color)
1073 };
1074
1075 let base_run = TextRun {
1076 len: display_text.len(),
1077 font: text_style.font(),
1078 color: text_color,
1079 background_color: None,
1080 underline: None,
1081 strikethrough: None,
1082 };
1083
1084 let runs = if !is_empty {
1086 if let Some(ref marked) = marked_range {
1087 let line_start = starts[line_idx];
1088 let line_end = line_start + line_text.len();
1089 let mark_start = marked.start.max(line_start).saturating_sub(line_start);
1090 let mark_end = marked.end.min(line_end).saturating_sub(line_start);
1091 if mark_start < mark_end && mark_start < display_text.len() {
1092 vec![
1093 TextRun {
1094 len: mark_start,
1095 ..base_run.clone()
1096 },
1097 TextRun {
1098 len: mark_end - mark_start,
1099 underline: Some(UnderlineStyle {
1100 color: Some(base_run.color),
1101 thickness: px(1.0),
1102 wavy: false,
1103 }),
1104 ..base_run.clone()
1105 },
1106 TextRun {
1107 len: display_text.len() - mark_end,
1108 ..base_run.clone()
1109 },
1110 ]
1111 .into_iter()
1112 .filter(|r| r.len > 0)
1113 .collect()
1114 } else {
1115 vec![base_run]
1116 }
1117 } else {
1118 vec![base_run]
1119 }
1120 } else {
1121 vec![base_run]
1122 };
1123
1124 let mut shaped = window
1125 .text_system()
1126 .shape_text(display_text, font_size, &runs, wrap_width, None)
1127 .unwrap_or_default();
1128 wrapped_lines.push(shaped.pop().unwrap_or_default());
1129 }
1130
1131 let visual_lines = input.visual_lines_for_layouts(&wrapped_lines, line_height);
1132 let mut cursor_quad = None;
1133 let mut selection_quads = Vec::new();
1134
1135 if selected_range.is_empty() {
1136 if let Some((logical_line_idx, cursor_point)) =
1137 input.point_for_offset_in_layouts(&wrapped_lines, cursor_offset, line_height)
1138 {
1139 let logical_line_origin_y = visual_lines
1140 .iter()
1141 .find(|line| line.logical_line_idx == logical_line_idx)
1142 .map(|line| line.origin_y)
1143 .unwrap_or(Pixels::ZERO);
1144 cursor_quad = Some(fill(
1145 Bounds::new(
1146 point(
1147 bounds.left() + cursor_point.x,
1148 bounds.top() + logical_line_origin_y + cursor_point.y,
1149 ),
1150 size(px(2.), line_height),
1151 ),
1152 theme.tokens.primary,
1153 ));
1154 }
1155 } else if !is_empty {
1156 for visual_line in &visual_lines {
1157 let visual_start = visual_line.logical_start + visual_line.local_start;
1158 let visual_end = visual_line.logical_start + visual_line.local_end;
1159 let overlaps_text =
1160 selected_range.start < visual_end && selected_range.end > visual_start;
1161 let spans_newline = selected_range.end > visual_end
1162 && visual_line.local_end
1163 == wrapped_lines
1164 .get(visual_line.logical_line_idx)
1165 .map(|line| line.text.len())
1166 .unwrap_or(0);
1167
1168 if !overlaps_text && !spans_newline {
1169 continue;
1170 }
1171
1172 let Some(wrapped_line) = wrapped_lines.get(visual_line.logical_line_idx) else {
1173 continue;
1174 };
1175 let local_start = selected_range
1176 .start
1177 .max(visual_start)
1178 .saturating_sub(visual_line.logical_start)
1179 .min(wrapped_line.text.len());
1180 let local_end = selected_range
1181 .end
1182 .min(visual_end)
1183 .saturating_sub(visual_line.logical_start)
1184 .min(wrapped_line.text.len());
1185 let Some(start_point) = wrapped_line.position_for_index(local_start, line_height)
1186 else {
1187 continue;
1188 };
1189 let end_point = wrapped_line
1190 .position_for_index(local_end, line_height)
1191 .unwrap_or(start_point);
1192 let logical_line_origin_y = visual_lines
1193 .iter()
1194 .find(|line| line.logical_line_idx == visual_line.logical_line_idx)
1195 .map(|line| line.origin_y)
1196 .unwrap_or(Pixels::ZERO);
1197 let x_end = if spans_newline {
1198 wrapped_line.width().max(end_point.x + px(4.0))
1199 } else {
1200 end_point.x
1201 };
1202
1203 selection_quads.push(fill(
1204 Bounds::from_corners(
1205 point(
1206 bounds.left() + start_point.x,
1207 bounds.top() + logical_line_origin_y + start_point.y,
1208 ),
1209 point(
1210 bounds.left() + x_end,
1211 bounds.top() + logical_line_origin_y + end_point.y + line_height,
1212 ),
1213 ),
1214 theme.tokens.primary.opacity(0.25),
1215 ));
1216 }
1217 }
1218 TextareaPrepaintState {
1219 lines: wrapped_lines,
1220 cursor: cursor_quad,
1221 selections: selection_quads,
1222 }
1223 }
1224
1225 fn paint(
1226 &mut self,
1227 _id: Option<&GlobalElementId>,
1228 _inspector_id: Option<&InspectorElementId>,
1229 bounds: Bounds<Pixels>,
1230 _request_layout: &mut Self::RequestLayoutState,
1231 prepaint: &mut Self::PrepaintState,
1232 window: &mut Window,
1233 cx: &mut App,
1234 ) {
1235 let focus_handle = self.state.read(cx).focus_handle.clone();
1236 let disabled = self.state.read(cx).disabled;
1237 let line_height = window.line_height();
1238
1239 if !disabled {
1241 window.handle_input(
1242 &focus_handle,
1243 ElementInputHandler::new(bounds, self.state.clone()),
1244 cx,
1245 );
1246 }
1247
1248 for selection in prepaint.selections.drain(..) {
1250 window.paint_quad(selection);
1251 }
1252
1253 let lines = std::mem::take(&mut prepaint.lines);
1255 let mut painted_lines = Vec::with_capacity(lines.len());
1256 let mut current_y = Pixels::ZERO;
1257 for line in lines.into_iter() {
1258 let origin = point(bounds.left(), bounds.top() + current_y);
1259 let _ = line.paint(
1260 origin,
1261 line_height,
1262 TextAlign::default(),
1263 Some(bounds),
1264 window,
1265 cx,
1266 );
1267 current_y += line.size(line_height).height;
1268 painted_lines.push(line);
1269 }
1270
1271 let is_focused = focus_handle.is_focused(window);
1273 if is_focused {
1274 let cursor_visible = self.state.read(cx).cursor_visible;
1275 if cursor_visible {
1276 if let Some(cursor) = prepaint.cursor.take() {
1277 window.paint_quad(cursor);
1278 }
1279 }
1280 }
1281
1282 self.state.update(cx, |state, cx| {
1284 let visual_line_count = painted_lines
1285 .iter()
1286 .map(|line| line.wrap_boundaries().len() + 1)
1287 .sum::<usize>()
1288 .max(1);
1289 state.last_layouts = painted_lines;
1290 state.last_bounds = Some(bounds);
1291 state.last_line_height = line_height;
1292 if state.last_visual_line_count != visual_line_count {
1293 state.last_visual_line_count = visual_line_count;
1294 cx.notify();
1295 }
1296 state.sync_focus_state(is_focused, window, cx);
1297 });
1298 }
1299}
1300
1301pub fn wire_actions(state: &Entity<TextareaState>, window: &mut Window, cx: &App) -> Stateful<Div> {
1337 let disabled = state.read(cx).disabled;
1338 let focus_handle = state.read(cx).focus_handle(cx);
1339 let scroll_handle = state.read(cx).scroll_handle.clone();
1340 let focus_handle_for_mouse = focus_handle.clone();
1341
1342 div()
1343 .id(("textarea", state.entity_id()))
1344 .key_context("Textarea")
1345 .track_focus(&focus_handle.tab_index(0).tab_stop(true))
1346 .track_scroll(&scroll_handle)
1347 .overflow_y_scroll()
1348 .when(!disabled, |this| {
1349 this.on_mouse_down(MouseButton::Left, move |_event, window, _cx| {
1350 window.focus(&focus_handle_for_mouse);
1351 })
1352 .on_action(window.listener_for(state, TextareaState::backspace))
1353 .on_action(window.listener_for(state, TextareaState::delete))
1354 .on_action(window.listener_for(state, TextareaState::left))
1355 .on_action(window.listener_for(state, TextareaState::right))
1356 .on_action(window.listener_for(state, TextareaState::up))
1357 .on_action(window.listener_for(state, TextareaState::down))
1358 .on_action(window.listener_for(state, TextareaState::select_left))
1359 .on_action(window.listener_for(state, TextareaState::select_right))
1360 .on_action(window.listener_for(state, TextareaState::select_up))
1361 .on_action(window.listener_for(state, TextareaState::select_down))
1362 .on_action(window.listener_for(state, TextareaState::select_all))
1363 .on_action(window.listener_for(state, TextareaState::home))
1364 .on_action(window.listener_for(state, TextareaState::end))
1365 .on_action(window.listener_for(state, TextareaState::copy))
1366 .on_action(window.listener_for(state, TextareaState::cut))
1367 .on_action(window.listener_for(state, TextareaState::paste))
1368 .on_action(window.listener_for(state, TextareaState::enter))
1369 .on_action(window.listener_for(state, TextareaState::shift_enter))
1370 .on_action(window.listener_for(state, TextareaState::tab))
1371 .on_action(window.listener_for(state, TextareaState::shift_tab))
1372 .on_action(window.listener_for(state, TextareaState::escape))
1373 .on_action(window.listener_for(state, TextareaState::word_left))
1374 .on_action(window.listener_for(state, TextareaState::word_right))
1375 .on_action(window.listener_for(state, TextareaState::select_word_left))
1376 .on_action(window.listener_for(state, TextareaState::select_word_right))
1377 })
1378}
1379
1380#[cfg(test)]
1381mod tests {
1382 use super::*;
1383 use crate::capabilities::foundation::theme::{install_theme, Theme};
1384
1385 struct TestView {
1386 state: Entity<TextareaState>,
1387 }
1388
1389 #[gpui::test]
1390 fn builders_configure_common_state_options() {
1391 let mut app = TestApp::new();
1392 app.update(|cx| install_theme(cx, Theme::light()));
1393 let state = app.update(|cx| {
1394 cx.new(|cx| {
1395 TextareaState::new(cx)
1396 .value("hello")
1397 .placeholder("p")
1398 .disabled(true)
1399 })
1400 });
1401
1402 app.update(|cx| {
1403 let state = state.read(cx);
1404 assert_eq!(state.content(), "hello");
1405 assert_eq!(state.placeholder, "p");
1406 assert!(state.disabled);
1407 });
1408 }
1409
1410 impl Render for TestView {
1411 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1412 div()
1413 }
1414 }
1415
1416 #[gpui::test]
1417 fn word_left_moves_cursor_to_previous_word_boundary() {
1418 let mut app = TestApp::new();
1419 app.update(|cx| install_theme(cx, Theme::light()));
1420 let state = app.update(|cx| cx.new(TextareaState::new));
1421 let mut window = app.open_window(|_, _| TestView {
1422 state: state.clone(),
1423 });
1424
1425 let text = "foo bar baz";
1426 window.update(|view, window, cx| {
1427 view.state.update(cx, |state, cx| {
1428 state.set_value(text, window, cx);
1429 state.word_left(&WordLeft, window, cx);
1431 assert_eq!(state.selected_range, 8..8, "should stop before baz");
1432 state.word_left(&WordLeft, window, cx);
1433 assert_eq!(state.selected_range, 4..4, "should stop before bar");
1434 state.word_left(&WordLeft, window, cx);
1435 assert_eq!(state.selected_range, 0..0, "should reach start");
1436 });
1437 });
1438 }
1439
1440 #[gpui::test]
1441 fn word_right_moves_cursor_to_next_word_boundary() {
1442 let mut app = TestApp::new();
1443 app.update(|cx| install_theme(cx, Theme::light()));
1444 let state = app.update(|cx| cx.new(TextareaState::new));
1445 let mut window = app.open_window(|_, _| TestView {
1446 state: state.clone(),
1447 });
1448
1449 window.update(|view, window, cx| {
1450 view.state.update(cx, |state, cx| {
1451 state.set_value("foo bar baz", window, cx);
1452 state.selected_range = 0..0;
1453 state.word_right(&WordRight, window, cx);
1454 assert_eq!(state.selected_range, 4..4, "should stop at bar start");
1455 state.word_right(&WordRight, window, cx);
1456 assert_eq!(state.selected_range, 8..8, "should stop at baz start");
1457 state.word_right(&WordRight, window, cx);
1458 assert_eq!(state.selected_range, 11..11, "should reach end");
1459 });
1460 });
1461 }
1462
1463 #[gpui::test]
1464 fn word_movement_handles_unicode() {
1465 let mut app = TestApp::new();
1466 app.update(|cx| install_theme(cx, Theme::light()));
1467 let state = app.update(|cx| cx.new(TextareaState::new));
1468 let mut window = app.open_window(|_, _| TestView {
1469 state: state.clone(),
1470 });
1471
1472 let text = "中文 test";
1473 window.update(|view, window, cx| {
1474 view.state.update(cx, |state, cx| {
1475 state.set_value(text, window, cx);
1476 state.word_left(&WordLeft, window, cx);
1478 assert_eq!(state.selected_range, 7..7, "should stop before test");
1479 state.word_left(&WordLeft, window, cx);
1480 assert_eq!(state.selected_range, 0..0, "should reach start");
1481 });
1482 });
1483 }
1484
1485 #[gpui::test]
1486 fn grapheme_deletion_removes_whole_unicode_clusters() {
1487 let mut app = TestApp::new();
1488 app.update(|cx| install_theme(cx, Theme::light()));
1489 let state = app.update(|cx| cx.new(TextareaState::new));
1490 let mut window = app.open_window(|_, _| TestView {
1491 state: state.clone(),
1492 });
1493
1494 window.update(|view, window, cx| {
1495 view.state.update(cx, |state, cx| {
1496 state.set_value("a👩💻e\u{301}b", window, cx);
1497 state.backspace(&Backspace, window, cx);
1498 assert_eq!(state.content(), "a👩💻e\u{301}");
1499 assert_eq!(
1500 state.selected_range,
1501 state.content().len()..state.content().len()
1502 );
1503
1504 state.backspace(&Backspace, window, cx);
1505 assert_eq!(state.content(), "a👩💻");
1506 assert_eq!(
1507 state.selected_range,
1508 state.content().len()..state.content().len()
1509 );
1510
1511 state.selected_range = "a".len().."a".len();
1512 state.selection_reversed = false;
1513 state.delete(&Delete, window, cx);
1514 assert_eq!(state.content(), "a");
1515 assert_eq!(state.selected_range, "a".len().."a".len());
1516 });
1517 });
1518 }
1519
1520 #[gpui::test]
1521 fn selection_direction_flips_when_crossing_the_anchor() {
1522 let mut app = TestApp::new();
1523 app.update(|cx| install_theme(cx, Theme::light()));
1524 let state = app.update(|cx| cx.new(TextareaState::new));
1525 let mut window = app.open_window(|_, _| TestView {
1526 state: state.clone(),
1527 });
1528
1529 window.update(|view, window, cx| {
1530 view.state.update(cx, |state, cx| {
1531 let text = "a😀b";
1532 let emoji_start = "a".len();
1533 let emoji_end = "a😀".len();
1534
1535 state.set_value(text, window, cx);
1536 state.selected_range = emoji_start..emoji_start;
1537 state.selection_reversed = false;
1538 state.select_right(&SelectRight, window, cx);
1539 assert_eq!(state.selected_range, emoji_start..emoji_end);
1540 assert!(!state.selection_reversed);
1541
1542 state.select_left(&SelectLeft, window, cx);
1543 assert_eq!(state.selected_range, emoji_start..emoji_start);
1544 assert!(!state.selection_reversed);
1545 state.select_left(&SelectLeft, window, cx);
1546 assert_eq!(state.selected_range, 0..emoji_start);
1547 assert!(state.selection_reversed);
1548
1549 state.selected_range = emoji_end..emoji_end;
1550 state.selection_reversed = false;
1551 state.select_left(&SelectLeft, window, cx);
1552 assert_eq!(state.selected_range, emoji_start..emoji_end);
1553 assert!(state.selection_reversed);
1554 state.select_right(&SelectRight, window, cx);
1555 assert_eq!(state.selected_range, emoji_end..emoji_end);
1556 assert!(state.selection_reversed);
1557 state.select_right(&SelectRight, window, cx);
1558 assert_eq!(state.selected_range, emoji_end..text.len());
1559 assert!(!state.selection_reversed);
1560 });
1561 });
1562 }
1563
1564 #[gpui::test]
1565 fn utf16_ranges_preserve_astral_character_boundaries() {
1566 let mut app = TestApp::new();
1567 app.update(|cx| install_theme(cx, Theme::light()));
1568 let state = app.update(|cx| cx.new(TextareaState::new));
1569 let mut window = app.open_window(|_, _| TestView {
1570 state: state.clone(),
1571 });
1572
1573 window.update(|view, window, cx| {
1574 view.state.update(cx, |state, cx| {
1575 state.set_value("a😀b", window, cx);
1576 let mut actual_range = None;
1577 assert_eq!(
1578 state.text_for_range(1..3, &mut actual_range, window, cx),
1579 Some("😀".to_string())
1580 );
1581 assert_eq!(actual_range, Some(1..3));
1582
1583 state.selected_range = "a".len().."a😀".len();
1584 let selected = state
1585 .selected_text_range(false, window, cx)
1586 .expect("selection should be available");
1587 assert_eq!(selected.range, 1..3);
1588 assert!(!selected.reversed);
1589
1590 state.replace_text_in_range(Some(1..3), "", window, cx);
1591 assert_eq!(state.content(), "ab");
1592 assert_eq!(state.selected_range, 1..1);
1593 });
1594 });
1595 }
1596}