1use crate::capabilities::controls::text_util;
2use crate::capabilities::foundation::theme::use_theme;
3use crate::capabilities::primitives::avatar::{Avatar, AvatarSize};
4use crate::capabilities::scroll::scrollable::scrollable_vertical;
5use gpui::{prelude::*, *};
6use std::ops::Range;
7use std::rc::Rc;
8
9use crate::capabilities::foundation::edit;
10
11actions!(
12 mention_input,
13 [
14 MentionUp,
15 MentionDown,
16 MentionConfirm,
17 MentionCancel,
18 MentionBackspace,
19 MentionDelete,
20 MentionLeft,
21 MentionRight,
22 MentionHome,
23 MentionEnd,
24 MentionSelectAll,
25 MentionCopy,
26 MentionCut,
27 MentionPaste,
28 MentionEnter,
29 ]
30);
31
32const DROPDOWN_MARGIN: Pixels = px(4.0);
33
34#[derive(Clone, Debug, PartialEq)]
35pub struct MentionItem {
36 pub id: SharedString,
37 pub name: SharedString,
38 pub avatar_url: Option<SharedString>,
39}
40
41impl MentionItem {
42 pub fn new(id: impl Into<SharedString>, name: impl Into<SharedString>) -> Self {
43 Self {
44 id: id.into(),
45 name: name.into(),
46 avatar_url: None,
47 }
48 }
49
50 pub fn with_avatar(mut self, url: impl Into<SharedString>) -> Self {
51 self.avatar_url = Some(url.into());
52 self
53 }
54}
55
56#[derive(Clone, Debug)]
57pub struct Mention {
58 pub item: MentionItem,
59 pub range: Range<usize>,
60}
61
62#[derive(Clone, Debug)]
63pub enum MentionInputEvent {
64 Change,
65 MentionSelected(MentionItem),
66 Enter,
67 Focus,
68 Blur,
69}
70
71pub struct MentionInputState {
72 focus_handle: FocusHandle,
73 pub content: String,
74 pub placeholder: SharedString,
75 pub disabled: bool,
76 selected_range: Range<usize>,
77 selection_reversed: bool,
78 marked_range: Option<Range<usize>>,
79 last_layout: Option<gpui::ShapedLine>,
80 last_bounds: Option<Bounds<Pixels>>,
81 is_selecting: bool,
82
83 pub trigger_char: char,
84 pub mentions: Vec<Mention>,
85 pub dropdown_open: bool,
86 pub dropdown_filter: String,
87 pub dropdown_index: usize,
88 trigger_start: Option<usize>,
89 event_subscription: Option<Subscription>,
90}
91
92impl EventEmitter<MentionInputEvent> for MentionInputState {}
93
94impl MentionInputState {
95 pub fn new(cx: &mut Context<Self>) -> Self {
96 Self {
97 focus_handle: cx.focus_handle(),
98 content: String::new(),
99 placeholder: DEFAULT_PLACEHOLDER.into(),
100 disabled: false,
101 selected_range: 0..0,
102 selection_reversed: false,
103 marked_range: None,
104 last_layout: None,
105 last_bounds: None,
106 is_selecting: false,
107
108 trigger_char: '@',
109 mentions: Vec::new(),
110 dropdown_open: false,
111 dropdown_filter: String::new(),
112 dropdown_index: 0,
113 trigger_start: None,
114 event_subscription: None,
115 }
116 }
117
118 fn replace_event_subscription(&mut self, subscription: Option<Subscription>) {
119 self.event_subscription = subscription;
120 }
121
122 pub fn content(&self) -> &str {
123 &self.content
124 }
125
126 pub fn mentions(&self) -> &[Mention] {
127 &self.mentions
128 }
129
130 pub fn set_value(
131 &mut self,
132 value: impl Into<String>,
133 _window: &mut Window,
134 cx: &mut Context<Self>,
135 ) {
136 self.content = value.into();
137 self.mentions.clear();
138 self.selected_range = self.content.len()..self.content.len();
139 self.marked_range = None;
140 self.invalidate_layout_cache();
141 cx.emit(MentionInputEvent::Change);
142 cx.notify();
143 }
144
145 pub fn clear(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
146 self.content.clear();
147 self.mentions.clear();
148 self.selected_range = 0..0;
149 self.marked_range = None;
150 self.invalidate_layout_cache();
151 self.close_dropdown(cx);
152 cx.emit(MentionInputEvent::Change);
153 cx.notify();
154 }
155
156 fn open_dropdown(&mut self, start: usize, cx: &mut Context<Self>) {
157 self.dropdown_open = true;
158 self.trigger_start = Some(start);
159 self.dropdown_filter.clear();
160 self.dropdown_index = 0;
161 cx.notify();
162 }
163
164 fn close_dropdown(&mut self, cx: &mut Context<Self>) {
165 self.dropdown_open = false;
166 self.trigger_start = None;
167 self.dropdown_filter.clear();
168 self.dropdown_index = 0;
169 cx.notify();
170 }
171
172 fn insert_mention(&mut self, item: MentionItem, cx: &mut Context<Self>) {
173 let Some(trigger_start) = self.trigger_start else {
174 return;
175 };
176
177 let mention_text = format!("@{} ", item.name);
178 let end_pos = self.selected_range.end;
179
180 self.adjust_mentions_after_edit(
181 trigger_start,
182 end_pos.saturating_sub(trigger_start),
183 mention_text.len(),
184 );
185 self.marked_range = None;
186
187 let before = &self.content[..trigger_start];
188 let after = &self.content[end_pos..];
189 self.content = format!("{}{}{}", before, mention_text, after);
190
191 let mention_range = trigger_start..trigger_start + mention_text.len() - 1;
192 self.mentions.push(Mention {
193 item: item.clone(),
194 range: mention_range,
195 });
196
197 self.selected_range =
198 trigger_start + mention_text.len()..trigger_start + mention_text.len();
199 self.invalidate_layout_cache();
200 self.close_dropdown(cx);
201
202 cx.emit(MentionInputEvent::MentionSelected(item));
203 cx.emit(MentionInputEvent::Change);
204 cx.notify();
205 }
206
207 fn cursor_offset(&self) -> usize {
208 if self.selection_reversed {
209 self.selected_range.start
210 } else {
211 self.selected_range.end
212 }
213 }
214
215 fn move_to(&mut self, offset: usize, cx: &mut Context<Self>) {
216 self.selected_range = offset..offset;
217 cx.notify()
218 }
219
220 fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
221 if self.selection_reversed {
222 self.selected_range.start = offset
223 } else {
224 self.selected_range.end = offset
225 };
226 if self.selected_range.end < self.selected_range.start {
227 self.selection_reversed = !self.selection_reversed;
228 self.selected_range = self.selected_range.end..self.selected_range.start;
229 }
230 cx.notify()
231 }
232
233 fn previous_boundary(&self, offset: usize) -> usize {
234 text_util::previous_grapheme_boundary(&self.content, offset)
235 }
236
237 fn next_boundary(&self, offset: usize) -> usize {
238 text_util::next_grapheme_boundary(&self.content, offset)
239 }
240
241 fn offset_to_utf16(&self, offset: usize) -> usize {
242 crate::capabilities::controls::text_util::offset_to_utf16(&self.content, offset)
243 }
244
245 fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
246 crate::capabilities::controls::text_util::range_to_utf16(&self.content, range)
247 }
248
249 fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
250 crate::capabilities::controls::text_util::range_from_utf16(&self.content, range_utf16)
251 }
252
253 fn invalidate_layout_cache(&mut self) {
254 self.last_layout = None;
255 self.last_bounds = None;
256 }
257
258 fn layout_matches_content(&self, layout: &gpui::ShapedLine) -> bool {
259 layout.text.as_ref() == self.content.as_str()
260 }
261
262 fn index_for_mouse_position(&mut self, position: Point<Pixels>) -> usize {
263 if self.content.is_empty() {
264 return 0;
265 }
266 let (Some(bounds), Some(line)) = (self.last_bounds.as_ref(), self.last_layout.as_ref())
267 else {
268 return 0;
269 };
270 if !self.layout_matches_content(line) {
271 self.invalidate_layout_cache();
272 return self.cursor_offset();
273 }
274 if position.y < bounds.top() {
275 return 0;
276 }
277 if position.y > bounds.bottom() {
278 return self.content.len();
279 }
280 line.closest_index_for_x(position.x - bounds.left())
281 }
282
283 fn check_for_trigger(&mut self, cx: &mut Context<Self>) {
284 let cursor = self.cursor_offset();
285 if cursor == 0 {
286 if self.dropdown_open {
287 self.close_dropdown(cx);
288 }
289 return;
290 }
291
292 let trigger_char = self.trigger_char;
293 let content = self.content.clone();
294 let text_before = &content[..cursor];
295
296 if let Some(trigger_pos) = text_before.rfind(trigger_char) {
297 let between = text_before[trigger_pos + trigger_char.len_utf8()..].to_string();
298 let has_space = between.contains(' ');
299 let at_word_boundary = trigger_pos == 0
300 || text_before[..trigger_pos]
301 .chars()
302 .last()
303 .is_none_or(|c| c.is_whitespace());
304
305 if !has_space && at_word_boundary {
306 if !self.dropdown_open || self.trigger_start != Some(trigger_pos) {
307 self.open_dropdown(trigger_pos, cx);
308 }
309 self.dropdown_filter = between;
310 self.dropdown_index = 0;
311 cx.notify();
312 } else if self.dropdown_open {
313 self.close_dropdown(cx);
314 }
315 } else if self.dropdown_open {
316 self.close_dropdown(cx);
317 }
318 }
319
320 fn adjust_mentions_after_edit(&mut self, edit_start: usize, old_len: usize, new_len: usize) {
321 let diff = new_len as isize - old_len as isize;
322
323 self.mentions.retain(|mention| {
324 !(edit_start < mention.range.end && edit_start + old_len > mention.range.start)
325 });
326
327 for mention in &mut self.mentions {
328 if mention.range.start >= edit_start + old_len {
329 mention.range.start = (mention.range.start as isize + diff) as usize;
330 mention.range.end = (mention.range.end as isize + diff) as usize;
331 }
332 }
333 }
334
335 pub fn mention_up(&mut self, _: &MentionUp, _: &mut Window, cx: &mut Context<Self>) {
336 if self.dropdown_open && self.dropdown_index > 0 {
337 self.dropdown_index -= 1;
338 cx.notify();
339 }
340 }
341
342 pub fn mention_down(
343 &mut self,
344 _: &MentionDown,
345 filtered_count: usize,
346 _: &mut Window,
347 cx: &mut Context<Self>,
348 ) {
349 if self.dropdown_open && self.dropdown_index < filtered_count.saturating_sub(1) {
350 self.dropdown_index += 1;
351 cx.notify();
352 }
353 }
354
355 pub fn mention_confirm(
356 &mut self,
357 _: &MentionConfirm,
358 items: &[MentionItem],
359 _: &mut Window,
360 cx: &mut Context<Self>,
361 ) {
362 if self.dropdown_open {
363 let filter = self.dropdown_filter.to_lowercase();
364 let filtered: Vec<_> = items
365 .iter()
366 .filter(|item| item.name.to_lowercase().contains(&filter))
367 .collect();
368
369 if let Some(item) = filtered.get(self.dropdown_index) {
370 self.insert_mention((*item).clone(), cx);
371 }
372 }
373 }
374
375 pub fn mention_cancel(&mut self, _: &MentionCancel, _: &mut Window, cx: &mut Context<Self>) {
376 if self.dropdown_open {
377 self.close_dropdown(cx);
378 }
379 }
380
381 pub fn mention_backspace(
382 &mut self,
383 _: &MentionBackspace,
384 window: &mut Window,
385 cx: &mut Context<Self>,
386 ) {
387 if self.selected_range.is_empty() {
388 self.select_to(self.previous_boundary(self.cursor_offset()), cx)
389 }
390 self.replace_text_in_range(None, "", window, cx);
391 self.check_for_trigger(cx);
392 }
393
394 pub fn mention_delete(
395 &mut self,
396 _: &MentionDelete,
397 window: &mut Window,
398 cx: &mut Context<Self>,
399 ) {
400 if self.selected_range.is_empty() {
401 self.select_to(self.next_boundary(self.cursor_offset()), cx)
402 }
403 self.replace_text_in_range(None, "", window, cx);
404 self.check_for_trigger(cx);
405 }
406
407 pub fn mention_left(&mut self, _: &MentionLeft, _: &mut Window, cx: &mut Context<Self>) {
408 if self.dropdown_open {
409 return;
410 }
411 if self.selected_range.is_empty() {
412 self.move_to(self.previous_boundary(self.cursor_offset()), cx);
413 } else {
414 self.move_to(self.selected_range.start, cx)
415 }
416 }
417
418 pub fn mention_right(&mut self, _: &MentionRight, _: &mut Window, cx: &mut Context<Self>) {
419 if self.dropdown_open {
420 return;
421 }
422 if self.selected_range.is_empty() {
423 self.move_to(self.next_boundary(self.selected_range.end), cx);
424 } else {
425 self.move_to(self.selected_range.end, cx)
426 }
427 }
428
429 pub fn mention_home(&mut self, _: &MentionHome, _: &mut Window, cx: &mut Context<Self>) {
430 self.move_to(0, cx);
431 }
432
433 pub fn mention_end(&mut self, _: &MentionEnd, _: &mut Window, cx: &mut Context<Self>) {
434 self.move_to(self.content.len(), cx);
435 }
436
437 pub fn mention_select_all(
438 &mut self,
439 _: &MentionSelectAll,
440 _: &mut Window,
441 cx: &mut Context<Self>,
442 ) {
443 self.move_to(0, cx);
444 self.select_to(self.content.len(), cx)
445 }
446
447 pub fn mention_copy(&mut self, _: &MentionCopy, _: &mut Window, cx: &mut Context<Self>) {
448 if !self.selected_range.is_empty() {
449 cx.write_to_clipboard(ClipboardItem::new_string(
450 self.content[self.selected_range.clone()].to_string(),
451 ));
452 }
453 }
454
455 pub fn mention_cut(&mut self, _: &MentionCut, window: &mut Window, cx: &mut Context<Self>) {
456 if !self.selected_range.is_empty() {
457 cx.write_to_clipboard(ClipboardItem::new_string(
458 self.content[self.selected_range.clone()].to_string(),
459 ));
460 self.replace_text_in_range(None, "", window, cx);
461 self.check_for_trigger(cx);
462 }
463 }
464
465 pub fn mention_paste(&mut self, _: &MentionPaste, window: &mut Window, cx: &mut Context<Self>) {
466 if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) {
467 let text = text.replace("\n", " ");
468 self.replace_text_in_range(None, &text, window, cx);
469 self.check_for_trigger(cx);
470 }
471 }
472
473 pub fn mention_enter(&mut self, _: &MentionEnter, _: &mut Window, cx: &mut Context<Self>) {
474 if !self.dropdown_open {
475 cx.emit(MentionInputEvent::Enter);
476 }
477 }
478
479 fn on_mouse_down(
480 &mut self,
481 event: &MouseDownEvent,
482 _window: &mut Window,
483 cx: &mut Context<Self>,
484 ) {
485 self.is_selecting = true;
486 let click_index = self.index_for_mouse_position(event.position);
487 if event.modifiers.shift {
488 self.select_to(click_index, cx);
489 } else {
490 self.move_to(click_index, cx)
491 }
492 }
493
494 fn on_mouse_up(&mut self, _: &MouseUpEvent, _window: &mut Window, _cx: &mut Context<Self>) {
495 self.is_selecting = false;
496 }
497
498 fn on_mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {
499 if self.is_selecting {
500 let position = self.index_for_mouse_position(event.position);
501 self.select_to(position, cx);
502 }
503 }
504
505 pub fn focus_handle(&self, _: &App) -> FocusHandle {
506 self.focus_handle.clone()
507 }
508}
509
510impl EntityInputHandler for MentionInputState {
511 fn text_for_range(
512 &mut self,
513 range_utf16: Range<usize>,
514 actual_range: &mut Option<Range<usize>>,
515 _window: &mut Window,
516 _cx: &mut Context<Self>,
517 ) -> Option<String> {
518 let range = self.range_from_utf16(&range_utf16);
519 actual_range.replace(self.range_to_utf16(&range));
520 Some(self.content[range].to_string())
521 }
522
523 fn selected_text_range(
524 &mut self,
525 _ignore_disabled_input: bool,
526 _window: &mut Window,
527 _cx: &mut Context<Self>,
528 ) -> Option<UTF16Selection> {
529 Some(UTF16Selection {
530 range: self.range_to_utf16(&self.selected_range),
531 reversed: self.selection_reversed,
532 })
533 }
534
535 fn marked_text_range(
536 &self,
537 _window: &mut Window,
538 _cx: &mut Context<Self>,
539 ) -> Option<Range<usize>> {
540 self.marked_range
541 .as_ref()
542 .map(|range| self.range_to_utf16(range))
543 }
544
545 fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
546 self.marked_range = None;
547 self.invalidate_layout_cache();
548 }
549
550 fn replace_text_in_range(
551 &mut self,
552 range_utf16: Option<Range<usize>>,
553 new_text: &str,
554 _: &mut Window,
555 cx: &mut Context<Self>,
556 ) {
557 let range = range_utf16
558 .as_ref()
559 .map(|range_utf16| self.range_from_utf16(range_utf16))
560 .or(self.marked_range.clone())
561 .unwrap_or(self.selected_range.clone());
562
563 let old_len = range.end - range.start;
564 self.adjust_mentions_after_edit(range.start, old_len, new_text.len());
565
566 self.content = format!(
567 "{}{}{}",
568 &self.content[0..range.start],
569 new_text,
570 &self.content[range.end..]
571 );
572 self.selected_range = range.start + new_text.len()..range.start + new_text.len();
573 self.marked_range.take();
574
575 self.invalidate_layout_cache();
576 self.check_for_trigger(cx);
577 cx.emit(MentionInputEvent::Change);
578 cx.notify();
579 }
580
581 fn replace_and_mark_text_in_range(
582 &mut self,
583 range_utf16: Option<Range<usize>>,
584 new_text: &str,
585 new_selected_range_utf16: Option<Range<usize>>,
586 _window: &mut Window,
587 cx: &mut Context<Self>,
588 ) {
589 let range = range_utf16
590 .as_ref()
591 .map(|range_utf16| self.range_from_utf16(range_utf16))
592 .or(self.marked_range.clone())
593 .unwrap_or(self.selected_range.clone());
594
595 let old_len = range.end - range.start;
596 self.adjust_mentions_after_edit(range.start, old_len, new_text.len());
597
598 self.content = format!(
599 "{}{}{}",
600 &self.content[0..range.start],
601 new_text,
602 &self.content[range.end..]
603 );
604
605 if !new_text.is_empty() {
606 self.marked_range = Some(range.start..range.start + new_text.len());
607 } else {
608 self.marked_range = None;
609 }
610
611 self.selected_range = text_util::selection_after_replacement(
612 new_text,
613 new_selected_range_utf16.as_ref(),
614 range.start,
615 );
616
617 self.invalidate_layout_cache();
618 self.check_for_trigger(cx);
619 cx.notify();
620 }
621
622 fn bounds_for_range(
623 &mut self,
624 range_utf16: Range<usize>,
625 bounds: Bounds<Pixels>,
626 _window: &mut Window,
627 _cx: &mut Context<Self>,
628 ) -> Option<Bounds<Pixels>> {
629 if self.content.is_empty() {
630 return None;
631 }
632 let layout_matches = {
633 let last_layout = self.last_layout.as_ref()?;
634 self.layout_matches_content(last_layout)
635 };
636 if !layout_matches {
637 self.invalidate_layout_cache();
638 return None;
639 }
640
641 let last_layout = self.last_layout.as_ref()?;
642 let range = self.range_from_utf16(&range_utf16);
643 Some(Bounds::from_corners(
644 point(
645 bounds.left() + last_layout.x_for_index(range.start),
646 bounds.top(),
647 ),
648 point(
649 bounds.left() + last_layout.x_for_index(range.end),
650 bounds.bottom(),
651 ),
652 ))
653 }
654
655 fn character_index_for_point(
656 &mut self,
657 point: Point<Pixels>,
658 _window: &mut Window,
659 _cx: &mut Context<Self>,
660 ) -> Option<usize> {
661 if self.content.is_empty() {
662 return None;
663 }
664 let line_point = self.last_bounds?.localize(&point)?;
665 let layout_matches = {
666 let last_layout = self.last_layout.as_ref()?;
667 self.layout_matches_content(last_layout)
668 };
669 if !layout_matches {
670 self.invalidate_layout_cache();
671 return None;
672 }
673
674 let last_layout = self.last_layout.as_ref()?;
675 let utf8_index = last_layout.index_for_x(point.x - line_point.x)?;
676 Some(self.offset_to_utf16(utf8_index))
677 }
678}
679
680impl Focusable for MentionInputState {
681 fn focus_handle(&self, _: &App) -> FocusHandle {
682 self.focus_handle.clone()
683 }
684}
685
686impl Render for MentionInputState {
687 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
688 div()
689 }
690}
691
692#[derive(IntoElement)]
693pub struct MentionInput {
694 state: Entity<MentionInputState>,
695 items: Vec<MentionItem>,
696 placeholder: SharedString,
697 disabled: bool,
698 trigger_char: char,
699 max_dropdown_height: Pixels,
700
701 on_change: Option<Rc<dyn Fn(&str, &mut App)>>,
702 on_mention: Option<Rc<dyn Fn(&MentionItem, &mut App)>>,
703 on_enter: Option<Rc<dyn Fn(&str, &mut App)>>,
704
705 style: StyleRefinement,
706}
707
708const DEFAULT_PLACEHOLDER: &str = "Type @ to mention someone...";
709
710impl MentionInput {
711 pub fn new(state: &Entity<MentionInputState>, items: Vec<MentionItem>) -> Self {
712 Self {
713 state: state.clone(),
714 items,
715 placeholder: DEFAULT_PLACEHOLDER.into(),
716 disabled: false,
717 trigger_char: '@',
718 max_dropdown_height: px(200.0),
719 on_change: None,
720 on_mention: None,
721 on_enter: None,
722 style: StyleRefinement::default(),
723 }
724 }
725
726 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
727 self.placeholder = placeholder.into();
728 self
729 }
730
731 pub fn disabled(mut self, disabled: bool) -> Self {
732 self.disabled = disabled;
733 self
734 }
735
736 pub fn trigger_char(mut self, trigger: char) -> Self {
737 self.trigger_char = trigger;
738 self
739 }
740
741 pub fn max_dropdown_height(mut self, height: impl Into<Pixels>) -> Self {
742 self.max_dropdown_height = height.into();
743 self
744 }
745
746 pub fn on_change<F>(mut self, callback: F) -> Self
747 where
748 F: Fn(&str, &mut App) + 'static,
749 {
750 self.on_change = Some(Rc::new(callback));
751 self
752 }
753
754 pub fn on_mention<F>(mut self, callback: F) -> Self
755 where
756 F: Fn(&MentionItem, &mut App) + 'static,
757 {
758 self.on_mention = Some(Rc::new(callback));
759 self
760 }
761
762 pub fn on_enter<F>(mut self, callback: F) -> Self
763 where
764 F: Fn(&str, &mut App) + 'static,
765 {
766 self.on_enter = Some(Rc::new(callback));
767 self
768 }
769
770 fn install_event_subscription(&self, cx: &mut App) {
771 let on_change = self.on_change.clone();
772 let on_mention = self.on_mention.clone();
773 let on_enter = self.on_enter.clone();
774 let has_callbacks = on_change.is_some() || on_mention.is_some() || on_enter.is_some();
775
776 let subscription = has_callbacks.then(|| {
777 cx.subscribe(
778 &self.state,
779 move |emitter, event: &MentionInputEvent, cx| match event {
780 MentionInputEvent::Change => {
781 if let Some(callback) = on_change.as_ref() {
782 let content = emitter.read(cx).content.clone();
783 callback(&content, cx);
784 }
785 }
786 MentionInputEvent::MentionSelected(item) => {
787 if let Some(callback) = on_mention.as_ref() {
788 callback(item, cx);
789 }
790 }
791 MentionInputEvent::Enter => {
792 if let Some(callback) = on_enter.as_ref() {
793 let content = emitter.read(cx).content.clone();
794 callback(&content, cx);
795 }
796 }
797 MentionInputEvent::Focus | MentionInputEvent::Blur => {}
798 },
799 )
800 });
801
802 self.state.update(cx, |state, _| {
803 state.replace_event_subscription(subscription);
804 });
805 }
806
807 fn filtered_items(&self, filter: &str) -> Vec<&MentionItem> {
808 let filter_lower = filter.to_lowercase();
809 self.items
810 .iter()
811 .filter(|item| item.name.to_lowercase().contains(&filter_lower))
812 .collect()
813 }
814}
815
816impl Styled for MentionInput {
817 fn style(&mut self) -> &mut StyleRefinement {
818 &mut self.style
819 }
820}
821
822impl RenderOnce for MentionInput {
823 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
824 let theme = use_theme(cx);
825
826 let state_entity = self.state.clone();
827 let state = self.state.read(cx);
828 let is_focused = state.focus_handle(cx).is_focused(window);
829 let dropdown_open = state.dropdown_open;
830 let dropdown_filter = state.dropdown_filter.clone();
831 let dropdown_index = state.dropdown_index;
832 let mentions = state.mentions.clone();
833 let placeholder = self.placeholder.clone();
834 let focus_handle = state.focus_handle(cx);
835
836 self.state.update(cx, |s, _| {
837 s.trigger_char = self.trigger_char;
838 if s.placeholder != self.placeholder {
839 s.placeholder = self.placeholder.clone();
840 if s.content.is_empty() {
841 s.invalidate_layout_cache();
842 }
843 }
844 s.disabled = self.disabled;
845 });
846
847 let user_style = self.style.clone();
848 let filtered = self.filtered_items(&dropdown_filter);
849 let filtered_count = filtered.len();
850
851 let items_for_confirm = self.items.clone();
852
853 self.install_event_subscription(cx);
854
855 let text_element = MentionTextElement {
856 input: self.state.clone(),
857 mentions: mentions.clone(),
858 placeholder: placeholder.clone(),
859 };
860
861 div()
862 .relative()
863 .w_full()
864 .key_context("MentionInput")
865 .track_focus(&focus_handle)
866 .when(!self.disabled, |this| {
867 this.on_action({
868 let state = state_entity.clone();
869 move |action: &MentionBackspace, window, cx| {
870 state.update(cx, |s, cx| s.mention_backspace(action, window, cx));
871 }
872 })
873 .on_action({
874 let state = state_entity.clone();
875 move |action: &MentionDelete, window, cx| {
876 state.update(cx, |s, cx| s.mention_delete(action, window, cx));
877 }
878 })
879 .on_action({
880 let state = state_entity.clone();
881 move |action: &MentionLeft, window, cx| {
882 state.update(cx, |s, cx| s.mention_left(action, window, cx));
883 }
884 })
885 .on_action({
886 let state = state_entity.clone();
887 move |action: &MentionRight, window, cx| {
888 state.update(cx, |s, cx| s.mention_right(action, window, cx));
889 }
890 })
891 .on_action({
892 let state = state_entity.clone();
893 move |action: &MentionHome, window, cx| {
894 state.update(cx, |s, cx| s.mention_home(action, window, cx));
895 }
896 })
897 .on_action({
898 let state = state_entity.clone();
899 move |action: &MentionEnd, window, cx| {
900 state.update(cx, |s, cx| s.mention_end(action, window, cx));
901 }
902 })
903 .on_action({
904 let state = state_entity.clone();
905 move |action: &MentionSelectAll, window, cx| {
906 state.update(cx, |s, cx| s.mention_select_all(action, window, cx));
907 }
908 })
909 .on_action({
910 let state = state_entity.clone();
911 move |action: &MentionCopy, window, cx| {
912 state.update(cx, |s, cx| s.mention_copy(action, window, cx));
913 }
914 })
915 .on_action({
916 let state = state_entity.clone();
917 move |action: &MentionCut, window, cx| {
918 state.update(cx, |s, cx| s.mention_cut(action, window, cx));
919 }
920 })
921 .on_action({
922 let state = state_entity.clone();
923 move |action: &MentionPaste, window, cx| {
924 state.update(cx, |s, cx| s.mention_paste(action, window, cx));
925 }
926 })
927 .on_action({
928 let state = state_entity.clone();
929 move |action: &MentionUp, window, cx| {
930 state.update(cx, |s, cx| s.mention_up(action, window, cx));
931 }
932 })
933 .on_action({
934 let state = state_entity.clone();
935 let count = filtered_count;
936 move |action: &MentionDown, window, cx| {
937 state.update(cx, |s, cx| s.mention_down(action, count, window, cx));
938 }
939 })
940 .on_action({
941 let state = state_entity.clone();
942 let items = items_for_confirm.clone();
943 move |action: &MentionConfirm, window, cx| {
944 state.update(cx, |s, cx| s.mention_confirm(action, &items, window, cx));
945 }
946 })
947 .on_action({
948 let state = state_entity.clone();
949 move |action: &MentionCancel, window, cx| {
950 state.update(cx, |s, cx| s.mention_cancel(action, window, cx));
951 }
952 })
953 .on_action({
954 let state = state_entity.clone();
955 move |action: &MentionEnter, window, cx| {
956 state.update(cx, |s, cx| s.mention_enter(action, window, cx));
957 }
958 })
959 })
960 .child(
961 div()
962 .id("mention-input-container")
963 .flex()
964 .items_center()
965 .h(px(40.0))
966 .px(px(12.0))
967 .bg(theme.tokens.background)
968 .border_1()
969 .border_color(if is_focused {
970 theme.tokens.ring
971 } else {
972 theme.tokens.input
973 })
974 .rounded(theme.tokens.radius_md)
975 .shadow(smallvec::smallvec![theme.tokens.shadow_xs.clone()])
976 .when(!self.disabled, |this| {
977 this.hover(|style| style.border_color(theme.tokens.ring))
978 })
979 .when(self.disabled, |this| this.opacity(0.5))
980 .on_mouse_down(MouseButton::Left, {
981 let state = state_entity.clone();
982 move |event, window, cx| {
983 state.update(cx, |s, cx| s.on_mouse_down(event, window, cx));
984 }
985 })
986 .on_mouse_up(MouseButton::Left, {
987 let state = state_entity.clone();
988 move |event, window, cx| {
989 state.update(cx, |s, cx| s.on_mouse_up(event, window, cx));
990 }
991 })
992 .on_mouse_move({
993 let state = state_entity.clone();
994 move |event, window, cx| {
995 state.update(cx, |s, cx| s.on_mouse_move(event, window, cx));
996 }
997 })
998 .child(
999 div()
1000 .flex_1()
1001 .overflow_hidden()
1002 .text_size(px(14.0))
1003 .font_family(theme.tokens.font_family.clone())
1004 .text_color(theme.tokens.foreground)
1005 .child(text_element),
1006 ),
1007 )
1008 .when(dropdown_open && !filtered.is_empty(), |this| {
1009 let state_for_select = state_entity.clone();
1010
1011 this.child(
1012 deferred(
1013 anchored()
1014 .snap_to_window_with_margin(Edges::all(DROPDOWN_MARGIN))
1015 .child(
1016 div().occlude().w(px(300.0)).child(
1017 div()
1018 .occlude()
1019 .mt(DROPDOWN_MARGIN)
1020 .bg(theme.tokens.popover)
1021 .border_1()
1022 .border_color(theme.tokens.border)
1023 .rounded(theme.tokens.radius_md)
1024 .shadow_lg()
1025 .overflow_hidden()
1026 .child(div().max_h(self.max_dropdown_height).child(
1027 scrollable_vertical(div().py(px(4.0)).children(
1028 filtered.into_iter().enumerate().map(
1029 |(idx, item)| {
1030 let is_selected = idx == dropdown_index;
1031 let item_clone = item.clone();
1032 let state = state_for_select.clone();
1033
1034 div()
1035 .id(SharedString::from(format!(
1036 "mention-item-{}",
1037 idx
1038 )))
1039 .flex()
1040 .items_center()
1041 .gap(px(8.0))
1042 .px(px(12.0))
1043 .py(px(8.0))
1044 .cursor_pointer()
1045 .bg(if is_selected {
1046 theme.tokens.accent
1047 } else {
1048 gpui::transparent_black()
1049 })
1050 .hover(|style| {
1051 style.bg(theme.tokens.accent)
1052 })
1053 .on_mouse_down(
1054 MouseButton::Left,
1055 move |_, _, cx| {
1056 state.update(cx, |s, cx| {
1057 s.insert_mention(
1058 item_clone.clone(),
1059 cx,
1060 );
1061 });
1062 },
1063 )
1064 .child(
1065 if let Some(ref avatar_url) =
1066 item.avatar_url
1067 {
1068 Avatar::new()
1069 .src(avatar_url.clone())
1070 .size(AvatarSize::Sm)
1071 .into_any_element()
1072 } else {
1073 Avatar::new()
1074 .name(item.name.clone())
1075 .size(AvatarSize::Sm)
1076 .into_any_element()
1077 },
1078 )
1079 .child(
1080 div()
1081 .text_size(px(14.0))
1082 .font_family(
1083 theme
1084 .tokens
1085 .font_family
1086 .clone(),
1087 )
1088 .text_color(
1089 theme
1090 .tokens
1091 .popover_foreground,
1092 )
1093 .child(item.name.clone()),
1094 )
1095 },
1096 ),
1097 )),
1098 )),
1099 ),
1100 ),
1101 )
1102 .with_priority(1),
1103 )
1104 })
1105 .map(|this| {
1106 let mut div = this;
1107 div.style().refine(&user_style);
1108 div
1109 })
1110 }
1111}
1112
1113struct MentionTextElement {
1114 input: Entity<MentionInputState>,
1115 mentions: Vec<Mention>,
1116 placeholder: SharedString,
1117}
1118
1119struct MentionPrepaintState {
1120 line: Option<gpui::ShapedLine>,
1121 cursor: Option<PaintQuad>,
1122 selection: Option<PaintQuad>,
1123}
1124
1125impl IntoElement for MentionTextElement {
1126 type Element = Self;
1127
1128 fn into_element(self) -> Self::Element {
1129 self
1130 }
1131}
1132
1133impl gpui::Element for MentionTextElement {
1134 type RequestLayoutState = ();
1135 type PrepaintState = MentionPrepaintState;
1136
1137 fn id(&self) -> Option<ElementId> {
1138 None
1139 }
1140
1141 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
1142 None
1143 }
1144
1145 fn request_layout(
1146 &mut self,
1147 _id: Option<&GlobalElementId>,
1148 _inspector_id: Option<&gpui::InspectorElementId>,
1149 window: &mut Window,
1150 cx: &mut App,
1151 ) -> (LayoutId, Self::RequestLayoutState) {
1152 let mut style = Style::default();
1153 style.size.width = relative(1.).into();
1154 style.size.height = window.line_height().into();
1155 (window.request_layout(style, [], cx), ())
1156 }
1157
1158 fn prepaint(
1159 &mut self,
1160 _id: Option<&GlobalElementId>,
1161 _inspector_id: Option<&gpui::InspectorElementId>,
1162 bounds: Bounds<Pixels>,
1163 _request_layout: &mut Self::RequestLayoutState,
1164 window: &mut Window,
1165 cx: &mut App,
1166 ) -> Self::PrepaintState {
1167 let input = self.input.read(cx);
1168 let content: SharedString = input.content.clone().into();
1169 let selected_range = input.selected_range.clone();
1170 let cursor_offset = input.cursor_offset();
1171 let theme = use_theme(cx);
1172 let style = window.text_style();
1173
1174 let (display_text, text_color) = if content.is_empty() {
1175 (self.placeholder.clone(), theme.tokens.muted_foreground)
1176 } else {
1177 (content.clone(), style.color)
1178 };
1179
1180 let font_size = style.font_size.to_pixels(window.rem_size());
1181
1182 let mut runs = Vec::new();
1183 if !content.is_empty() {
1184 let mut last_end = 0;
1185 let mut sorted_mentions = self.mentions.clone();
1186 sorted_mentions.sort_by_key(|m| m.range.start);
1187
1188 for mention in &sorted_mentions {
1189 if mention.range.start > last_end {
1190 runs.push(TextRun {
1191 len: mention.range.start - last_end,
1192 font: style.font(),
1193 color: text_color,
1194 background_color: None,
1195 underline: None,
1196 strikethrough: None,
1197 });
1198 }
1199
1200 let mention_len = mention.range.end.min(content.len()) - mention.range.start;
1201 if mention_len > 0 {
1202 runs.push(TextRun {
1203 len: mention_len,
1204 font: style.font(),
1205 color: theme.tokens.primary,
1206 background_color: Some(theme.tokens.primary.opacity(0.1)),
1207 underline: None,
1208 strikethrough: None,
1209 });
1210 }
1211 last_end = mention.range.end.min(content.len());
1212 }
1213
1214 if last_end < content.len() {
1215 runs.push(TextRun {
1216 len: content.len() - last_end,
1217 font: style.font(),
1218 color: text_color,
1219 background_color: None,
1220 underline: None,
1221 strikethrough: None,
1222 });
1223 }
1224 }
1225
1226 if runs.is_empty() {
1227 runs.push(TextRun {
1228 len: display_text.len(),
1229 font: style.font(),
1230 color: text_color,
1231 background_color: None,
1232 underline: None,
1233 strikethrough: None,
1234 });
1235 }
1236
1237 let line = window
1238 .text_system()
1239 .shape_line(display_text, font_size, &runs, None);
1240
1241 let cursor_pos = line.x_for_index(cursor_offset);
1242 let (selection, cursor) = if selected_range.is_empty() {
1243 (
1244 None,
1245 Some(fill(
1246 Bounds::new(
1247 point(bounds.left() + cursor_pos, bounds.top()),
1248 size(edit::CARET_WIDTH, bounds.bottom() - bounds.top()),
1249 ),
1250 theme.tokens.primary,
1251 )),
1252 )
1253 } else {
1254 (
1255 Some(fill(
1256 Bounds::from_corners(
1257 point(
1258 bounds.left() + line.x_for_index(selected_range.start),
1259 bounds.top(),
1260 ),
1261 point(
1262 bounds.left() + line.x_for_index(selected_range.end),
1263 bounds.bottom(),
1264 ),
1265 ),
1266 theme
1267 .tokens
1268 .primary
1269 .opacity(edit::SELECTION_HIGHLIGHT_OPACITY),
1270 )),
1271 None,
1272 )
1273 };
1274
1275 MentionPrepaintState {
1276 line: Some(line),
1277 cursor,
1278 selection,
1279 }
1280 }
1281
1282 fn paint(
1283 &mut self,
1284 _id: Option<&GlobalElementId>,
1285 _inspector_id: Option<&gpui::InspectorElementId>,
1286 bounds: Bounds<Pixels>,
1287 _request_layout: &mut Self::RequestLayoutState,
1288 prepaint: &mut Self::PrepaintState,
1289 window: &mut Window,
1290 cx: &mut App,
1291 ) {
1292 let focus_handle = self.input.read(cx).focus_handle.clone();
1293 let disabled = self.input.read(cx).disabled;
1294
1295 if !disabled {
1296 window.handle_input(
1297 &focus_handle,
1298 ElementInputHandler::new(bounds, self.input.clone()),
1299 cx,
1300 );
1301 }
1302
1303 if let Some(selection) = prepaint.selection.take() {
1304 window.paint_quad(selection)
1305 }
1306
1307 let Some(line) = prepaint.line.take() else {
1308 return;
1309 };
1310
1311 if line
1312 .paint(bounds.origin, window.line_height(), window, cx)
1313 .is_err()
1314 {
1315 return;
1316 }
1317
1318 if focus_handle.is_focused(window) {
1319 if let Some(cursor) = prepaint.cursor.take() {
1320 window.paint_quad(cursor);
1321 }
1322 }
1323
1324 self.input.update(cx, |input, _cx| {
1325 input.last_layout = Some(line);
1326 input.last_bounds = Some(bounds);
1327 });
1328 }
1329}
1330
1331pub fn init_mention_input(cx: &mut App) {
1332 if !crate::capabilities::foundation::initialization::begin(cx, "mention-input") {
1333 return;
1334 }
1335 cx.bind_keys([
1336 KeyBinding::new("backspace", MentionBackspace, Some("MentionInput")),
1337 KeyBinding::new("delete", MentionDelete, Some("MentionInput")),
1338 KeyBinding::new("left", MentionLeft, Some("MentionInput")),
1339 KeyBinding::new("right", MentionRight, Some("MentionInput")),
1340 KeyBinding::new("home", MentionHome, Some("MentionInput")),
1341 KeyBinding::new("end", MentionEnd, Some("MentionInput")),
1342 KeyBinding::new("up", MentionUp, Some("MentionInput")),
1343 KeyBinding::new("down", MentionDown, Some("MentionInput")),
1344 KeyBinding::new("enter", MentionConfirm, Some("MentionInput")),
1345 KeyBinding::new("escape", MentionCancel, Some("MentionInput")),
1346 #[cfg(target_os = "macos")]
1347 KeyBinding::new("cmd-a", MentionSelectAll, Some("MentionInput")),
1348 #[cfg(not(target_os = "macos"))]
1349 KeyBinding::new("ctrl-a", MentionSelectAll, Some("MentionInput")),
1350 #[cfg(target_os = "macos")]
1351 KeyBinding::new("cmd-c", MentionCopy, Some("MentionInput")),
1352 #[cfg(not(target_os = "macos"))]
1353 KeyBinding::new("ctrl-c", MentionCopy, Some("MentionInput")),
1354 #[cfg(target_os = "macos")]
1355 KeyBinding::new("cmd-x", MentionCut, Some("MentionInput")),
1356 #[cfg(not(target_os = "macos"))]
1357 KeyBinding::new("ctrl-x", MentionCut, Some("MentionInput")),
1358 #[cfg(target_os = "macos")]
1359 KeyBinding::new("cmd-v", MentionPaste, Some("MentionInput")),
1360 #[cfg(not(target_os = "macos"))]
1361 KeyBinding::new("ctrl-v", MentionPaste, Some("MentionInput")),
1362 ]);
1363}
1364
1365#[cfg(test)]
1366mod tests {
1367 use super::*;
1368 use crate::capabilities::foundation::theme::{install_theme, Theme};
1369 use std::{cell::Cell, rc::Rc};
1370
1371 struct MentionRenderTestView {
1372 state: Entity<MentionInputState>,
1373 callback_calls: Option<Rc<Cell<usize>>>,
1374 }
1375
1376 impl Render for MentionRenderTestView {
1377 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
1378 MentionInput::new(&self.state, Vec::new())
1379 .when_some(self.callback_calls.clone(), |input, calls| {
1380 input.on_change(move |_, _| calls.set(calls.get() + 1))
1381 })
1382 }
1383 }
1384
1385 #[gpui::test]
1386 fn repeated_render_replaces_mention_event_subscription() {
1387 let mut app = TestApp::new();
1388 app.update(|cx| install_theme(cx, Theme::light()));
1389 let stale_calls = Rc::new(Cell::new(0));
1390 let current_calls = Rc::new(Cell::new(0));
1391 let mut window = app.open_window(|_, cx| MentionRenderTestView {
1392 state: cx.new(MentionInputState::new),
1393 callback_calls: Some(stale_calls.clone()),
1394 });
1395
1396 window.draw();
1397 window.update(|view, _, cx| {
1398 view.callback_calls = Some(current_calls.clone());
1399 cx.notify();
1400 });
1401 window.draw();
1402 window.update(|view, _, cx| {
1403 view.state
1404 .update(cx, |_, cx| cx.emit(MentionInputEvent::Change));
1405 });
1406 assert_eq!(stale_calls.get(), 0);
1407 assert_eq!(current_calls.get(), 1);
1408
1409 window.update(|view, _, cx| {
1410 view.callback_calls = None;
1411 cx.notify();
1412 });
1413 window.draw();
1414 window.update(|view, _, cx| {
1415 view.state
1416 .update(cx, |_, cx| cx.emit(MentionInputEvent::Change));
1417 });
1418 assert_eq!(current_calls.get(), 1);
1419 }
1420}