BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / composer / slash.rs

slash.rs

22f1841f History
slash.rs 16.7 KiB Download Raw
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}