use std::rc::Rc;
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, Typography, oklab_mix};
use gpui_kit::{
AnyElement, App, ElementId, Entity, FocusHandle, Focusable as _, Hsla, IntoElement,
KeyDownEvent, ParentElement, Pixels, RenderOnce, Role, SharedString, Styled,
TestSupportExt as _, Window,
base::StyledExt as _,
component::input::{Input as KitInput, InputState},
deferred, div,
prelude::*,
px,
};
use super::field_message::render_field_message;
const MENTION_POPOVER_WIDTH: f32 = 272.0;
pub fn mention_text(kind: MentionKind, label: &str) -> String {
format!("{}{label}", kind.symbol())
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Mention {
pub kind: MentionKind,
pub id: SharedString,
pub label: SharedString,
pub start: usize,
pub end: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MentionKind {
Person,
Channel,
}
impl MentionKind {
pub fn symbol(self) -> &'static str {
match self {
Self::Person => "@",
Self::Channel => "#",
}
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MentionValue {
pub text: String,
pub mentions: Vec<Mention>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct MentionPerson {
pub id: SharedString,
pub name: SharedString,
pub role: Option<SharedString>,
}
impl MentionPerson {
pub fn new(id: impl Into<SharedString>, name: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
name: name.into(),
role: None,
}
}
pub fn role(mut self, role: impl Into<SharedString>) -> Self {
self.role = Some(role.into());
self
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct MentionChannel {
pub id: SharedString,
pub name: SharedString,
pub description: Option<SharedString>,
}
impl MentionChannel {
pub fn new(id: impl Into<SharedString>, name: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
name: name.into(),
description: None,
}
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum MentionSuggestion {
Person(MentionPerson),
Channel(MentionChannel),
}
impl MentionSuggestion {
fn id(&self) -> &SharedString {
match self {
Self::Person(p) => &p.id,
Self::Channel(c) => &c.id,
}
}
fn label(&self) -> &SharedString {
match self {
Self::Person(p) => &p.name,
Self::Channel(c) => &c.name,
}
}
fn meta(&self) -> Option<&SharedString> {
match self {
Self::Person(p) => p.role.as_ref(),
Self::Channel(c) => c.description.as_ref(),
}
}
fn kind(&self) -> MentionKind {
match self {
Self::Person(_) => MentionKind::Person,
Self::Channel(_) => MentionKind::Channel,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct MentionTrigger {
pub kind: MentionKind,
pub start: usize,
pub query: String,
}
pub fn mention_find_trigger(
text: &str,
caret: usize,
mentions: &[Mention],
person_enabled: bool,
channel_enabled: bool,
) -> Option<MentionTrigger> {
let chars: Vec<char> = text.chars().collect();
let caret = caret.min(chars.len());
for index in (0..caret).rev() {
if caret - index > 48 {
break;
}
let ch = chars[index];
if ch == '\n' {
return None;
}
if ch != '@' && ch != '#' {
continue;
}
let kind = if ch == '@' {
MentionKind::Person
} else {
MentionKind::Channel
};
if (kind == MentionKind::Person && !person_enabled)
|| (kind == MentionKind::Channel && !channel_enabled)
{
return None;
}
if index > 0 {
let prev = chars[index - 1];
if !(prev.is_whitespace() || matches!(prev, '(' | '[' | '{' | '"' | '\'')) {
return None;
}
}
if mentions.iter().any(|m| index >= m.start && index < m.end) {
return None;
}
let query: String = chars[index + 1..caret].iter().collect();
let shape_ok = if kind == MentionKind::Person {
let parts: Vec<&str> = query.split(' ').collect();
parts.len() <= 2
&& parts.iter().all(|p| {
!p.contains(['@', '#']) && !p.chars().any(|c| c.is_whitespace()) || p.is_empty()
})
} else {
!query.contains(['@', '#']) && !query.chars().any(|c| c.is_whitespace())
};
if shape_ok {
return Some(MentionTrigger {
kind,
start: index,
query,
});
}
return None;
}
None
}
pub fn mention_rank(label: &str, extra: &str, query: &str) -> usize {
let name = label.to_lowercase();
if query.is_empty() {
return 1;
}
if name.starts_with(query) {
return 4;
}
if name
.split([' ', '-', '_', '.'])
.any(|word| word.starts_with(query))
{
return 3;
}
if name.contains(query) {
return 2;
}
if extra.to_lowercase().contains(query) {
return 1;
}
0
}
pub fn mention_reconcile(
previous: &[Mention],
old_text: &str,
text: &str,
hint: usize,
) -> Vec<Mention> {
let a: Vec<char> = old_text.chars().collect();
let b: Vec<char> = text.chars().collect();
let mut prefix = 0usize;
let max_prefix = a.len().min(b.len()).min(hint);
while prefix < max_prefix && a[prefix] == b[prefix] {
prefix += 1;
}
let mut suffix = 0usize;
while suffix < a.len() - prefix
&& suffix < b.len() - prefix
&& a[a.len() - 1 - suffix] == b[b.len() - 1 - suffix]
{
suffix += 1;
}
let old_end = a.len() - suffix;
let delta = b.len() as i64 - a.len() as i64;
let out: Vec<Mention> = previous
.iter()
.filter_map(|mention| {
if mention.end <= prefix {
return Some(mention.clone());
}
if mention.start >= old_end {
let start = (mention.start as i64 + delta) as usize;
let end = (mention.end as i64 + delta) as usize;
return Some(Mention {
start,
end,
..mention.clone()
});
}
None
})
.filter(|mention| {
let chars: Vec<char> = text.chars().collect();
if mention.end > chars.len() || mention.start > mention.end {
return false;
}
let slice: String = chars[mention.start..mention.end].iter().collect();
slice == mention_text(mention.kind, &mention.label)
})
.collect();
out
}
type MentionChangeHandler = Rc<dyn Fn(&MentionValue, &mut Window, &mut App)>;
type MentionAddHandler = Rc<dyn Fn(&Mention, &mut Window, &mut App)>;
type MentionSubmitHandler = Rc<dyn Fn(&MentionValue, &mut Window, &mut App)>;
#[derive(Clone)]
struct MentionInputInternal {
value: MentionValue,
last_caret: usize,
dismissed_start: Option<usize>,
active_index: usize,
last_query_key: String,
query_input: Entity<InputState>,
focus_handle: FocusHandle,
}
impl MentionInputInternal {
fn new(window: &mut Window, cx: &mut App) -> Self {
let query_input = cx.new(|cx| InputState::new(window, cx));
Self {
value: MentionValue::default(),
last_caret: 0,
dismissed_start: None,
active_index: 0,
last_query_key: String::new(),
query_input,
focus_handle: cx.focus_handle(),
}
}
}
#[derive(IntoElement)]
pub struct MentionInput {
id: ElementId,
label: SharedString,
value: Option<MentionValue>,
default_value: MentionValue,
people: Vec<MentionPerson>,
channels: Vec<MentionChannel>,
submit_on_enter: bool,
placeholder: Option<SharedString>,
max_suggestions: usize,
disabled: bool,
width: Option<Pixels>,
on_change: Option<MentionChangeHandler>,
on_mention_add: Option<MentionAddHandler>,
on_submit: Option<MentionSubmitHandler>,
}
impl MentionInput {
pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
value: None,
default_value: MentionValue::default(),
people: Vec::new(),
channels: Vec::new(),
submit_on_enter: false,
placeholder: None,
max_suggestions: 6,
disabled: false,
width: None,
on_change: None,
on_mention_add: None,
on_submit: None,
}
}
pub fn value(mut self, value: MentionValue) -> Self {
self.value = Some(value);
self
}
pub fn default_value(mut self, value: MentionValue) -> Self {
self.default_value = value;
self
}
pub fn people<I>(mut self, people: I) -> Self
where
I: IntoIterator<Item = MentionPerson>,
{
self.people = people.into_iter().collect();
self
}
pub fn channels<I>(mut self, channels: I) -> Self
where
I: IntoIterator<Item = MentionChannel>,
{
self.channels = channels.into_iter().collect();
self
}
pub fn submit_on_enter(mut self, submit: bool) -> Self {
self.submit_on_enter = submit;
self
}
pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
self.placeholder = Some(placeholder.into());
self
}
pub fn max_suggestions(mut self, max: usize) -> Self {
self.max_suggestions = max.max(1);
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn width(mut self, width: impl Into<Pixels>) -> Self {
self.width = Some(width.into());
self
}
pub fn on_change(
mut self,
handler: impl Fn(&MentionValue, &mut Window, &mut App) + 'static,
) -> Self {
self.on_change = Some(Rc::new(handler));
self
}
pub fn on_mention_add(
mut self,
handler: impl Fn(&Mention, &mut Window, &mut App) + 'static,
) -> Self {
self.on_mention_add = Some(Rc::new(handler));
self
}
pub fn on_submit(
mut self,
handler: impl Fn(&MentionValue, &mut Window, &mut App) + 'static,
) -> Self {
self.on_submit = Some(Rc::new(handler));
self
}
}
impl RenderOnce for MentionInput {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let _motion = theme.motion;
let _reduced = arc_motion::is_reduced_motion(cx);
let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-mention-state".into());
let default_for_init = self
.value
.clone()
.unwrap_or_else(|| self.default_value.clone());
let placeholder_for_init = self
.placeholder
.clone()
.unwrap_or_else(|| "Type @ to mention someone, or # for a channel…".into());
let internal = window.use_keyed_state(state_id, cx, |window, cx| {
let mut st = MentionInputInternal::new(window, cx);
st.query_input.update(cx, |s, cx| {
s.set_placeholder(placeholder_for_init.clone(), window, cx);
if !default_for_init.text.is_empty() {
s.set_value(default_for_init.text.as_str(), window, cx);
}
});
st.value = default_for_init.clone();
st
});
let q_in_placeholder = internal.read(cx).query_input.clone();
q_in_placeholder.update(cx, |s, cx| {
s.set_placeholder(
self.placeholder
.clone()
.unwrap_or_else(|| "Type @ to mention someone, or # for a channel…".into()),
window,
cx,
);
});
let is_ctrl = self.value.is_some();
let live_input = internal.read(cx).query_input.read(cx).value().to_string();
let stored_val = internal.read(cx).value.clone();
if live_input != stored_val.text {
let reconciled = mention_reconcile(
&stored_val.mentions,
&stored_val.text,
&live_input,
stored_val.text.chars().count(),
);
let next_val = MentionValue {
text: live_input.clone(),
mentions: reconciled,
};
internal.update(cx, |s, _| {
s.value = next_val.clone();
s.last_caret = next_val.text.chars().count();
});
if let Some(handler) = self.on_change.clone() {
let next_for_cb = next_val.clone();
window.defer(cx, move |window, cx| {
handler(&next_for_cb, window, cx);
});
}
} else if let Some(ext) = self.value.clone()
&& ext.text != stored_val.text
{
let q_in = internal.read(cx).query_input.clone();
q_in.update(cx, |s, cx| s.set_value(ext.text.as_str(), window, cx));
internal.update(cx, |s, _| {
s.value = ext;
});
}
let value = internal.read(cx).value.clone();
let person_enabled = !self.people.is_empty();
let channel_enabled = !self.channels.is_empty();
let text = value.text.clone();
let trigger = mention_find_trigger(
&text,
text.chars().count(),
&value.mentions,
person_enabled,
channel_enabled,
);
let mut suggestions: Vec<MentionSuggestion> = Vec::new();
if let Some(trig) = &trigger {
let query = trig.query.to_lowercase();
let mut scored: Vec<(usize, MentionSuggestion)> = Vec::new();
if trig.kind == MentionKind::Person {
for p in &self.people {
let score = mention_rank(&p.name, p.role.as_deref().unwrap_or(""), &query);
if score > 0 {
scored.push((score, MentionSuggestion::Person(p.clone())));
}
}
} else {
for c in &self.channels {
let score =
mention_rank(&c.name, c.description.as_deref().unwrap_or(""), &query);
if score > 0 {
scored.push((score, MentionSuggestion::Channel(c.clone())));
}
}
}
scored.sort_by_key(|entry| std::cmp::Reverse(entry.0));
suggestions = scored
.into_iter()
.take(self.max_suggestions)
.map(|(_, entry)| entry)
.collect();
}
let snap = internal.read(cx).clone();
let query_key = trigger
.as_ref()
.map(|t| format!("{}:{}", t.start, t.query))
.unwrap_or_default();
let active_index = if snap.last_query_key != query_key {
internal.update(cx, |s, _| {
s.last_query_key = query_key.clone();
s.active_index = 0;
});
0
} else {
snap.active_index.min(suggestions.len().saturating_sub(1))
};
let open = trigger.is_some()
&& trigger
.as_ref()
.is_some_and(|t| Some(t.start) != snap.dismissed_start)
&& (!suggestions.is_empty() || !trigger.as_ref().unwrap().query.contains(' '));
let _insert_st = internal.clone();
let insert_ch = self.on_change.clone();
let insert_add = self.on_mention_add.clone();
let insert_is_ctrl = is_ctrl;
let insert_people = self.people.clone();
let insert_channels = self.channels.clone();
let insert_trigger = trigger.clone();
let _pick_st = internal.clone();
#[allow(clippy::type_complexity)]
let apply_pick: Rc<
dyn Fn(
&MentionSuggestion,
&gpui_kit::Entity<MentionInputInternal>,
&mut Window,
&mut App,
),
> = Rc::new(
move |suggestion: &MentionSuggestion,
st: &gpui_kit::Entity<MentionInputInternal>,
window: &mut Window,
cx: &mut App| {
let trig = insert_trigger.clone();
let Some(trig) = trig else {
return;
};
let label = suggestion.label().clone();
let token = mention_text(suggestion.kind(), &label);
let start = trig.start;
let text = st.read(cx).value.text.clone();
let chars: Vec<char> = text.chars().collect();
let caret = chars.len();
let after_space = chars.get(caret).is_none_or(|c| c.is_whitespace());
let insertion = if after_space {
format!("{token} ")
} else {
token.clone()
};
let next_text = format!(
"{}{}{}",
text.chars().take(start).collect::<String>(),
insertion,
text.chars().skip(caret).collect::<String>()
);
let mention = Mention {
kind: suggestion.kind(),
id: suggestion.id().clone(),
label,
start,
end: start + token.chars().count(),
};
let mentions =
mention_reconcile(&st.read(cx).value.mentions, &text, &next_text, start);
let mut mentions = mentions;
mentions.push(mention.clone());
mentions.sort_by_key(|m| m.start);
let next = MentionValue {
text: next_text,
mentions,
};
let added = mention.clone();
let q_in = st.read(cx).query_input.clone();
q_in.update(cx, |s, cx| s.set_value(next.text.as_str(), window, cx));
st.update(cx, |s, _| {
s.value = next.clone();
s.dismissed_start = None;
s.active_index = 0;
});
if !insert_is_ctrl {
let _ = insert_is_ctrl;
}
if let Some(handler) = &insert_ch {
handler(&next, window, cx);
}
if let Some(handler) = &insert_add {
handler(&added, window, cx);
}
window.refresh();
let _ = (&insert_people, &insert_channels, &insert_trigger);
},
);
let _hover_st = internal.clone();
let pick_st = internal.clone();
let mut row_els: Vec<AnyElement> = Vec::with_capacity(suggestions.len());
for (index, suggestion) in suggestions.iter().enumerate() {
let is_active = index == active_index;
let row_fg = if is_active {
colors.foreground
} else {
colors.text_secondary
};
let label_text = suggestion.label().clone();
let meta_text = suggestion.meta().cloned();
let symbol = suggestion.kind().symbol();
let st_row_hover = pick_st.clone();
let st_row_click = pick_st.clone();
let apply_row = apply_pick.clone();
let item_clone = suggestion.clone();
row_els.push(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
SharedString::from(format!("mention-{index}")),
))
.test_support()
.role(Role::ListBoxOption)
.aria_selected(is_active)
.aria_label(label_text.clone())
.w_full()
.min_h(px(36.0))
.px(px(10.0))
.flex()
.flex_row()
.items_center()
.gap(px(8.0))
.rounded(px(10.0))
.text_size(Typography::TEXT_SM)
.text_color(row_fg)
.bg(if is_active {
oklab_mix(colors.foreground, colors.surface_raised, 0.065)
} else {
Hsla::transparent_black()
})
.cursor_pointer()
.on_hover(move |hovered, window, cx| {
if *hovered {
st_row_hover.update(cx, |s, _| s.active_index = index);
window.refresh();
}
})
.on_click(move |_, window, cx| {
apply_row(&item_clone, &st_row_click, window, cx);
})
.child(
div()
.size(px(20.0))
.rounded_full()
.bg(colors.control_track)
.flex()
.items_center()
.justify_center()
.text_size(px(10.0))
.text_color(colors.text_muted)
.child(SharedString::from(symbol)),
)
.child(
div()
.flex()
.flex_col()
.min_w_0()
.child(div().font_medium().truncate().child(label_text))
.when_some(meta_text, |this, meta| {
this.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.truncate()
.child(meta),
)
}),
)
.into_any_element(),
);
}
let popover_el = if open {
let list_id = ElementId::NamedChild(self.id.clone().into(), "mention-list".into());
Some(
deferred(
div()
.id(list_id)
.test_support()
.role(Role::ListBox)
.aria_label(SharedString::from("Suggestions"))
.absolute()
.top_full()
.mt(px(6.0))
.left_0()
.w(px(MENTION_POPOVER_WIDTH))
.p(px(6.0))
.rounded(Radii::CONTROL)
.border_1()
.border_color(colors.border)
.bg(colors.surface_raised)
.shadow(Shadows::floating(theme.mode))
.overflow_hidden()
.children(row_els),
)
.with_priority(25),
)
} else {
None
};
let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
let is_input_focused = snap
.query_input
.read(cx)
.focus_handle(cx)
.is_focused(window);
let q_for_shell = snap.query_input.clone();
let st_at_btn = internal.clone();
let ch_at_btn = self.on_change.clone();
let st_hash_btn = internal.clone();
let ch_hash_btn = self.on_change.clone();
let mention_pills: Vec<AnyElement> = value
.mentions
.iter()
.map(|m| {
let sym = m.kind.symbol();
let pill_bg = oklab_mix(colors.accent, colors.surface, 0.14);
let pill_border = oklab_mix(colors.accent, colors.border, 0.36);
div()
.px(px(8.0))
.py(px(2.0))
.rounded_full()
.border_1()
.border_color(pill_border)
.bg(pill_bg)
.text_size(Typography::TEXT_XS)
.font_medium()
.text_color(colors.foreground)
.child(SharedString::from(format!("{sym}{}", m.label)))
.into_any_element()
})
.collect();
let footer_bar = div()
.w_full()
.pt(px(6.0))
.border_t_1()
.border_color(colors.border_subtle)
.flex()
.flex_row()
.items_center()
.justify_between()
.gap(Spacing::S2)
.child(
div()
.flex()
.flex_row()
.flex_wrap()
.items_center()
.gap(px(6.0))
.when(person_enabled, |this| {
this.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"insert-person-trigger".into(),
))
.px(px(8.0))
.py(px(2.0))
.rounded(px(6.0))
.bg(colors.surface_muted)
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.cursor_pointer()
.on_click(move |_, window, cx| {
let q_in = st_at_btn.read(cx).query_input.clone();
let cur = st_at_btn.read(cx).value.clone();
let sep = if cur.text.is_empty() || cur.text.ends_with(' ') {
""
} else {
" "
};
let next_text = format!("{}{sep}@", cur.text);
q_in.update(cx, |s, cx| {
s.set_value(next_text.as_str(), window, cx);
s.focus(window, cx);
});
let next_val = MentionValue {
text: next_text,
mentions: cur.mentions,
};
st_at_btn.update(cx, |s, _| {
s.value = next_val.clone();
s.dismissed_start = None;
});
if let Some(cb) = &ch_at_btn {
cb(&next_val, window, cx);
}
window.refresh();
})
.child(SharedString::from("@ Mention")),
)
})
.when(channel_enabled, |this| {
this.child(
div()
.id(ElementId::NamedChild(
self.id.clone().into(),
"insert-channel-trigger".into(),
))
.px(px(8.0))
.py(px(2.0))
.rounded(px(6.0))
.bg(colors.surface_muted)
.text_size(Typography::TEXT_XS)
.text_color(colors.text_secondary)
.cursor_pointer()
.on_click(move |_, window, cx| {
let q_in = st_hash_btn.read(cx).query_input.clone();
let cur = st_hash_btn.read(cx).value.clone();
let sep = if cur.text.is_empty() || cur.text.ends_with(' ') {
""
} else {
" "
};
let next_text = format!("{}{sep}#", cur.text);
q_in.update(cx, |s, cx| {
s.set_value(next_text.as_str(), window, cx);
s.focus(window, cx);
});
let next_val = MentionValue {
text: next_text,
mentions: cur.mentions,
};
st_hash_btn.update(cx, |s, _| {
s.value = next_val.clone();
s.dismissed_start = None;
});
if let Some(cb) = &ch_hash_btn {
cb(&next_val, window, cx);
}
window.refresh();
})
.child(SharedString::from("# Channel")),
)
})
.children(mention_pills),
)
.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(SharedString::from(format!(
"{} mentions",
value.mentions.len()
))),
);
div()
.id(self.id)
.test_support()
.aria_label(self.label.clone())
.track_focus(&snap.focus_handle.clone())
.when_some(self.width, |this, w| this.w(w))
.when(self.width.is_none(), |this| this.w_full())
.flex()
.flex_col()
.gap(Spacing::S2)
.when(self.disabled, |this| this.opacity(0.5))
.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(self.label.clone()),
)
.child(
div()
.relative()
.w_full()
.min_h(px(84.0))
.px(px(12.0))
.py(px(10.0))
.flex()
.flex_col()
.justify_between()
.gap(px(8.0))
.rounded(Radii::CONTROL)
.border_1()
.border_color(if is_input_focused || open {
colors.control_fill
} else {
colors.border_strong
})
.bg(colors.surface)
.on_mouse_down(gpui_kit::MouseButton::Left, move |_, window, cx| {
q_for_shell.update(cx, |s, cx| s.focus(window, cx));
})
.child(
div().w_full().min_h(px(28.0)).flex().items_center().child(
KitInput::new(&snap.query_input)
.appearance(false)
.w_full()
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground),
),
)
.child(footer_bar)
.when_some(popover_el, |this, el| this.child(el)),
)
.on_key_down({
let st_key = internal.clone();
let suggestions_key = suggestions.clone();
let ch_key = self.on_change.clone();
let submit_key = self.on_submit.clone();
let is_ctrl_key = is_ctrl;
let person_key = person_enabled;
let channel_key = channel_enabled;
let submit_on_enter_flag = self.submit_on_enter;
let apply_key = apply_pick.clone();
move |event: &KeyDownEvent, window, cx| {
if self.disabled {
return;
}
let key = event.keystroke.key.as_str();
let trig_now = mention_find_trigger(
&st_key.read(cx).value.text,
st_key.read(cx).value.text.chars().count(),
&st_key.read(cx).value.mentions,
person_key,
channel_key,
);
match key {
"down" | "arrowdown" | "up" | "arrowup"
if trig_now.is_some() && !suggestions_key.is_empty() =>
{
let len = suggestions_key.len() as i64;
let step = if key.starts_with("down") { 1 } else { -1 };
let cur = st_key.read(cx).active_index as i64;
let next = (cur + step).rem_euclid(len);
st_key.update(cx, |s, _| s.active_index = next as usize);
window.refresh();
}
"enter" | "tab" if trig_now.is_some() && !suggestions_key.is_empty() => {
let idx = st_key.read(cx).active_index;
if let Some(s) = suggestions_key.get(idx) {
let apply = apply_key.clone();
apply(s, &st_key, window, cx);
}
}
"escape" if trig_now.is_some() => {
st_key.update(cx, |s, _| {
s.dismissed_start = trig_now.as_ref().map(|t| t.start);
});
window.refresh();
}
"backspace" => {
let text_before = st_key.read(cx).value.text.clone();
let mentions_before = st_key.read(cx).value.mentions.clone();
let next_text: String = text_before
.chars()
.take(text_before.chars().count().saturating_sub(1))
.collect();
let mentions = mention_reconcile(
&mentions_before,
&text_before,
&next_text,
text_before.chars().count(),
);
let next = MentionValue {
text: next_text,
mentions,
};
let q_in = st_key.read(cx).query_input.clone();
q_in.update(cx, |s, cx| s.set_value(next.text.as_str(), window, cx));
st_key.update(cx, |s, _| {
s.value = next.clone();
});
if let Some(handler) = &ch_key {
handler(&next, window, cx);
}
window.refresh();
}
k if k.len() == 1 && k.chars().next().is_some_and(|c| !c.is_control()) => {
let ch = k.chars().next().unwrap();
let prev = st_key.read(cx).value.clone();
let next_text = format!("{}{ch}", prev.text);
let mentions = mention_reconcile(
&prev.mentions,
&prev.text,
&next_text,
prev.text.chars().count(),
);
let next = MentionValue {
text: next_text,
mentions,
};
st_key.update(cx, |s, _| {
s.value = next.clone();
s.last_caret = next.text.chars().count();
});
if let Some(handler) = &ch_key {
handler(&next, window, cx);
}
window.refresh();
}
"enter" if trig_now.is_none() && submit_on_enter_flag => {
let current = st_key.read(cx).value.clone();
if !current.text.trim().is_empty()
&& let Some(handler) = &submit_key
{
handler(¤t, window, cx);
}
window.refresh();
}
_ => {
let _ = is_ctrl_key;
}
}
}
})
.child(render_field_message(msg_id, None, false, window, cx))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mention_find_trigger_matches_upstream_shapes() {
let mentions = Vec::new();
let t = mention_find_trigger("hello @na", 9, &mentions, true, true).unwrap();
assert_eq!(t.kind, MentionKind::Person);
assert_eq!(t.start, 6);
assert_eq!(t.query, "na");
let t = mention_find_trigger("join #gene", 10, &mentions, false, true).unwrap();
assert_eq!(t.kind, MentionKind::Channel);
let with_mention = vec![Mention {
kind: MentionKind::Person,
id: "u1".into(),
label: "Ada".into(),
start: 6,
end: 10,
}];
assert!(mention_find_trigger("hello @Ada x", 11, &with_mention, true, true).is_none());
assert!(mention_find_trigger("email@na", 8, &mentions, true, true).is_none());
}
#[test]
fn mention_reconcile_shifts_and_drops_touched() {
let mention = Mention {
kind: MentionKind::Person,
id: "u1".into(),
label: "Ada".into(),
start: 6,
end: 10,
};
let out = mention_reconcile(
std::slice::from_ref(&mention),
"hello @Ada",
"xhello @Ada",
0,
);
assert_eq!(out[0].start, 7);
assert_eq!(out[0].end, 11);
let out = mention_reconcile(std::slice::from_ref(&mention), "hello @Ada", "hello @Ad", 9);
assert!(out.is_empty());
let out = mention_reconcile(
std::slice::from_ref(&mention),
"hello @Ada",
"hello @Ada!",
10,
);
assert_eq!(out.len(), 1);
assert_eq!(out[0].start, 6);
}
#[test]
fn mention_rank_orders_prefix_first() {
assert_eq!(mention_rank("Ada", "", ""), 1);
assert_eq!(mention_rank("Ada", "", "ad"), 4);
assert_eq!(mention_rank("Grace Hopper", "", "ho"), 3);
assert_eq!(mention_rank("Ada", "math", "ma"), 1);
assert_eq!(mention_rank("Ada", "", "zz"), 0);
}
}