BlueGit

ict rusty-teams

feat(composer): slash commands in the compose box

- Typing / at the start opens the Teams command list (14 commands, Teams names and descriptions)
- Status commands, /goto, /leavechat, /mute, /unmute, /schedulemessage, /settings, /shortcuts reuse the existing actions
- Commands filtered by chat kind like Teams (no /leavechat in 1:1 or notes, mute only when unmuted)
- Deviation: bot and app commands from installed apps are not listed
- Deviation: confirmations show as an in-app notice instead of the Teams compose banner

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-11-04 · 3 weeks ago

Hash
22f1841f25896180984d793a098a1c20015ebee9
Parent
1ac03fe2
2 files changed +517 −4
crates/app/src/views/composer.rs +24 −4
@@ -35,6 +35,7 @@ mod drafts;
35 35 mod format_menus;
36 36 mod rule;
37 37 mod schedule;
38 mod slash;
38 39 mod table;
39 40
40 41 use super::actions::{
@@ -68,6 +69,7 @@ use crate::theme::{self, ElevatedSurface as _};
68 69 use crate::typing::OutgoingTyping;
69 70 use format_menus::{FormatPopup, paragraph_label};
70 71 use rule::{is_rule_token, render_rule_token};
72 use slash::SlashPopup;
71 73 use table::{TableKey, TableLineMenu, TableMenu, TablePicker, TableViews, is_table_token};
72 74
73 75 const MIN_ROWS: usize = 1;
@@ -198,6 +200,8 @@ pub struct Composer {
198 200 lookup: Option<Task<()>>,
199 201 emoji_popup: Option<EmojiPopup>,
200 202 emoji_dismissed_at: Option<usize>,
203 slash_popup: Option<SlashPopup>,
204 slash_dismissed: bool,
201 205 recent_emoji: emoji::Recent,
202 206 conversion: Option<Conversion>,
203 207 undone_value: Option<String>,
@@ -458,6 +462,8 @@ impl Composer {
458 462 lookup: None,
459 463 emoji_popup: None,
460 464 emoji_dismissed_at: None,
465 slash_popup: None,
466 slash_dismissed: false,
461 467 recent_emoji,
462 468 conversion: None,
463 469 undone_value: None,
@@ -519,6 +525,7 @@ impl Composer {
519 525 self.on_change(window, cx);
520 526 self.update_emoji(cx);
521 527 self.update_mention(cx);
528 self.update_slash(cx);
522 529 self.update_link_preview(cx);
523 530 self.schedule_draft_save(cx);
524 531 }
@@ -558,6 +565,7 @@ impl Composer {
558 565 fn close_popup(&mut self) {
559 566 self.close_mention_popup();
560 567 self.emoji_popup = None;
568 self.slash_popup = None;
561 569 }
562 570
563 571 fn close_mention_popup(&mut self) {
@@ -1654,7 +1662,10 @@ impl Composer {
1654 1662 }
1655 1663
1656 1664 fn popup_is_open(&self) -> bool {
1657 self.emoji_popup.is_some()
1665 self.slash_popup
1666 .as_ref()
1667 .is_some_and(|popup| !popup.commands.is_empty())
1668 || self.emoji_popup.is_some()
1658 1669 || self
1659 1670 .popup
1660 1671 .as_ref()
@@ -1662,7 +1673,10 @@ impl Composer {
1662 1673 }
1663 1674
1664 1675 fn move_highlight(&mut self, delta: isize, cx: &mut Context<Self>) {
1665 if let Some(popup) = self.emoji_popup.as_mut() {
1676 if let Some(popup) = self.slash_popup.as_mut() {
1677 popup.move_highlight(delta);
1678 cx.notify();
1679 } else if let Some(popup) = self.emoji_popup.as_mut() {
1666 1680 popup.move_highlight(delta);
1667 1681 cx.notify();
1668 1682 } else if let Some(popup) = self.popup.as_mut() {
@@ -1673,7 +1687,9 @@ impl Composer {
1673 1687 }
1674 1688
1675 1689 fn accept_popup(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1676 if self.emoji_popup.is_some() {
1690 if self.slash_popup.is_some() {
1691 self.accept_slash(window, cx);
1692 } else if self.emoji_popup.is_some() {
1677 1693 self.accept_emoji(window, cx);
1678 1694 } else {
1679 1695 self.accept_mention(window, cx);
@@ -3319,7 +3335,10 @@ impl Render for Composer {
3319 3335 if let Some(popup) = &this.emoji_popup {
3320 3336 this.emoji_dismissed_at = Some(popup.range.start);
3321 3337 }
3322 if this.popup.is_some() || this.emoji_popup.is_some() {
3338 if this.slash_popup.is_some() {
3339 this.slash_dismissed = true;
3340 }
3341 if this.popup.is_some() || this.emoji_popup.is_some() || this.slash_popup.is_some() {
3323 3342 this.close_popup();
3324 3343 cx.notify();
3325 3344 cx.stop_propagation();
@@ -3339,6 +3358,7 @@ impl Render for Composer {
3339 3358 .relative()
3340 3359 .w_full()
3341 3360 .children(self.render_popup(cx))
3361 .children(self.render_slash_popup(cx))
3342 3362 .children(self.render_emoji_popup(window, cx))
3343 3363 .children(self.render_toolbar(focused, cx))
3344 3364 .children(self.render_schedule(cx))
@@ -35,6 +35,7 @@ mod drafts;
35mod format_menus;
35mod format_menus;
36mod rule;
36mod rule;
37mod schedule;
37mod schedule;
38mod slash;
38mod table;
39mod table;
39
40
40use super::actions::{
41use super::actions::{
@@ -68,6 +69,7 @@ use crate::theme::{self, ElevatedSurface as _};
68use crate::typing::OutgoingTyping;
69use crate::typing::OutgoingTyping;
69use format_menus::{FormatPopup, paragraph_label};
70use format_menus::{FormatPopup, paragraph_label};
70use rule::{is_rule_token, render_rule_token};
71use rule::{is_rule_token, render_rule_token};
72use slash::SlashPopup;
71use table::{TableKey, TableLineMenu, TableMenu, TablePicker, TableViews, is_table_token};
73use table::{TableKey, TableLineMenu, TableMenu, TablePicker, TableViews, is_table_token};
72
74
73const MIN_ROWS: usize = 1;
75const MIN_ROWS: usize = 1;
@@ -198,6 +200,8 @@ pub struct Composer {
198 lookup: Option<Task<()>>,
200 lookup: Option<Task<()>>,
199 emoji_popup: Option<EmojiPopup>,
201 emoji_popup: Option<EmojiPopup>,
200 emoji_dismissed_at: Option<usize>,
202 emoji_dismissed_at: Option<usize>,
203 slash_popup: Option<SlashPopup>,
204 slash_dismissed: bool,
201 recent_emoji: emoji::Recent,
205 recent_emoji: emoji::Recent,
202 conversion: Option<Conversion>,
206 conversion: Option<Conversion>,
203 undone_value: Option<String>,
207 undone_value: Option<String>,
@@ -458,6 +462,8 @@ impl Composer {
458 lookup: None,
462 lookup: None,
459 emoji_popup: None,
463 emoji_popup: None,
460 emoji_dismissed_at: None,
464 emoji_dismissed_at: None,
465 slash_popup: None,
466 slash_dismissed: false,
461 recent_emoji,
467 recent_emoji,
462 conversion: None,
468 conversion: None,
463 undone_value: None,
469 undone_value: None,
@@ -519,6 +525,7 @@ impl Composer {
519 self.on_change(window, cx);
525 self.on_change(window, cx);
520 self.update_emoji(cx);
526 self.update_emoji(cx);
521 self.update_mention(cx);
527 self.update_mention(cx);
528 self.update_slash(cx);
522 self.update_link_preview(cx);
529 self.update_link_preview(cx);
523 self.schedule_draft_save(cx);
530 self.schedule_draft_save(cx);
524 }
531 }
@@ -558,6 +565,7 @@ impl Composer {
558 fn close_popup(&mut self) {
565 fn close_popup(&mut self) {
559 self.close_mention_popup();
566 self.close_mention_popup();
560 self.emoji_popup = None;
567 self.emoji_popup = None;
568 self.slash_popup = None;
561 }
569 }
562
570
563 fn close_mention_popup(&mut self) {
571 fn close_mention_popup(&mut self) {
@@ -1654,7 +1662,10 @@ impl Composer {
1654 }
1662 }
1655
1663
1656 fn popup_is_open(&self) -> bool {
1664 fn popup_is_open(&self) -> bool {
1657 self.emoji_popup.is_some()
1665 self.slash_popup
1666 .as_ref()
1667 .is_some_and(|popup| !popup.commands.is_empty())
1668 || self.emoji_popup.is_some()
1658 || self
1669 || self
1659 .popup
1670 .popup
1660 .as_ref()
1671 .as_ref()
@@ -1662,7 +1673,10 @@ impl Composer {
1662 }
1673 }
1663
1674
1664 fn move_highlight(&mut self, delta: isize, cx: &mut Context<Self>) {
1675 fn move_highlight(&mut self, delta: isize, cx: &mut Context<Self>) {
1665 if let Some(popup) = self.emoji_popup.as_mut() {
1676 if let Some(popup) = self.slash_popup.as_mut() {
1677 popup.move_highlight(delta);
1678 cx.notify();
1679 } else if let Some(popup) = self.emoji_popup.as_mut() {
1666 popup.move_highlight(delta);
1680 popup.move_highlight(delta);
1667 cx.notify();
1681 cx.notify();
1668 } else if let Some(popup) = self.popup.as_mut() {
1682 } else if let Some(popup) = self.popup.as_mut() {
@@ -1673,7 +1687,9 @@ impl Composer {
1673 }
1687 }
1674
1688
1675 fn accept_popup(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1689 fn accept_popup(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1676 if self.emoji_popup.is_some() {
1690 if self.slash_popup.is_some() {
1691 self.accept_slash(window, cx);
1692 } else if self.emoji_popup.is_some() {
1677 self.accept_emoji(window, cx);
1693 self.accept_emoji(window, cx);
1678 } else {
1694 } else {
1679 self.accept_mention(window, cx);
1695 self.accept_mention(window, cx);
@@ -3319,7 +3335,10 @@ impl Render for Composer {
3319 if let Some(popup) = &this.emoji_popup {
3335 if let Some(popup) = &this.emoji_popup {
3320 this.emoji_dismissed_at = Some(popup.range.start);
3336 this.emoji_dismissed_at = Some(popup.range.start);
3321 }
3337 }
3322 if this.popup.is_some() || this.emoji_popup.is_some() {
3338 if this.slash_popup.is_some() {
3339 this.slash_dismissed = true;
3340 }
3341 if this.popup.is_some() || this.emoji_popup.is_some() || this.slash_popup.is_some() {
3323 this.close_popup();
3342 this.close_popup();
3324 cx.notify();
3343 cx.notify();
3325 cx.stop_propagation();
3344 cx.stop_propagation();
@@ -3339,6 +3358,7 @@ impl Render for Composer {
3339 .relative()
3358 .relative()
3340 .w_full()
3359 .w_full()
3341 .children(self.render_popup(cx))
3360 .children(self.render_popup(cx))
3361 .children(self.render_slash_popup(cx))
3342 .children(self.render_emoji_popup(window, cx))
3362 .children(self.render_emoji_popup(window, cx))
3343 .children(self.render_toolbar(focused, cx))
3363 .children(self.render_toolbar(focused, cx))
3344 .children(self.render_schedule(cx))
3364 .children(self.render_schedule(cx))
crates/app/src/views/composer/slash.rs added +493 −0
@@ -0,0 +1,493 @@
1 use std::ops::Range;
2 use std::rc::Rc;
3
4 use gpui_kit::component::{h_flex, v_flex};
5 use gpui_kit::prelude::FluentBuilder as _;
6 use gpui_kit::*;
7 use teams_core::{ForcedAvailability, ForcedKind};
8
9 use super::Composer;
10 use crate::theme::{self, ElevatedSurface as _};
11 use crate::views::actions::OpenSwitcher;
12 use crate::views::shortcuts::{OpenSettings, ShowShortcuts};
13 use crate::views::sidebar::confirm_leave;
14
15 const GROUP_KIND: &str = "group";
16 const WIDTH: f32 = 380.;
17 const ROW_HEIGHT: f32 = 32.;
18 const HEADER_HEIGHT: f32 = 28.;
19 const VISIBLE_ROWS: usize = 8;
20 const NAME_WIDTH: f32 = 128.;
21 pub const HEADER: &str = "Commands";
22 pub const NO_RESULTS: &str = "No results";
23
24 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
25 pub enum SlashCommand {
26 Presence(ForcedKind),
27 ResetPresence,
28 Goto,
29 LeaveChat,
30 Mute,
31 Unmute,
32 ScheduleMessage,
33 Settings,
34 Shortcuts,
35 }
36
37 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
38 pub struct SlashContext {
39 pub chat: bool,
40 pub notes: bool,
41 pub group: bool,
42 pub muted: bool,
43 }
44
45 impl SlashCommand {
46 pub const ALL: [SlashCommand; 14] = [
47 SlashCommand::Presence(ForcedKind::Available),
48 SlashCommand::Presence(ForcedKind::Away),
49 SlashCommand::Presence(ForcedKind::BeRightBack),
50 SlashCommand::Presence(ForcedKind::Busy),
51 SlashCommand::Presence(ForcedKind::DoNotDisturb),
52 SlashCommand::Goto,
53 SlashCommand::LeaveChat,
54 SlashCommand::Mute,
55 SlashCommand::Presence(ForcedKind::Offline),
56 SlashCommand::ResetPresence,
57 SlashCommand::ScheduleMessage,
58 SlashCommand::Settings,
59 SlashCommand::Shortcuts,
60 SlashCommand::Unmute,
61 ];
62
63 pub fn name(self) -> &'static str {
64 match self {
65 SlashCommand::Presence(ForcedKind::Available) => "available",
66 SlashCommand::Presence(ForcedKind::Away) => "away",
67 SlashCommand::Presence(ForcedKind::BeRightBack) => "brb",
68 SlashCommand::Presence(ForcedKind::Busy) => "busy",
69 SlashCommand::Presence(ForcedKind::DoNotDisturb) => "dnd",
70 SlashCommand::Presence(ForcedKind::Offline) => "offline",
71 SlashCommand::ResetPresence => "reset",
72 SlashCommand::Goto => "goto",
73 SlashCommand::LeaveChat => "leavechat",
74 SlashCommand::Mute => "mute",
75 SlashCommand::Unmute => "unmute",
76 SlashCommand::ScheduleMessage => "schedulemessage",
77 SlashCommand::Settings => "settings",
78 SlashCommand::Shortcuts => "shortcuts",
79 }
80 }
81
82 pub fn description(self) -> &'static str {
83 match self {
84 SlashCommand::Presence(ForcedKind::Available) => "Set your status to available",
85 SlashCommand::Presence(ForcedKind::Away) => "Set your status to away",
86 SlashCommand::Presence(ForcedKind::BeRightBack) => "Set your status to be right back",
87 SlashCommand::Presence(ForcedKind::Busy) => "Set your status to busy",
88 SlashCommand::Presence(ForcedKind::DoNotDisturb) => {
89 "Set your status to do not disturb"
90 }
91 SlashCommand::Presence(ForcedKind::Offline) => "Set your status to offline",
92 SlashCommand::ResetPresence => "Reset your presence status",
93 SlashCommand::Goto => "Go right to a chat or channel",
94 SlashCommand::LeaveChat => "Leave the chat",
95 SlashCommand::Mute => "Mute the chat",
96 SlashCommand::Unmute => "Unmute the chat",
97 SlashCommand::ScheduleMessage => "Schedule a message",
98 SlashCommand::Settings => "Open Settings",
99 SlashCommand::Shortcuts => "Open keyboard shortcuts",
100 }
101 }
102
103 pub fn confirmation(self) -> Option<&'static str> {
104 match self {
105 SlashCommand::Presence(ForcedKind::Available) => {
106 Some("Your status is set to available.")
107 }
108 SlashCommand::Presence(ForcedKind::Away) => Some("Your status is set to away."),
109 SlashCommand::Presence(ForcedKind::BeRightBack) => {
110 Some("Your status is set to be right back.")
111 }
112 SlashCommand::Presence(ForcedKind::Busy) => Some("Your status is set to busy."),
113 SlashCommand::Presence(ForcedKind::DoNotDisturb) => {
114 Some("Your status is set to do not disturb.")
115 }
116 SlashCommand::Presence(ForcedKind::Offline) => Some("Your status is set to offline."),
117 SlashCommand::ResetPresence => Some("Your presence status is reset."),
118 _ => None,
119 }
120 }
121
122 fn available_in(self, context: SlashContext) -> bool {
123 match self {
124 SlashCommand::LeaveChat => context.chat && context.group,
125 SlashCommand::Mute => context.chat && !context.notes && !context.muted,
126 SlashCommand::Unmute => context.chat && !context.notes && context.muted,
127 SlashCommand::ScheduleMessage => context.chat && !context.notes,
128 _ => true,
129 }
130 }
131 }
132
133 fn commands() -> impl Iterator<Item = SlashCommand> {
134 SlashCommand::ALL.iter().copied()
135 }
136
137 /// The command query while the draft starts with "/" and the caret is still in its first word.
138 pub fn active_query(value: &str, cursor: usize) -> Option<(Range<usize>, String)> {
139 if !value.starts_with('/') || cursor == 0 || cursor > value.len() {
140 return None;
141 }
142 let typed = value.get(1..cursor)?;
143 if typed.chars().any(char::is_whitespace) {
144 return None;
145 }
146 let word_end = value
147 .char_indices()
148 .find(|(_, character)| character.is_whitespace())
149 .map_or(value.len(), |(index, _)| index);
150 if cursor < word_end {
151 return None;
152 }
153 Some((0..cursor, typed.to_lowercase()))
154 }
155
156 pub fn matching(query: &str, context: SlashContext) -> Vec<SlashCommand> {
157 let available: Vec<SlashCommand> = commands()
158 .filter(|command| command.available_in(context))
159 .collect();
160 let starts = available
161 .iter()
162 .filter(|command| command.name().starts_with(query));
163 let contains = available
164 .iter()
165 .filter(|command| !command.name().starts_with(query) && command.name().contains(query));
166 let described = available.iter().filter(|command| {
167 !command.name().contains(query) && command.description().to_lowercase().contains(query)
168 });
169 starts.chain(contains).chain(described).copied().collect()
170 }
171
172 pub struct SlashPopup {
173 pub range: Range<usize>,
174 pub query: String,
175 pub commands: Vec<SlashCommand>,
176 pub highlighted: usize,
177 scroll: ScrollHandle,
178 }
179
180 impl SlashPopup {
181 pub fn new(range: Range<usize>, query: String, commands: Vec<SlashCommand>) -> Self {
182 SlashPopup {
183 range,
184 query,
185 commands,
186 highlighted: 0,
187 scroll: ScrollHandle::new(),
188 }
189 }
190
191 pub fn move_highlight(&mut self, delta: isize) {
192 let count = self.commands.len() as isize;
193 if count > 0 {
194 self.highlighted = (self.highlighted as isize + delta).rem_euclid(count) as usize;
195 self.scroll.scroll_to_item(self.highlighted);
196 }
197 }
198
199 pub fn selected(&self) -> Option<SlashCommand> {
200 self.commands.get(self.highlighted).copied()
201 }
202 }
203
204 fn row(index: usize, command: SlashCommand, selected: bool) -> Stateful<Div> {
205 h_flex()
206 .id(ElementId::Name(format!("slash-row-{index}").into()))
207 .flex_none()
208 .h(px(ROW_HEIGHT))
209 .px(px(8.))
210 .gap(px(8.))
211 .items_center()
212 .rounded(px(6.))
213 .cursor_pointer()
214 .when(selected, |row| row.bg(theme::popup_hover()))
215 .hover(|row| row.bg(theme::popup_hover()))
216 .child(
217 div()
218 .w(px(NAME_WIDTH))
219 .flex_none()
220 .truncate()
221 .text_size(px(13.))
222 .font_weight(FontWeight::SEMIBOLD)
223 .text_color(theme::text())
224 .child(format!("/{}", command.name())),
225 )
226 .child(
227 div()
228 .flex_1()
229 .min_w_0()
230 .truncate()
231 .text_size(px(12.))
232 .text_color(theme::text_muted())
233 .child(command.description()),
234 )
235 }
236
237 fn label(text: &'static str) -> Div {
238 h_flex()
239 .h(px(HEADER_HEIGHT))
240 .px(px(8.))
241 .items_center()
242 .text_size(px(12.))
243 .font_weight(FontWeight::SEMIBOLD)
244 .text_color(theme::text_muted())
245 .child(text)
246 }
247
248 pub fn render(
249 popup: &SlashPopup,
250 on_pick: impl Fn(usize, &mut Window, &mut App) + 'static,
251 ) -> AnyElement {
252 let on_pick = Rc::new(on_pick);
253 let rows = popup.commands.iter().enumerate().map(|(index, command)| {
254 let on_pick = on_pick.clone();
255 row(index, *command, index == popup.highlighted)
256 .on_click(move |_, window, cx| on_pick(index, window, cx))
257 });
258 let visible = popup.commands.len().clamp(1, VISIBLE_ROWS) as f32;
259 v_flex()
260 .id("slash-popup")
261 .absolute()
262 .bottom(relative(1.))
263 .left_0()
264 .mb(px(6.))
265 .w(px(WIDTH))
266 .p(px(4.))
267 .rounded(px(10.))
268 .flyout_surface()
269 .occlude()
270 .child(label(HEADER))
271 .when(popup.commands.is_empty(), |panel| {
272 panel.child(
273 h_flex()
274 .h(px(ROW_HEIGHT))
275 .flex_none()
276 .px(px(8.))
277 .items_center()
278 .text_size(px(13.))
279 .text_color(theme::text_muted())
280 .child(NO_RESULTS),
281 )
282 })
283 .when(!popup.commands.is_empty(), |panel| {
284 panel.child(
285 v_flex()
286 .id("slash-rows")
287 .max_h(px(ROW_HEIGHT * visible))
288 .overflow_y_scroll()
289 .track_scroll(&popup.scroll)
290 .children(rows),
291 )
292 })
293 .into_any_element()
294 }
295
296 impl Composer {
297 fn slash_context(&self, cx: &App) -> SlashContext {
298 let Some(conversation_id) = self.conversation_id.as_deref() else {
299 return SlashContext::default();
300 };
301 let state = self.app.read(cx);
302 let Some(chat) = state
303 .sidebar
304 .chats
305 .iter()
306 .find(|chat| chat.id == conversation_id)
307 else {
308 return SlashContext::default();
309 };
310 SlashContext {
311 chat: true,
312 notes: teams_core::is_notes_chat(conversation_id),
313 group: chat.kind == GROUP_KIND,
314 muted: chat.muted,
315 }
316 }
317
318 pub(super) fn update_slash(&mut self, cx: &mut Context<Self>) {
319 let state = self.input.read(cx);
320 let found = active_query(&state.value(), state.cursor()).filter(|_| self.editing.is_none());
321 let Some((range, query)) = found else {
322 self.slash_popup = None;
323 self.slash_dismissed = false;
324 return;
325 };
326 if self.slash_dismissed {
327 return;
328 }
329 let unchanged = self
330 .slash_popup
331 .as_ref()
332 .is_some_and(|popup| popup.query == query && popup.range == range);
333 if unchanged {
334 return;
335 }
336 let commands = matching(&query, self.slash_context(cx));
337 self.slash_popup = Some(SlashPopup::new(range, query, commands));
338 }
339
340 pub(super) fn accept_slash(&mut self, window: &mut Window, cx: &mut Context<Self>) {
341 let Some(popup) = self.slash_popup.take() else {
342 return;
343 };
344 let Some(command) = popup.selected() else {
345 return;
346 };
347 self.replace_text(popup.range, "", 0, window, cx);
348 self.run_slash_command(command, window, cx);
349 cx.notify();
350 }
351
352 fn run_slash_command(
353 &mut self,
354 command: SlashCommand,
355 window: &mut Window,
356 cx: &mut Context<Self>,
357 ) {
358 let chat_id = self.conversation_id.clone().unwrap_or_default();
359 match command {
360 SlashCommand::Presence(kind) => self.set_presence(
361 Some(ForcedAvailability {
362 kind,
363 expires_at: None,
364 }),
365 command,
366 cx,
367 ),
368 SlashCommand::ResetPresence => self.set_presence(None, command, cx),
369 SlashCommand::Goto => window.dispatch_action(Box::new(OpenSwitcher), cx),
370 SlashCommand::Settings => window.dispatch_action(Box::new(OpenSettings), cx),
371 SlashCommand::Shortcuts => window.dispatch_action(Box::new(ShowShortcuts), cx),
372 SlashCommand::ScheduleMessage => self.open_schedule_menu(cx),
373 SlashCommand::Mute | SlashCommand::Unmute => {
374 let muted = command == SlashCommand::Mute;
375 self.app
376 .update(cx, |state, cx| state.set_chat_muted(&chat_id, muted, cx));
377 }
378 SlashCommand::LeaveChat => {
379 let Some(chat) = self
380 .app
381 .read(cx)
382 .sidebar
383 .chats
384 .iter()
385 .find(|chat| chat.id == chat_id)
386 .cloned()
387 else {
388 return;
389 };
390 let title = crate::app_state::chat_title(&chat);
391 confirm_leave(&self.app, &chat_id, &title, chat.members.len(), window, cx);
392 }
393 }
394 }
395
396 fn set_presence(
397 &mut self,
398 forced: Option<ForcedAvailability>,
399 command: SlashCommand,
400 cx: &mut Context<Self>,
401 ) {
402 self.app.update(cx, |state, cx| {
403 state.set_own_availability(forced, cx);
404 if let Some(text) = command.confirmation() {
405 state.raise_notice(text.to_owned(), None, cx);
406 }
407 });
408 }
409
410 pub(super) fn render_slash_popup(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
411 let popup = self.slash_popup.as_ref()?;
412 let composer = cx.entity().downgrade();
413 Some(render(popup, move |index, window, cx| {
414 composer
415 .update(cx, |this, cx| {
416 if let Some(popup) = this.slash_popup.as_mut() {
417 popup.highlighted = index;
418 }
419 this.accept_slash(window, cx);
420 })
421 .ok();
422 }))
423 }
424 }
425
426 #[cfg(test)]
427 mod tests {
428 use super::{SlashContext, active_query, matching};
429
430 fn chat() -> SlashContext {
431 SlashContext {
432 chat: true,
433 ..SlashContext::default()
434 }
435 }
436
437 #[test]
438 fn a_slash_at_the_start_opens_the_list() {
439 assert_eq!(active_query("/", 1), Some((0..1, String::new())));
440 assert_eq!(active_query("/Aw", 3), Some((0..3, "aw".to_owned())));
441 }
442
443 #[test]
444 fn a_slash_later_in_the_text_or_after_a_space_does_not_open() {
445 assert_eq!(active_query("hi /away", 8), None);
446 assert_eq!(active_query("/away now", 9), None);
447 assert_eq!(active_query("/away", 0), None);
448 assert_eq!(active_query("/away", 2), None);
449 }
450
451 #[test]
452 fn the_list_is_sorted_by_name_like_teams() {
453 let names: Vec<&str> = matching("", chat()).iter().map(|command| command.name()).collect();
454 let mut sorted = names.clone();
455 sorted.sort_unstable();
456 assert_eq!(names, sorted);
457 assert!(names.contains(&"mute") && !names.contains(&"unmute"));
458 assert!(!names.contains(&"leavechat"));
459 }
460
461 #[test]
462 fn name_prefix_matches_come_before_description_matches() {
463 let found = matching("b", chat());
464 assert_eq!(found[0].name(), "brb");
465 assert_eq!(found[1].name(), "busy");
466 assert!(found.iter().any(|command| command.name() == "available"));
467 assert_eq!(matching("status", chat())[0].name(), "available");
468 }
469
470 #[test]
471 fn commands_follow_the_conversation() {
472 let group_muted = SlashContext {
473 chat: true,
474 group: true,
475 muted: true,
476 notes: false,
477 };
478 let names: Vec<&str> = matching("", group_muted).iter().map(|command| command.name()).collect();
479 assert!(names.contains(&"leavechat") && names.contains(&"unmute") && !names.contains(&"mute"));
480 let notes = SlashContext {
481 chat: true,
482 notes: true,
483 ..SlashContext::default()
484 };
485 let names: Vec<&str> = matching("", notes).iter().map(|command| command.name()).collect();
486 assert!(!names.contains(&"mute") && !names.contains(&"schedulemessage"));
487 let channel: Vec<&str> = matching("", SlashContext::default())
488 .iter()
489 .map(|command| command.name())
490 .collect();
491 assert!(channel.contains(&"goto") && !channel.contains(&"leavechat"));
492 }
493 }
@@ -0,0 +1,493 @@
1use std::ops::Range;
2use std::rc::Rc;
3
4use gpui_kit::component::{h_flex, v_flex};
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
7use teams_core::{ForcedAvailability, ForcedKind};
8
9use super::Composer;
10use crate::theme::{self, ElevatedSurface as _};
11use crate::views::actions::OpenSwitcher;
12use crate::views::shortcuts::{OpenSettings, ShowShortcuts};
13use crate::views::sidebar::confirm_leave;
14
15const GROUP_KIND: &str = "group";
16const WIDTH: f32 = 380.;
17const ROW_HEIGHT: f32 = 32.;
18const HEADER_HEIGHT: f32 = 28.;
19const VISIBLE_ROWS: usize = 8;
20const NAME_WIDTH: f32 = 128.;
21pub const HEADER: &str = "Commands";
22pub const NO_RESULTS: &str = "No results";
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum SlashCommand {
26 Presence(ForcedKind),
27 ResetPresence,
28 Goto,
29 LeaveChat,
30 Mute,
31 Unmute,
32 ScheduleMessage,
33 Settings,
34 Shortcuts,
35}
36
37#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
38pub struct SlashContext {
39 pub chat: bool,
40 pub notes: bool,
41 pub group: bool,
42 pub muted: bool,
43}
44
45impl SlashCommand {
46 pub const ALL: [SlashCommand; 14] = [
47 SlashCommand::Presence(ForcedKind::Available),
48 SlashCommand::Presence(ForcedKind::Away),
49 SlashCommand::Presence(ForcedKind::BeRightBack),
50 SlashCommand::Presence(ForcedKind::Busy),
51 SlashCommand::Presence(ForcedKind::DoNotDisturb),
52 SlashCommand::Goto,
53 SlashCommand::LeaveChat,
54 SlashCommand::Mute,
55 SlashCommand::Presence(ForcedKind::Offline),
56 SlashCommand::ResetPresence,
57 SlashCommand::ScheduleMessage,
58 SlashCommand::Settings,
59 SlashCommand::Shortcuts,
60 SlashCommand::Unmute,
61 ];
62
63 pub fn name(self) -> &'static str {
64 match self {
65 SlashCommand::Presence(ForcedKind::Available) => "available",
66 SlashCommand::Presence(ForcedKind::Away) => "away",
67 SlashCommand::Presence(ForcedKind::BeRightBack) => "brb",
68 SlashCommand::Presence(ForcedKind::Busy) => "busy",
69 SlashCommand::Presence(ForcedKind::DoNotDisturb) => "dnd",
70 SlashCommand::Presence(ForcedKind::Offline) => "offline",
71 SlashCommand::ResetPresence => "reset",
72 SlashCommand::Goto => "goto",
73 SlashCommand::LeaveChat => "leavechat",
74 SlashCommand::Mute => "mute",
75 SlashCommand::Unmute => "unmute",
76 SlashCommand::ScheduleMessage => "schedulemessage",
77 SlashCommand::Settings => "settings",
78 SlashCommand::Shortcuts => "shortcuts",
79 }
80 }
81
82 pub fn description(self) -> &'static str {
83 match self {
84 SlashCommand::Presence(ForcedKind::Available) => "Set your status to available",
85 SlashCommand::Presence(ForcedKind::Away) => "Set your status to away",
86 SlashCommand::Presence(ForcedKind::BeRightBack) => "Set your status to be right back",
87 SlashCommand::Presence(ForcedKind::Busy) => "Set your status to busy",
88 SlashCommand::Presence(ForcedKind::DoNotDisturb) => {
89 "Set your status to do not disturb"
90 }
91 SlashCommand::Presence(ForcedKind::Offline) => "Set your status to offline",
92 SlashCommand::ResetPresence => "Reset your presence status",
93 SlashCommand::Goto => "Go right to a chat or channel",
94 SlashCommand::LeaveChat => "Leave the chat",
95 SlashCommand::Mute => "Mute the chat",
96 SlashCommand::Unmute => "Unmute the chat",
97 SlashCommand::ScheduleMessage => "Schedule a message",
98 SlashCommand::Settings => "Open Settings",
99 SlashCommand::Shortcuts => "Open keyboard shortcuts",
100 }
101 }
102
103 pub fn confirmation(self) -> Option<&'static str> {
104 match self {
105 SlashCommand::Presence(ForcedKind::Available) => {
106 Some("Your status is set to available.")
107 }
108 SlashCommand::Presence(ForcedKind::Away) => Some("Your status is set to away."),
109 SlashCommand::Presence(ForcedKind::BeRightBack) => {
110 Some("Your status is set to be right back.")
111 }
112 SlashCommand::Presence(ForcedKind::Busy) => Some("Your status is set to busy."),
113 SlashCommand::Presence(ForcedKind::DoNotDisturb) => {
114 Some("Your status is set to do not disturb.")
115 }
116 SlashCommand::Presence(ForcedKind::Offline) => Some("Your status is set to offline."),
117 SlashCommand::ResetPresence => Some("Your presence status is reset."),
118 _ => None,
119 }
120 }
121
122 fn available_in(self, context: SlashContext) -> bool {
123 match self {
124 SlashCommand::LeaveChat => context.chat && context.group,
125 SlashCommand::Mute => context.chat && !context.notes && !context.muted,
126 SlashCommand::Unmute => context.chat && !context.notes && context.muted,
127 SlashCommand::ScheduleMessage => context.chat && !context.notes,
128 _ => true,
129 }
130 }
131}
132
133fn commands() -> impl Iterator<Item = SlashCommand> {
134 SlashCommand::ALL.iter().copied()
135}
136
137/// The command query while the draft starts with "/" and the caret is still in its first word.
138pub fn active_query(value: &str, cursor: usize) -> Option<(Range<usize>, String)> {
139 if !value.starts_with('/') || cursor == 0 || cursor > value.len() {
140 return None;
141 }
142 let typed = value.get(1..cursor)?;
143 if typed.chars().any(char::is_whitespace) {
144 return None;
145 }
146 let word_end = value
147 .char_indices()
148 .find(|(_, character)| character.is_whitespace())
149 .map_or(value.len(), |(index, _)| index);
150 if cursor < word_end {
151 return None;
152 }
153 Some((0..cursor, typed.to_lowercase()))
154}
155
156pub fn matching(query: &str, context: SlashContext) -> Vec<SlashCommand> {
157 let available: Vec<SlashCommand> = commands()
158 .filter(|command| command.available_in(context))
159 .collect();
160 let starts = available
161 .iter()
162 .filter(|command| command.name().starts_with(query));
163 let contains = available
164 .iter()
165 .filter(|command| !command.name().starts_with(query) && command.name().contains(query));
166 let described = available.iter().filter(|command| {
167 !command.name().contains(query) && command.description().to_lowercase().contains(query)
168 });
169 starts.chain(contains).chain(described).copied().collect()
170}
171
172pub struct SlashPopup {
173 pub range: Range<usize>,
174 pub query: String,
175 pub commands: Vec<SlashCommand>,
176 pub highlighted: usize,
177 scroll: ScrollHandle,
178}
179
180impl SlashPopup {
181 pub fn new(range: Range<usize>, query: String, commands: Vec<SlashCommand>) -> Self {
182 SlashPopup {
183 range,
184 query,
185 commands,
186 highlighted: 0,
187 scroll: ScrollHandle::new(),
188 }
189 }
190
191 pub fn move_highlight(&mut self, delta: isize) {
192 let count = self.commands.len() as isize;
193 if count > 0 {
194 self.highlighted = (self.highlighted as isize + delta).rem_euclid(count) as usize;
195 self.scroll.scroll_to_item(self.highlighted);
196 }
197 }
198
199 pub fn selected(&self) -> Option<SlashCommand> {
200 self.commands.get(self.highlighted).copied()
201 }
202}
203
204fn row(index: usize, command: SlashCommand, selected: bool) -> Stateful<Div> {
205 h_flex()
206 .id(ElementId::Name(format!("slash-row-{index}").into()))
207 .flex_none()
208 .h(px(ROW_HEIGHT))
209 .px(px(8.))
210 .gap(px(8.))
211 .items_center()
212 .rounded(px(6.))
213 .cursor_pointer()
214 .when(selected, |row| row.bg(theme::popup_hover()))
215 .hover(|row| row.bg(theme::popup_hover()))
216 .child(
217 div()
218 .w(px(NAME_WIDTH))
219 .flex_none()
220 .truncate()
221 .text_size(px(13.))
222 .font_weight(FontWeight::SEMIBOLD)
223 .text_color(theme::text())
224 .child(format!("/{}", command.name())),
225 )
226 .child(
227 div()
228 .flex_1()
229 .min_w_0()
230 .truncate()
231 .text_size(px(12.))
232 .text_color(theme::text_muted())
233 .child(command.description()),
234 )
235}
236
237fn label(text: &'static str) -> Div {
238 h_flex()
239 .h(px(HEADER_HEIGHT))
240 .px(px(8.))
241 .items_center()
242 .text_size(px(12.))
243 .font_weight(FontWeight::SEMIBOLD)
244 .text_color(theme::text_muted())
245 .child(text)
246}
247
248pub fn render(
249 popup: &SlashPopup,
250 on_pick: impl Fn(usize, &mut Window, &mut App) + 'static,
251) -> AnyElement {
252 let on_pick = Rc::new(on_pick);
253 let rows = popup.commands.iter().enumerate().map(|(index, command)| {
254 let on_pick = on_pick.clone();
255 row(index, *command, index == popup.highlighted)
256 .on_click(move |_, window, cx| on_pick(index, window, cx))
257 });
258 let visible = popup.commands.len().clamp(1, VISIBLE_ROWS) as f32;
259 v_flex()
260 .id("slash-popup")
261 .absolute()
262 .bottom(relative(1.))
263 .left_0()
264 .mb(px(6.))
265 .w(px(WIDTH))
266 .p(px(4.))
267 .rounded(px(10.))
268 .flyout_surface()
269 .occlude()
270 .child(label(HEADER))
271 .when(popup.commands.is_empty(), |panel| {
272 panel.child(
273 h_flex()
274 .h(px(ROW_HEIGHT))
275 .flex_none()
276 .px(px(8.))
277 .items_center()
278 .text_size(px(13.))
279 .text_color(theme::text_muted())
280 .child(NO_RESULTS),
281 )
282 })
283 .when(!popup.commands.is_empty(), |panel| {
284 panel.child(
285 v_flex()
286 .id("slash-rows")
287 .max_h(px(ROW_HEIGHT * visible))
288 .overflow_y_scroll()
289 .track_scroll(&popup.scroll)
290 .children(rows),
291 )
292 })
293 .into_any_element()
294}
295
296impl Composer {
297 fn slash_context(&self, cx: &App) -> SlashContext {
298 let Some(conversation_id) = self.conversation_id.as_deref() else {
299 return SlashContext::default();
300 };
301 let state = self.app.read(cx);
302 let Some(chat) = state
303 .sidebar
304 .chats
305 .iter()
306 .find(|chat| chat.id == conversation_id)
307 else {
308 return SlashContext::default();
309 };
310 SlashContext {
311 chat: true,
312 notes: teams_core::is_notes_chat(conversation_id),
313 group: chat.kind == GROUP_KIND,
314 muted: chat.muted,
315 }
316 }
317
318 pub(super) fn update_slash(&mut self, cx: &mut Context<Self>) {
319 let state = self.input.read(cx);
320 let found = active_query(&state.value(), state.cursor()).filter(|_| self.editing.is_none());
321 let Some((range, query)) = found else {
322 self.slash_popup = None;
323 self.slash_dismissed = false;
324 return;
325 };
326 if self.slash_dismissed {
327 return;
328 }
329 let unchanged = self
330 .slash_popup
331 .as_ref()
332 .is_some_and(|popup| popup.query == query && popup.range == range);
333 if unchanged {
334 return;
335 }
336 let commands = matching(&query, self.slash_context(cx));
337 self.slash_popup = Some(SlashPopup::new(range, query, commands));
338 }
339
340 pub(super) fn accept_slash(&mut self, window: &mut Window, cx: &mut Context<Self>) {
341 let Some(popup) = self.slash_popup.take() else {
342 return;
343 };
344 let Some(command) = popup.selected() else {
345 return;
346 };
347 self.replace_text(popup.range, "", 0, window, cx);
348 self.run_slash_command(command, window, cx);
349 cx.notify();
350 }
351
352 fn run_slash_command(
353 &mut self,
354 command: SlashCommand,
355 window: &mut Window,
356 cx: &mut Context<Self>,
357 ) {
358 let chat_id = self.conversation_id.clone().unwrap_or_default();
359 match command {
360 SlashCommand::Presence(kind) => self.set_presence(
361 Some(ForcedAvailability {
362 kind,
363 expires_at: None,
364 }),
365 command,
366 cx,
367 ),
368 SlashCommand::ResetPresence => self.set_presence(None, command, cx),
369 SlashCommand::Goto => window.dispatch_action(Box::new(OpenSwitcher), cx),
370 SlashCommand::Settings => window.dispatch_action(Box::new(OpenSettings), cx),
371 SlashCommand::Shortcuts => window.dispatch_action(Box::new(ShowShortcuts), cx),
372 SlashCommand::ScheduleMessage => self.open_schedule_menu(cx),
373 SlashCommand::Mute | SlashCommand::Unmute => {
374 let muted = command == SlashCommand::Mute;
375 self.app
376 .update(cx, |state, cx| state.set_chat_muted(&chat_id, muted, cx));
377 }
378 SlashCommand::LeaveChat => {
379 let Some(chat) = self
380 .app
381 .read(cx)
382 .sidebar
383 .chats
384 .iter()
385 .find(|chat| chat.id == chat_id)
386 .cloned()
387 else {
388 return;
389 };
390 let title = crate::app_state::chat_title(&chat);
391 confirm_leave(&self.app, &chat_id, &title, chat.members.len(), window, cx);
392 }
393 }
394 }
395
396 fn set_presence(
397 &mut self,
398 forced: Option<ForcedAvailability>,
399 command: SlashCommand,
400 cx: &mut Context<Self>,
401 ) {
402 self.app.update(cx, |state, cx| {
403 state.set_own_availability(forced, cx);
404 if let Some(text) = command.confirmation() {
405 state.raise_notice(text.to_owned(), None, cx);
406 }
407 });
408 }
409
410 pub(super) fn render_slash_popup(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
411 let popup = self.slash_popup.as_ref()?;
412 let composer = cx.entity().downgrade();
413 Some(render(popup, move |index, window, cx| {
414 composer
415 .update(cx, |this, cx| {
416 if let Some(popup) = this.slash_popup.as_mut() {
417 popup.highlighted = index;
418 }
419 this.accept_slash(window, cx);
420 })
421 .ok();
422 }))
423 }
424}
425
426#[cfg(test)]
427mod tests {
428 use super::{SlashContext, active_query, matching};
429
430 fn chat() -> SlashContext {
431 SlashContext {
432 chat: true,
433 ..SlashContext::default()
434 }
435 }
436
437 #[test]
438 fn a_slash_at_the_start_opens_the_list() {
439 assert_eq!(active_query("/", 1), Some((0..1, String::new())));
440 assert_eq!(active_query("/Aw", 3), Some((0..3, "aw".to_owned())));
441 }
442
443 #[test]
444 fn a_slash_later_in_the_text_or_after_a_space_does_not_open() {
445 assert_eq!(active_query("hi /away", 8), None);
446 assert_eq!(active_query("/away now", 9), None);
447 assert_eq!(active_query("/away", 0), None);
448 assert_eq!(active_query("/away", 2), None);
449 }
450
451 #[test]
452 fn the_list_is_sorted_by_name_like_teams() {
453 let names: Vec<&str> = matching("", chat()).iter().map(|command| command.name()).collect();
454 let mut sorted = names.clone();
455 sorted.sort_unstable();
456 assert_eq!(names, sorted);
457 assert!(names.contains(&"mute") && !names.contains(&"unmute"));
458 assert!(!names.contains(&"leavechat"));
459 }
460
461 #[test]
462 fn name_prefix_matches_come_before_description_matches() {
463 let found = matching("b", chat());
464 assert_eq!(found[0].name(), "brb");
465 assert_eq!(found[1].name(), "busy");
466 assert!(found.iter().any(|command| command.name() == "available"));
467 assert_eq!(matching("status", chat())[0].name(), "available");
468 }
469
470 #[test]
471 fn commands_follow_the_conversation() {
472 let group_muted = SlashContext {
473 chat: true,
474 group: true,
475 muted: true,
476 notes: false,
477 };
478 let names: Vec<&str> = matching("", group_muted).iter().map(|command| command.name()).collect();
479 assert!(names.contains(&"leavechat") && names.contains(&"unmute") && !names.contains(&"mute"));
480 let notes = SlashContext {
481 chat: true,
482 notes: true,
483 ..SlashContext::default()
484 };
485 let names: Vec<&str> = matching("", notes).iter().map(|command| command.name()).collect();
486 assert!(!names.contains(&"mute") && !names.contains(&"schedulemessage"));
487 let channel: Vec<&str> = matching("", SlashContext::default())
488 .iter()
489 .map(|command| command.name())
490 .collect();
491 assert!(channel.contains(&"goto") && !channel.contains(&"leavechat"));
492 }
493}