Skip to main content

arc_ui/inputs/
mention_input.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/mention-input/mention-input.tsx` & `.module.css`
3//!
4//! P4 Component #23: `mention-input`
5//!
6//! - A textarea with `@` people and `#` channel mentions:
7//!   - Typing `@` or `#` (after whitespace/openers) opens a ranked suggestion list
8//!     (prefix > word-start > substring > meta, `max_suggestions` capped); ArrowUp/Down walk
9//!     it, Enter/Tab choose, Escape dismisses (a continuing sentence reopens it).
10//!   - Choosing a suggestion replaces the trigger query with `@Name ` (or `#Name `) and records
11//!     a structured mention with character offsets. `reconcile` moves mentions along with edits
12//!     and drops any the edit touched.
13//!   - `submit_on_enter`: Enter submits and Shift+Enter adds a line.
14//!   - The suggestion popover opens below (or above) on `spring.smooth`/`spring.snappy`
15//!     presence, `fast` opacity, with the matched part of a label in full contrast.
16//!
17//! Known deviations from upstream:
18//! - The text edits through the shared `Input` (real caret) instead of a native textarea; the
19//!   "caret never rests inside a token" selection surgery is approximated (tokens are still
20//!   atomic for reconciliation), there is no `aria-live` region, and the imperative handle is
21//!   exposed as plain methods on the component instead of a forwarded ref.
22
23use std::rc::Rc;
24
25use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
26use gpui_kit::{
27    AnyElement, App, ElementId, Entity, FocusHandle, Focusable as _, Hsla, IntoElement,
28    KeyDownEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Styled,
29    TestSupportExt as _, Window,
30    base::StyledExt as _,
31    component::input::{Input as KitInput, InputState},
32    deferred, div,
33    prelude::*,
34    px,
35};
36
37use super::field_message::render_field_message;
38
39const MENTION_POPOVER_WIDTH: f32 = 272.0;
40
41/// `@` for people, `#` for channels.
42pub fn mention_text(kind: MentionKind, label: &str) -> String {
43    format!("{}{label}", kind.symbol())
44}
45
46/// One mention inside the text: `start..end` are character offsets spanning `@label`/`#label`.
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub struct Mention {
49    pub kind: MentionKind,
50    pub id: SharedString,
51    pub label: SharedString,
52    pub start: usize,
53    pub end: usize,
54}
55
56/// The mention kind.
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub enum MentionKind {
59    Person,
60    Channel,
61}
62
63impl MentionKind {
64    pub fn symbol(self) -> &'static str {
65        match self {
66            Self::Person => "@",
67            Self::Channel => "#",
68        }
69    }
70}
71
72/// The field value: plain text plus the structured mention list.
73#[derive(Clone, Debug, Default, PartialEq)]
74pub struct MentionValue {
75    pub text: String,
76    pub mentions: Vec<Mention>,
77}
78
79/// A person candidate for `@`.
80#[derive(Clone, Debug, PartialEq)]
81pub struct MentionPerson {
82    pub id: SharedString,
83    pub name: SharedString,
84    /// One short line under the name, such as a job title.
85    pub role: Option<SharedString>,
86}
87
88impl MentionPerson {
89    pub fn new(id: impl Into<SharedString>, name: impl Into<SharedString>) -> Self {
90        Self {
91            id: id.into(),
92            name: name.into(),
93            role: None,
94        }
95    }
96
97    pub fn role(mut self, role: impl Into<SharedString>) -> Self {
98        self.role = Some(role.into());
99        self
100    }
101}
102
103/// A channel candidate for `#`.
104#[derive(Clone, Debug, PartialEq)]
105pub struct MentionChannel {
106    pub id: SharedString,
107    pub name: SharedString,
108    pub description: Option<SharedString>,
109}
110
111impl MentionChannel {
112    pub fn new(id: impl Into<SharedString>, name: impl Into<SharedString>) -> Self {
113        Self {
114            id: id.into(),
115            name: name.into(),
116            description: None,
117        }
118    }
119
120    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
121        self.description = Some(description.into());
122        self
123    }
124}
125
126/// A suggestion (person or channel).
127#[derive(Clone, Debug, PartialEq)]
128pub enum MentionSuggestion {
129    Person(MentionPerson),
130    Channel(MentionChannel),
131}
132
133impl MentionSuggestion {
134    fn id(&self) -> &SharedString {
135        match self {
136            Self::Person(p) => &p.id,
137            Self::Channel(c) => &c.id,
138        }
139    }
140
141    fn label(&self) -> &SharedString {
142        match self {
143            Self::Person(p) => &p.name,
144            Self::Channel(c) => &c.name,
145        }
146    }
147
148    fn meta(&self) -> Option<&SharedString> {
149        match self {
150            Self::Person(p) => p.role.as_ref(),
151            Self::Channel(c) => c.description.as_ref(),
152        }
153    }
154
155    fn kind(&self) -> MentionKind {
156        match self {
157            Self::Person(_) => MentionKind::Person,
158            Self::Channel(_) => MentionKind::Channel,
159        }
160    }
161}
162
163/// The active trigger: `@`/`#` at `start`, with the query typed after it.
164#[derive(Clone, Debug, PartialEq)]
165pub struct MentionTrigger {
166    pub kind: MentionKind,
167    pub start: usize,
168    pub query: String,
169}
170
171/// Finds the trigger before the caret (upstream `findTrigger`).
172pub fn mention_find_trigger(
173    text: &str,
174    caret: usize,
175    mentions: &[Mention],
176    person_enabled: bool,
177    channel_enabled: bool,
178) -> Option<MentionTrigger> {
179    let chars: Vec<char> = text.chars().collect();
180    let caret = caret.min(chars.len());
181    for index in (0..caret).rev() {
182        if caret - index > 48 {
183            break;
184        }
185        let ch = chars[index];
186        if ch == '\n' {
187            return None;
188        }
189        if ch != '@' && ch != '#' {
190            continue;
191        }
192        let kind = if ch == '@' {
193            MentionKind::Person
194        } else {
195            MentionKind::Channel
196        };
197        if (kind == MentionKind::Person && !person_enabled)
198            || (kind == MentionKind::Channel && !channel_enabled)
199        {
200            return None;
201        }
202        if index > 0 {
203            let prev = chars[index - 1];
204            if !(prev.is_whitespace() || matches!(prev, '(' | '[' | '{' | '"' | '\'')) {
205                return None;
206            }
207        }
208        if mentions.iter().any(|m| index >= m.start && index < m.end) {
209            return None;
210        }
211        let query: String = chars[index + 1..caret].iter().collect();
212        let shape_ok = if kind == MentionKind::Person {
213            // `[^\s@#]*( [^\s@#]*)?`
214            let parts: Vec<&str> = query.split(' ').collect();
215            parts.len() <= 2
216                && parts.iter().all(|p| {
217                    !p.contains(['@', '#']) && !p.chars().any(|c| c.is_whitespace()) || p.is_empty()
218                })
219        } else {
220            !query.contains(['@', '#']) && !query.chars().any(|c| c.is_whitespace())
221        };
222        if shape_ok {
223            return Some(MentionTrigger {
224                kind,
225                start: index,
226                query,
227            });
228        }
229        return None;
230    }
231    None
232}
233
234/// Ranks a label against the query: prefix > word-start > substring > meta.
235pub fn mention_rank(label: &str, extra: &str, query: &str) -> usize {
236    let name = label.to_lowercase();
237    if query.is_empty() {
238        return 1;
239    }
240    if name.starts_with(query) {
241        return 4;
242    }
243    if name
244        .split([' ', '-', '_', '.'])
245        .any(|word| word.starts_with(query))
246    {
247        return 3;
248    }
249    if name.contains(query) {
250        return 2;
251    }
252    if extra.to_lowercase().contains(query) {
253        return 1;
254    }
255    0
256}
257
258/// Moves mentions along with an edit and drops any the edit touched (upstream `reconcile`).
259pub fn mention_reconcile(
260    previous: &[Mention],
261    old_text: &str,
262    text: &str,
263    hint: usize,
264) -> Vec<Mention> {
265    let a: Vec<char> = old_text.chars().collect();
266    let b: Vec<char> = text.chars().collect();
267    let mut prefix = 0usize;
268    let max_prefix = a.len().min(b.len()).min(hint);
269    while prefix < max_prefix && a[prefix] == b[prefix] {
270        prefix += 1;
271    }
272    let mut suffix = 0usize;
273    while suffix < a.len() - prefix
274        && suffix < b.len() - prefix
275        && a[a.len() - 1 - suffix] == b[b.len() - 1 - suffix]
276    {
277        suffix += 1;
278    }
279    let old_end = a.len() - suffix;
280    let delta = b.len() as i64 - a.len() as i64;
281    let out: Vec<Mention> = previous
282        .iter()
283        .filter_map(|mention| {
284            if mention.end <= prefix {
285                return Some(mention.clone());
286            }
287            if mention.start >= old_end {
288                let start = (mention.start as i64 + delta) as usize;
289                let end = (mention.end as i64 + delta) as usize;
290                return Some(Mention {
291                    start,
292                    end,
293                    ..mention.clone()
294                });
295            }
296            None
297        })
298        .filter(|mention| {
299            let chars: Vec<char> = text.chars().collect();
300            if mention.end > chars.len() || mention.start > mention.end {
301                return false;
302            }
303            let slice: String = chars[mention.start..mention.end].iter().collect();
304            slice == mention_text(mention.kind, &mention.label)
305        })
306        .collect();
307    out
308}
309
310type MentionChangeHandler = Rc<dyn Fn(&MentionValue, &mut Window, &mut App)>;
311type MentionAddHandler = Rc<dyn Fn(&Mention, &mut Window, &mut App)>;
312type MentionSubmitHandler = Rc<dyn Fn(&MentionValue, &mut Window, &mut App)>;
313
314#[derive(Clone)]
315struct MentionInputInternal {
316    value: MentionValue,
317    last_caret: usize,
318    dismissed_start: Option<usize>,
319    active_index: usize,
320    last_query_key: String,
321    query_input: Entity<InputState>,
322    focus_handle: FocusHandle,
323}
324
325impl MentionInputInternal {
326    fn new(window: &mut Window, cx: &mut App) -> Self {
327        let query_input = cx.new(|cx| InputState::new(window, cx));
328        Self {
329            value: MentionValue::default(),
330            last_caret: 0,
331            dismissed_start: None,
332            active_index: 0,
333            last_query_key: String::new(),
334            query_input,
335            focus_handle: cx.focus_handle(),
336        }
337    }
338}
339
340/// Arc `MentionInput` — a field with `@` people and `#` channel mentions.
341#[derive(IntoElement)]
342pub struct MentionInput {
343    id: ElementId,
344    label: SharedString,
345    value: Option<MentionValue>,
346    default_value: MentionValue,
347    people: Vec<MentionPerson>,
348    channels: Vec<MentionChannel>,
349    submit_on_enter: bool,
350    placeholder: Option<SharedString>,
351    max_suggestions: usize,
352    disabled: bool,
353    width: Option<Pixels>,
354    on_change: Option<MentionChangeHandler>,
355    on_mention_add: Option<MentionAddHandler>,
356    on_submit: Option<MentionSubmitHandler>,
357}
358
359impl MentionInput {
360    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
361        Self {
362            id: id.into(),
363            label: label.into(),
364            value: None,
365            default_value: MentionValue::default(),
366            people: Vec::new(),
367            channels: Vec::new(),
368            submit_on_enter: false,
369            placeholder: None,
370            max_suggestions: 6,
371            disabled: false,
372            width: None,
373            on_change: None,
374            on_mention_add: None,
375            on_submit: None,
376        }
377    }
378
379    pub fn value(mut self, value: MentionValue) -> Self {
380        self.value = Some(value);
381        self
382    }
383
384    pub fn default_value(mut self, value: MentionValue) -> Self {
385        self.default_value = value;
386        self
387    }
388
389    /// People offered after `@`. Leave it out to turn person mentions off.
390    pub fn people<I>(mut self, people: I) -> Self
391    where
392        I: IntoIterator<Item = MentionPerson>,
393    {
394        self.people = people.into_iter().collect();
395        self
396    }
397
398    /// Channels offered after `#`. Leave it out to turn channel mentions off.
399    pub fn channels<I>(mut self, channels: I) -> Self
400    where
401        I: IntoIterator<Item = MentionChannel>,
402    {
403        self.channels = channels.into_iter().collect();
404        self
405    }
406
407    /// With `submit_on_enter`, Enter submits and Shift+Enter adds a line.
408    pub fn submit_on_enter(mut self, submit: bool) -> Self {
409        self.submit_on_enter = submit;
410        self
411    }
412
413    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
414        self.placeholder = Some(placeholder.into());
415        self
416    }
417
418    pub fn max_suggestions(mut self, max: usize) -> Self {
419        self.max_suggestions = max.max(1);
420        self
421    }
422
423    pub fn disabled(mut self, disabled: bool) -> Self {
424        self.disabled = disabled;
425        self
426    }
427
428    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
429        self.width = Some(width.into());
430        self
431    }
432
433    pub fn on_change(
434        mut self,
435        handler: impl Fn(&MentionValue, &mut Window, &mut App) + 'static,
436    ) -> Self {
437        self.on_change = Some(Rc::new(handler));
438        self
439    }
440
441    /// Called when a suggestion becomes a mention.
442    pub fn on_mention_add(
443        mut self,
444        handler: impl Fn(&Mention, &mut Window, &mut App) + 'static,
445    ) -> Self {
446        self.on_mention_add = Some(Rc::new(handler));
447        self
448    }
449
450    pub fn on_submit(
451        mut self,
452        handler: impl Fn(&MentionValue, &mut Window, &mut App) + 'static,
453    ) -> Self {
454        self.on_submit = Some(Rc::new(handler));
455        self
456    }
457}
458
459impl RenderOnce for MentionInput {
460    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
461        let theme = cx.arc_theme().clone();
462        let colors = theme.colors;
463        let _motion = theme.motion;
464        let _reduced = arc_motion::is_reduced_motion(cx);
465
466        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-mention-state".into());
467        let default_for_init = self
468            .value
469            .clone()
470            .unwrap_or_else(|| self.default_value.clone());
471        let placeholder_for_init = self
472            .placeholder
473            .clone()
474            .unwrap_or_else(|| "Type @ to mention someone, or # for a channel…".into());
475        let internal = window.use_keyed_state(state_id, cx, |window, cx| {
476            let mut st = MentionInputInternal::new(window, cx);
477            st.query_input.update(cx, |s, cx| {
478                s.set_placeholder(placeholder_for_init.clone(), window, cx);
479                if !default_for_init.text.is_empty() {
480                    s.set_value(default_for_init.text.as_str(), window, cx);
481                }
482            });
483            st.value = default_for_init.clone();
484            st
485        });
486
487        let q_in_placeholder = internal.read(cx).query_input.clone();
488        q_in_placeholder.update(cx, |s, cx| {
489            s.set_placeholder(
490                self.placeholder
491                    .clone()
492                    .unwrap_or_else(|| "Type @ to mention someone, or # for a channel…".into()),
493                window,
494                cx,
495            );
496        });
497
498        let is_ctrl = self.value.is_some();
499        // Sync live edits from `KitInput` (`query_input`) into `internal.value` & `on_change`.
500        let live_input = internal.read(cx).query_input.read(cx).value().to_string();
501        let stored_val = internal.read(cx).value.clone();
502        if live_input != stored_val.text {
503            let reconciled = mention_reconcile(
504                &stored_val.mentions,
505                &stored_val.text,
506                &live_input,
507                stored_val.text.chars().count(),
508            );
509            let next_val = MentionValue {
510                text: live_input.clone(),
511                mentions: reconciled,
512            };
513            internal.update(cx, |s, _| {
514                s.value = next_val.clone();
515                s.last_caret = next_val.text.chars().count();
516            });
517            if let Some(handler) = self.on_change.clone() {
518                let next_for_cb = next_val.clone();
519                window.defer(cx, move |window, cx| {
520                    handler(&next_for_cb, window, cx);
521                });
522            }
523        } else if let Some(ext) = self.value.clone()
524            && ext.text != stored_val.text
525        {
526            let q_in = internal.read(cx).query_input.clone();
527            q_in.update(cx, |s, cx| s.set_value(ext.text.as_str(), window, cx));
528            internal.update(cx, |s, _| {
529                s.value = ext;
530            });
531        }
532
533        let value = internal.read(cx).value.clone();
534        let person_enabled = !self.people.is_empty();
535        let channel_enabled = !self.channels.is_empty();
536        let text = value.text.clone();
537
538        let trigger = mention_find_trigger(
539            &text,
540            text.chars().count(),
541            &value.mentions,
542            person_enabled,
543            channel_enabled,
544        );
545
546        let mut suggestions: Vec<MentionSuggestion> = Vec::new();
547        if let Some(trig) = &trigger {
548            let query = trig.query.to_lowercase();
549            let mut scored: Vec<(usize, MentionSuggestion)> = Vec::new();
550            if trig.kind == MentionKind::Person {
551                for p in &self.people {
552                    let score = mention_rank(&p.name, p.role.as_deref().unwrap_or(""), &query);
553                    if score > 0 {
554                        scored.push((score, MentionSuggestion::Person(p.clone())));
555                    }
556                }
557            } else {
558                for c in &self.channels {
559                    let score =
560                        mention_rank(&c.name, c.description.as_deref().unwrap_or(""), &query);
561                    if score > 0 {
562                        scored.push((score, MentionSuggestion::Channel(c.clone())));
563                    }
564                }
565            }
566            scored.sort_by_key(|entry| std::cmp::Reverse(entry.0));
567            suggestions = scored
568                .into_iter()
569                .take(self.max_suggestions)
570                .map(|(_, entry)| entry)
571                .collect();
572        }
573
574        let snap = internal.read(cx).clone();
575        let query_key = trigger
576            .as_ref()
577            .map(|t| format!("{}:{}", t.start, t.query))
578            .unwrap_or_default();
579        let active_index = if snap.last_query_key != query_key {
580            internal.update(cx, |s, _| {
581                s.last_query_key = query_key.clone();
582                s.active_index = 0;
583            });
584            0
585        } else {
586            snap.active_index.min(suggestions.len().saturating_sub(1))
587        };
588        let open = trigger.is_some()
589            && trigger
590                .as_ref()
591                .is_some_and(|t| Some(t.start) != snap.dismissed_start)
592            && (!suggestions.is_empty() || !trigger.as_ref().unwrap().query.contains(' '));
593
594        // ── Insert plumbing ───────────────────────────────────────────────────────────────────
595        let _insert_st = internal.clone();
596        let insert_ch = self.on_change.clone();
597        let insert_add = self.on_mention_add.clone();
598        let insert_is_ctrl = is_ctrl;
599        let insert_people = self.people.clone();
600        let insert_channels = self.channels.clone();
601        let insert_trigger = trigger.clone();
602
603        let _pick_st = internal.clone();
604        #[allow(clippy::type_complexity)]
605        let apply_pick: Rc<
606            dyn Fn(
607                &MentionSuggestion,
608                &gpui_kit::Entity<MentionInputInternal>,
609                &mut Window,
610                &mut App,
611            ),
612        > = Rc::new(
613            move |suggestion: &MentionSuggestion,
614                  st: &gpui_kit::Entity<MentionInputInternal>,
615                  window: &mut Window,
616                  cx: &mut App| {
617                let trig = insert_trigger.clone();
618                let Some(trig) = trig else {
619                    return;
620                };
621                let label = suggestion.label().clone();
622                let token = mention_text(suggestion.kind(), &label);
623                let start = trig.start;
624                let text = st.read(cx).value.text.clone();
625                let chars: Vec<char> = text.chars().collect();
626                let caret = chars.len();
627                let after_space = chars.get(caret).is_none_or(|c| c.is_whitespace());
628                let insertion = if after_space {
629                    format!("{token} ")
630                } else {
631                    token.clone()
632                };
633                let next_text = format!(
634                    "{}{}{}",
635                    text.chars().take(start).collect::<String>(),
636                    insertion,
637                    text.chars().skip(caret).collect::<String>()
638                );
639                let mention = Mention {
640                    kind: suggestion.kind(),
641                    id: suggestion.id().clone(),
642                    label,
643                    start,
644                    end: start + token.chars().count(),
645                };
646                let mentions =
647                    mention_reconcile(&st.read(cx).value.mentions, &text, &next_text, start);
648                let mut mentions = mentions;
649                mentions.push(mention.clone());
650                mentions.sort_by_key(|m| m.start);
651                let next = MentionValue {
652                    text: next_text,
653                    mentions,
654                };
655                let added = mention.clone();
656                let q_in = st.read(cx).query_input.clone();
657                q_in.update(cx, |s, cx| s.set_value(next.text.as_str(), window, cx));
658                st.update(cx, |s, _| {
659                    s.value = next.clone();
660                    s.dismissed_start = None;
661                    s.active_index = 0;
662                });
663                if !insert_is_ctrl {
664                    let _ = insert_is_ctrl;
665                }
666                if let Some(handler) = &insert_ch {
667                    handler(&next, window, cx);
668                }
669                if let Some(handler) = &insert_add {
670                    handler(&added, window, cx);
671                }
672                window.refresh();
673                let _ = (&insert_people, &insert_channels, &insert_trigger);
674            },
675        );
676
677        // ── Suggestions popover ───────────────────────────────────────────────────────────────
678        let _hover_st = internal.clone();
679        let pick_st = internal.clone();
680        let mut row_els: Vec<AnyElement> = Vec::with_capacity(suggestions.len());
681        for (index, suggestion) in suggestions.iter().enumerate() {
682            let is_active = index == active_index;
683            let row_fg = if is_active {
684                colors.foreground
685            } else {
686                colors.text_secondary
687            };
688            let label_text = suggestion.label().clone();
689            let meta_text = suggestion.meta().cloned();
690            let symbol = suggestion.kind().symbol();
691            let st_row_hover = pick_st.clone();
692            let st_row_click = pick_st.clone();
693            let apply_row = apply_pick.clone();
694            let item_clone = suggestion.clone();
695            row_els.push(
696                div()
697                    .id(ElementId::NamedChild(
698                        self.id.clone().into(),
699                        SharedString::from(format!("mention-{index}")),
700                    ))
701                    .test_support()
702                    .role(Role::ListBoxOption)
703                    .aria_selected(is_active)
704                    .aria_label(label_text.clone())
705                    .w_full()
706                    .min_h(px(36.0))
707                    .px(px(10.0))
708                    .flex()
709                    .flex_row()
710                    .items_center()
711                    .gap(px(8.0))
712                    .rounded(px(10.0))
713                    .text_size(Typography::TEXT_SM)
714                    .text_color(row_fg)
715                    .bg(if is_active {
716                        oklab_mix(colors.foreground, colors.surface_raised, 0.065)
717                    } else {
718                        Hsla::transparent_black()
719                    })
720                    .cursor_pointer()
721                    .on_hover(move |hovered, window, cx| {
722                        if *hovered {
723                            st_row_hover.update(cx, |s, _| s.active_index = index);
724                            window.refresh();
725                        }
726                    })
727                    .on_click(move |_, window, cx| {
728                        apply_row(&item_clone, &st_row_click, window, cx);
729                    })
730                    .child(
731                        div()
732                            .size(px(20.0))
733                            .rounded_full()
734                            .bg(colors.control_track)
735                            .flex()
736                            .items_center()
737                            .justify_center()
738                            .text_size(px(10.0))
739                            .text_color(colors.text_muted)
740                            .child(SharedString::from(symbol)),
741                    )
742                    .child(
743                        div()
744                            .flex()
745                            .flex_col()
746                            .min_w_0()
747                            .child(div().font_medium().truncate().child(label_text))
748                            .when_some(meta_text, |this, meta| {
749                                this.child(
750                                    div()
751                                        .text_size(Typography::TEXT_XS)
752                                        .text_color(colors.text_muted)
753                                        .truncate()
754                                        .child(meta),
755                                )
756                            }),
757                    )
758                    .into_any_element(),
759            );
760        }
761
762        let popover_el = if open {
763            let list_id = ElementId::NamedChild(self.id.clone().into(), "mention-list".into());
764            Some(
765                deferred(
766                    div()
767                        .id(list_id)
768                        .test_support()
769                        .role(Role::ListBox)
770                        .aria_label(SharedString::from("Suggestions"))
771                        .absolute()
772                        .top_full()
773                        .mt(px(6.0))
774                        .left_0()
775                        .w(px(MENTION_POPOVER_WIDTH))
776                        .p(px(6.0))
777                        .rounded(Radii::CONTROL)
778                        .border_1()
779                        .border_color(colors.border)
780                        .bg(colors.surface_raised)
781                        .shadow(Shadows::floating(theme.mode))
782                        .overflow_hidden()
783                        .children(row_els),
784                )
785                .with_priority(25),
786            )
787        } else {
788            None
789        };
790
791        let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
792
793        let is_input_focused = snap
794            .query_input
795            .read(cx)
796            .focus_handle(cx)
797            .is_focused(window);
798        let q_for_shell = snap.query_input.clone();
799        let st_at_btn = internal.clone();
800        let ch_at_btn = self.on_change.clone();
801        let st_hash_btn = internal.clone();
802        let ch_hash_btn = self.on_change.clone();
803
804        let mention_pills: Vec<AnyElement> = value
805            .mentions
806            .iter()
807            .map(|m| {
808                let sym = m.kind.symbol();
809                let pill_bg = oklab_mix(colors.accent, colors.surface, 0.14);
810                let pill_border = oklab_mix(colors.accent, colors.border, 0.36);
811                div()
812                    .px(px(8.0))
813                    .py(px(2.0))
814                    .rounded_full()
815                    .border_1()
816                    .border_color(pill_border)
817                    .bg(pill_bg)
818                    .text_size(Typography::TEXT_XS)
819                    .font_medium()
820                    .text_color(colors.foreground)
821                    .child(SharedString::from(format!("{sym}{}", m.label)))
822                    .into_any_element()
823            })
824            .collect();
825
826        let footer_bar = div()
827            .w_full()
828            .pt(px(6.0))
829            .border_t_1()
830            .border_color(colors.border_subtle)
831            .flex()
832            .flex_row()
833            .items_center()
834            .justify_between()
835            .gap(Spacing::S2)
836            .child(
837                div()
838                    .flex()
839                    .flex_row()
840                    .flex_wrap()
841                    .items_center()
842                    .gap(px(6.0))
843                    .when(person_enabled, |this| {
844                        this.child(
845                            div()
846                                .id(ElementId::NamedChild(
847                                    self.id.clone().into(),
848                                    "insert-person-trigger".into(),
849                                ))
850                                .px(px(8.0))
851                                .py(px(2.0))
852                                .rounded(px(6.0))
853                                .bg(colors.surface_muted)
854                                .text_size(Typography::TEXT_XS)
855                                .text_color(colors.text_secondary)
856                                .cursor_pointer()
857                                .on_click(move |_, window, cx| {
858                                    let q_in = st_at_btn.read(cx).query_input.clone();
859                                    let cur = st_at_btn.read(cx).value.clone();
860                                    let sep = if cur.text.is_empty() || cur.text.ends_with(' ') {
861                                        ""
862                                    } else {
863                                        " "
864                                    };
865                                    let next_text = format!("{}{sep}@", cur.text);
866                                    q_in.update(cx, |s, cx| {
867                                        s.set_value(next_text.as_str(), window, cx);
868                                        s.focus(window, cx);
869                                    });
870                                    let next_val = MentionValue {
871                                        text: next_text,
872                                        mentions: cur.mentions,
873                                    };
874                                    st_at_btn.update(cx, |s, _| {
875                                        s.value = next_val.clone();
876                                        s.dismissed_start = None;
877                                    });
878                                    if let Some(cb) = &ch_at_btn {
879                                        cb(&next_val, window, cx);
880                                    }
881                                    window.refresh();
882                                })
883                                .child(SharedString::from("@ Mention")),
884                        )
885                    })
886                    .when(channel_enabled, |this| {
887                        this.child(
888                            div()
889                                .id(ElementId::NamedChild(
890                                    self.id.clone().into(),
891                                    "insert-channel-trigger".into(),
892                                ))
893                                .px(px(8.0))
894                                .py(px(2.0))
895                                .rounded(px(6.0))
896                                .bg(colors.surface_muted)
897                                .text_size(Typography::TEXT_XS)
898                                .text_color(colors.text_secondary)
899                                .cursor_pointer()
900                                .on_click(move |_, window, cx| {
901                                    let q_in = st_hash_btn.read(cx).query_input.clone();
902                                    let cur = st_hash_btn.read(cx).value.clone();
903                                    let sep = if cur.text.is_empty() || cur.text.ends_with(' ') {
904                                        ""
905                                    } else {
906                                        " "
907                                    };
908                                    let next_text = format!("{}{sep}#", cur.text);
909                                    q_in.update(cx, |s, cx| {
910                                        s.set_value(next_text.as_str(), window, cx);
911                                        s.focus(window, cx);
912                                    });
913                                    let next_val = MentionValue {
914                                        text: next_text,
915                                        mentions: cur.mentions,
916                                    };
917                                    st_hash_btn.update(cx, |s, _| {
918                                        s.value = next_val.clone();
919                                        s.dismissed_start = None;
920                                    });
921                                    if let Some(cb) = &ch_hash_btn {
922                                        cb(&next_val, window, cx);
923                                    }
924                                    window.refresh();
925                                })
926                                .child(SharedString::from("# Channel")),
927                        )
928                    })
929                    .children(mention_pills),
930            )
931            .child(
932                div()
933                    .text_size(Typography::TEXT_XS)
934                    .text_color(colors.text_muted)
935                    .child(SharedString::from(format!(
936                        "{} mentions",
937                        value.mentions.len()
938                    ))),
939            );
940
941        div()
942            .id(self.id)
943            .test_support()
944            .aria_label(self.label.clone())
945            .track_focus(&snap.focus_handle.clone())
946            .when_some(self.width, |this, w| this.w(w))
947            .when(self.width.is_none(), |this| this.w_full())
948            .flex()
949            .flex_col()
950            .gap(Spacing::S2)
951            .when(self.disabled, |this| this.opacity(0.5))
952            .child(
953                div()
954                    .text_size(Typography::TEXT_SM)
955                    .font_medium()
956                    .text_color(colors.foreground)
957                    .child(self.label.clone()),
958            )
959            .child(
960                div()
961                    .relative()
962                    .w_full()
963                    .min_h(px(84.0))
964                    .px(px(12.0))
965                    .py(px(10.0))
966                    .flex()
967                    .flex_col()
968                    .justify_between()
969                    .gap(px(8.0))
970                    .rounded(Radii::CONTROL)
971                    .border_1()
972                    .border_color(if is_input_focused || open {
973                        colors.control_fill
974                    } else {
975                        colors.border_strong
976                    })
977                    .bg(colors.surface)
978                    .on_mouse_down(gpui_kit::MouseButton::Left, move |_, window, cx| {
979                        q_for_shell.update(cx, |s, cx| s.focus(window, cx));
980                    })
981                    .child(
982                        div().w_full().min_h(px(28.0)).flex().items_center().child(
983                            KitInput::new(&snap.query_input)
984                                .appearance(false)
985                                .w_full()
986                                .text_size(Typography::TEXT_SM)
987                                .text_color(colors.foreground),
988                        ),
989                    )
990                    .child(footer_bar)
991                    .when_some(popover_el, |this, el| this.child(el)),
992            )
993            .on_key_down({
994                let st_key = internal.clone();
995                let suggestions_key = suggestions.clone();
996                let ch_key = self.on_change.clone();
997                let submit_key = self.on_submit.clone();
998                let is_ctrl_key = is_ctrl;
999                let person_key = person_enabled;
1000                let channel_key = channel_enabled;
1001                let submit_on_enter_flag = self.submit_on_enter;
1002                let apply_key = apply_pick.clone();
1003                move |event: &KeyDownEvent, window, cx| {
1004                    if self.disabled {
1005                        return;
1006                    }
1007                    let key = event.keystroke.key.as_str();
1008                    let trig_now = mention_find_trigger(
1009                        &st_key.read(cx).value.text,
1010                        st_key.read(cx).value.text.chars().count(),
1011                        &st_key.read(cx).value.mentions,
1012                        person_key,
1013                        channel_key,
1014                    );
1015                    match key {
1016                        "down" | "arrowdown" | "up" | "arrowup"
1017                            if trig_now.is_some() && !suggestions_key.is_empty() =>
1018                        {
1019                            let len = suggestions_key.len() as i64;
1020                            let step = if key.starts_with("down") { 1 } else { -1 };
1021                            let cur = st_key.read(cx).active_index as i64;
1022                            let next = (cur + step).rem_euclid(len);
1023                            st_key.update(cx, |s, _| s.active_index = next as usize);
1024                            window.refresh();
1025                        }
1026                        "enter" | "tab" if trig_now.is_some() && !suggestions_key.is_empty() => {
1027                            let idx = st_key.read(cx).active_index;
1028                            if let Some(s) = suggestions_key.get(idx) {
1029                                let apply = apply_key.clone();
1030                                apply(s, &st_key, window, cx);
1031                            }
1032                        }
1033                        "escape" if trig_now.is_some() => {
1034                            st_key.update(cx, |s, _| {
1035                                s.dismissed_start = trig_now.as_ref().map(|t| t.start);
1036                            });
1037                            window.refresh();
1038                        }
1039                        "backspace" => {
1040                            // The Input removes the character; reconcile drops touched mentions.
1041                            let text_before = st_key.read(cx).value.text.clone();
1042                            let mentions_before = st_key.read(cx).value.mentions.clone();
1043                            let next_text: String = text_before
1044                                .chars()
1045                                .take(text_before.chars().count().saturating_sub(1))
1046                                .collect();
1047                            let mentions = mention_reconcile(
1048                                &mentions_before,
1049                                &text_before,
1050                                &next_text,
1051                                text_before.chars().count(),
1052                            );
1053                            let next = MentionValue {
1054                                text: next_text,
1055                                mentions,
1056                            };
1057                            let q_in = st_key.read(cx).query_input.clone();
1058                            q_in.update(cx, |s, cx| s.set_value(next.text.as_str(), window, cx));
1059                            st_key.update(cx, |s, _| {
1060                                s.value = next.clone();
1061                            });
1062                            if let Some(handler) = &ch_key {
1063                                handler(&next, window, cx);
1064                            }
1065                            window.refresh();
1066                        }
1067                        k if k.len() == 1 && k.chars().next().is_some_and(|c| !c.is_control()) => {
1068                            let ch = k.chars().next().unwrap();
1069                            let prev = st_key.read(cx).value.clone();
1070                            let next_text = format!("{}{ch}", prev.text);
1071                            let mentions = mention_reconcile(
1072                                &prev.mentions,
1073                                &prev.text,
1074                                &next_text,
1075                                prev.text.chars().count(),
1076                            );
1077                            let next = MentionValue {
1078                                text: next_text,
1079                                mentions,
1080                            };
1081                            st_key.update(cx, |s, _| {
1082                                s.value = next.clone();
1083                                s.last_caret = next.text.chars().count();
1084                            });
1085                            if let Some(handler) = &ch_key {
1086                                handler(&next, window, cx);
1087                            }
1088                            window.refresh();
1089                        }
1090                        "enter" if trig_now.is_none() && submit_on_enter_flag => {
1091                            let current = st_key.read(cx).value.clone();
1092                            if !current.text.trim().is_empty()
1093                                && let Some(handler) = &submit_key
1094                            {
1095                                handler(&current, window, cx);
1096                            }
1097                            window.refresh();
1098                        }
1099                        _ => {
1100                            let _ = is_ctrl_key;
1101                        }
1102                    }
1103                }
1104            })
1105            .child(render_field_message(msg_id, None, false, window, cx))
1106    }
1107}
1108
1109#[cfg(test)]
1110mod tests {
1111
1112    use super::*;
1113
1114    #[test]
1115    fn mention_find_trigger_matches_upstream_shapes() {
1116        let mentions = Vec::new();
1117        let t = mention_find_trigger("hello @na", 9, &mentions, true, true).unwrap();
1118        assert_eq!(t.kind, MentionKind::Person);
1119        assert_eq!(t.start, 6);
1120        assert_eq!(t.query, "na");
1121        // Channel trigger.
1122        let t = mention_find_trigger("join #gene", 10, &mentions, false, true).unwrap();
1123        assert_eq!(t.kind, MentionKind::Channel);
1124        // Trigger inside a mention is ignored.
1125        let with_mention = vec![Mention {
1126            kind: MentionKind::Person,
1127            id: "u1".into(),
1128            label: "Ada".into(),
1129            start: 6,
1130            end: 10,
1131        }];
1132        assert!(mention_find_trigger("hello @Ada x", 11, &with_mention, true, true).is_none());
1133        // Mid-word trigger is rejected.
1134        assert!(mention_find_trigger("email@na", 8, &mentions, true, true).is_none());
1135    }
1136
1137    #[test]
1138    fn mention_reconcile_shifts_and_drops_touched() {
1139        let mention = Mention {
1140            kind: MentionKind::Person,
1141            id: "u1".into(),
1142            label: "Ada".into(),
1143            start: 6,
1144            end: 10,
1145        };
1146        // Text inserted before the mention shifts it.
1147        let out = mention_reconcile(
1148            std::slice::from_ref(&mention),
1149            "hello @Ada",
1150            "xhello @Ada",
1151            0,
1152        );
1153        assert_eq!(out[0].start, 7);
1154        assert_eq!(out[0].end, 11);
1155        // Editing inside the mention drops it.
1156        let out = mention_reconcile(std::slice::from_ref(&mention), "hello @Ada", "hello @Ad", 9);
1157        assert!(out.is_empty());
1158        // Untouched mentions survive after the edit point.
1159        let out = mention_reconcile(
1160            std::slice::from_ref(&mention),
1161            "hello @Ada",
1162            "hello @Ada!",
1163            10,
1164        );
1165        assert_eq!(out.len(), 1);
1166        assert_eq!(out[0].start, 6);
1167    }
1168
1169    #[test]
1170    fn mention_rank_orders_prefix_first() {
1171        assert_eq!(mention_rank("Ada", "", ""), 1);
1172        assert_eq!(mention_rank("Ada", "", "ad"), 4);
1173        assert_eq!(mention_rank("Grace Hopper", "", "ho"), 3);
1174        assert_eq!(mention_rank("Ada", "math", "ma"), 1);
1175        assert_eq!(mention_rank("Ada", "", "zz"), 0);
1176    }
1177}