BlueGit

ict rusty-teams

Files

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

slash.rs

slash.rs 17.0 KiB Download Raw
1use std::ops::Range;
2use std::rc::Rc;
3
4use gpui_kit::component::scroll::ScrollableElement as _;
5use gpui_kit::component::{h_flex, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
8use teams_core::{ForcedAvailability, ForcedKind};
9
10use super::Composer;
11use crate::theme::{self, ElevatedSurface as _};
12use crate::views::actions::OpenSwitcher;
13use crate::views::chat_menu::confirm_leave;
14use crate::views::shortcuts::{OpenSettings, ShowShortcuts};
15
16const GROUP_KIND: &str = "group";
17const WIDTH: f32 = 380.;
18const ROW_HEIGHT: f32 = 32.;
19const HEADER_HEIGHT: f32 = 28.;
20const VISIBLE_ROWS: usize = 8;
21const NAME_WIDTH: f32 = 128.;
22pub const HEADER: &str = "Commands";
23pub const NO_RESULTS: &str = "No results";
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum SlashCommand {
27 Presence(ForcedKind),
28 ResetPresence,
29 Goto,
30 LeaveChat,
31 Mute,
32 Unmute,
33 ScheduleMessage,
34 Settings,
35 Shortcuts,
36}
37
38#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
39pub struct SlashContext {
40 pub chat: bool,
41 pub notes: bool,
42 pub group: bool,
43 pub muted: bool,
44}
45
46impl SlashCommand {
47 pub const ALL: [SlashCommand; 14] = [
48 SlashCommand::Presence(ForcedKind::Available),
49 SlashCommand::Presence(ForcedKind::Away),
50 SlashCommand::Presence(ForcedKind::BeRightBack),
51 SlashCommand::Presence(ForcedKind::Busy),
52 SlashCommand::Presence(ForcedKind::DoNotDisturb),
53 SlashCommand::Goto,
54 SlashCommand::LeaveChat,
55 SlashCommand::Mute,
56 SlashCommand::Presence(ForcedKind::Offline),
57 SlashCommand::ResetPresence,
58 SlashCommand::ScheduleMessage,
59 SlashCommand::Settings,
60 SlashCommand::Shortcuts,
61 SlashCommand::Unmute,
62 ];
63
64 pub fn name(self) -> &'static str {
65 match self {
66 SlashCommand::Presence(ForcedKind::Available) => "available",
67 SlashCommand::Presence(ForcedKind::Away) => "away",
68 SlashCommand::Presence(ForcedKind::BeRightBack) => "brb",
69 SlashCommand::Presence(ForcedKind::Busy) => "busy",
70 SlashCommand::Presence(ForcedKind::DoNotDisturb) => "dnd",
71 SlashCommand::Presence(ForcedKind::Offline) => "offline",
72 SlashCommand::ResetPresence => "reset",
73 SlashCommand::Goto => "goto",
74 SlashCommand::LeaveChat => "leavechat",
75 SlashCommand::Mute => "mute",
76 SlashCommand::Unmute => "unmute",
77 SlashCommand::ScheduleMessage => "schedulemessage",
78 SlashCommand::Settings => "settings",
79 SlashCommand::Shortcuts => "shortcuts",
80 }
81 }
82
83 pub fn description(self) -> &'static str {
84 match self {
85 SlashCommand::Presence(ForcedKind::Available) => "Set your status to available",
86 SlashCommand::Presence(ForcedKind::Away) => "Set your status to away",
87 SlashCommand::Presence(ForcedKind::BeRightBack) => "Set your status to be right back",
88 SlashCommand::Presence(ForcedKind::Busy) => "Set your status to busy",
89 SlashCommand::Presence(ForcedKind::DoNotDisturb) => "Set your status to do not disturb",
90 SlashCommand::Presence(ForcedKind::Offline) => "Set your status to offline",
91 SlashCommand::ResetPresence => "Reset your presence status",
92 SlashCommand::Goto => "Go right to a chat or channel",
93 SlashCommand::LeaveChat => "Leave the chat",
94 SlashCommand::Mute => "Mute the chat",
95 SlashCommand::Unmute => "Unmute the chat",
96 SlashCommand::ScheduleMessage => "Schedule a message",
97 SlashCommand::Settings => "Open Settings",
98 SlashCommand::Shortcuts => "Open keyboard shortcuts",
99 }
100 }
101
102 pub fn confirmation(self) -> Option<&'static str> {
103 match self {
104 SlashCommand::Presence(ForcedKind::Available) => {
105 Some("Your status is set to available.")
106 }
107 SlashCommand::Presence(ForcedKind::Away) => Some("Your status is set to away."),
108 SlashCommand::Presence(ForcedKind::BeRightBack) => {
109 Some("Your status is set to be right back.")
110 }
111 SlashCommand::Presence(ForcedKind::Busy) => Some("Your status is set to busy."),
112 SlashCommand::Presence(ForcedKind::DoNotDisturb) => {
113 Some("Your status is set to do not disturb.")
114 }
115 SlashCommand::Presence(ForcedKind::Offline) => Some("Your status is set to offline."),
116 SlashCommand::ResetPresence => Some("Your presence status is reset."),
117 _ => None,
118 }
119 }
120
121 fn available_in(self, context: SlashContext) -> bool {
122 match self {
123 SlashCommand::LeaveChat => context.chat && context.group,
124 SlashCommand::Mute => context.chat && !context.notes && !context.muted,
125 SlashCommand::Unmute => context.chat && !context.notes && context.muted,
126 SlashCommand::ScheduleMessage => context.chat && !context.notes,
127 _ => true,
128 }
129 }
130}
131
132fn commands() -> impl Iterator<Item = SlashCommand> {
133 SlashCommand::ALL.iter().copied()
134}
135
136/// The command query while the draft starts with "/" and the caret is still in its first word.
137pub fn active_query(value: &str, cursor: usize) -> Option<(Range<usize>, String)> {
138 if !value.starts_with('/') || cursor == 0 || cursor > value.len() {
139 return None;
140 }
141 let typed = value.get(1..cursor)?;
142 if typed.chars().any(char::is_whitespace) {
143 return None;
144 }
145 let word_end = value
146 .char_indices()
147 .find(|(_, character)| character.is_whitespace())
148 .map_or(value.len(), |(index, _)| index);
149 if cursor < word_end {
150 return None;
151 }
152 Some((0..cursor, typed.to_lowercase()))
153}
154
155pub fn matching(query: &str, context: SlashContext) -> Vec<SlashCommand> {
156 let available: Vec<SlashCommand> = commands()
157 .filter(|command| command.available_in(context))
158 .collect();
159 let starts = available
160 .iter()
161 .filter(|command| command.name().starts_with(query));
162 let contains = available
163 .iter()
164 .filter(|command| !command.name().starts_with(query) && command.name().contains(query));
165 let described = available.iter().filter(|command| {
166 !command.name().contains(query) && command.description().to_lowercase().contains(query)
167 });
168 starts.chain(contains).chain(described).copied().collect()
169}
170
171pub struct SlashPopup {
172 pub range: Range<usize>,
173 pub query: String,
174 pub commands: Vec<SlashCommand>,
175 pub highlighted: usize,
176 scroll: ScrollHandle,
177}
178
179impl SlashPopup {
180 pub fn new(range: Range<usize>, query: String, commands: Vec<SlashCommand>) -> Self {
181 SlashPopup {
182 range,
183 query,
184 commands,
185 highlighted: 0,
186 scroll: ScrollHandle::new(),
187 }
188 }
189
190 pub fn move_highlight(&mut self, delta: isize) {
191 let count = self.commands.len() as isize;
192 if count > 0 {
193 self.highlighted = (self.highlighted as isize + delta).rem_euclid(count) as usize;
194 self.scroll.scroll_to_item(self.highlighted);
195 }
196 }
197
198 pub fn selected(&self) -> Option<SlashCommand> {
199 self.commands.get(self.highlighted).copied()
200 }
201}
202
203fn row(index: usize, command: SlashCommand, selected: bool) -> Stateful<Div> {
204 h_flex()
205 .id(ElementId::Name(format!("slash-row-{index}").into()))
206 .flex_none()
207 .h(px(ROW_HEIGHT))
208 .px(px(8.))
209 .gap(px(8.))
210 .items_center()
211 .rounded(px(6.))
212 .cursor_pointer()
213 .when(selected, |row| row.bg(theme::popup_hover()))
214 .hover(|row| row.bg(theme::popup_hover()))
215 .child(
216 div()
217 .w(px(NAME_WIDTH))
218 .flex_none()
219 .truncate()
220 .text_size(px(13.))
221 .font_weight(FontWeight::SEMIBOLD)
222 .text_color(theme::text())
223 .child(format!("/{}", command.name())),
224 )
225 .child(
226 div()
227 .flex_1()
228 .min_w_0()
229 .truncate()
230 .text_size(px(12.))
231 .text_color(theme::text_muted())
232 .child(command.description()),
233 )
234}
235
236fn label(text: &'static str) -> Div {
237 h_flex()
238 .h(px(HEADER_HEIGHT))
239 .px(px(8.))
240 .items_center()
241 .text_size(px(12.))
242 .font_weight(FontWeight::SEMIBOLD)
243 .text_color(theme::text_muted())
244 .child(text)
245}
246
247pub fn render(
248 popup: &SlashPopup,
249 on_pick: impl Fn(usize, &mut Window, &mut App) + 'static,
250) -> AnyElement {
251 let on_pick = Rc::new(on_pick);
252 let rows = popup.commands.iter().enumerate().map(|(index, command)| {
253 let on_pick = on_pick.clone();
254 row(index, *command, index == popup.highlighted)
255 .on_click(move |_, window, cx| on_pick(index, window, cx))
256 });
257 let visible = popup.commands.len().clamp(1, VISIBLE_ROWS) as f32;
258 v_flex()
259 .id("slash-popup")
260 .absolute()
261 .bottom(relative(1.))
262 .left_0()
263 .mb(px(6.))
264 .w(px(WIDTH))
265 .p(px(4.))
266 .rounded(px(10.))
267 .flyout_surface()
268 .occlude()
269 .child(label(HEADER))
270 .when(popup.commands.is_empty(), |panel| {
271 panel.child(
272 h_flex()
273 .h(px(ROW_HEIGHT))
274 .flex_none()
275 .px(px(8.))
276 .items_center()
277 .text_size(px(13.))
278 .text_color(theme::text_muted())
279 .child(NO_RESULTS),
280 )
281 })
282 .when(!popup.commands.is_empty(), |panel| {
283 panel.child(
284 v_flex()
285 .id("slash-rows")
286 .max_h(px(ROW_HEIGHT * visible))
287 .overflow_y_scrollbar()
288 .track_scroll(&popup.scroll)
289 .children(rows),
290 )
291 })
292 .into_any_element()
293}
294
295impl Composer {
296 fn slash_context(&self, cx: &App) -> SlashContext {
297 let Some(conversation_id) = self.conversation_id.as_deref() else {
298 return SlashContext::default();
299 };
300 let state = self.app.read(cx);
301 let Some(chat) = state
302 .sidebar
303 .chats
304 .iter()
305 .find(|chat| chat.id == conversation_id)
306 else {
307 return SlashContext::default();
308 };
309 SlashContext {
310 chat: true,
311 notes: teams_core::is_notes_chat(conversation_id),
312 group: chat.kind == GROUP_KIND,
313 muted: chat.muted,
314 }
315 }
316
317 pub(super) fn update_slash(&mut self, cx: &mut Context<Self>) {
318 let state = self.input.read(cx);
319 let found = active_query(&state.value(), state.cursor()).filter(|_| self.editing.is_none());
320 let Some((range, query)) = found else {
321 self.slash_popup = None;
322 self.slash_dismissed = false;
323 return;
324 };
325 if self.slash_dismissed {
326 return;
327 }
328 let unchanged = self
329 .slash_popup
330 .as_ref()
331 .is_some_and(|popup| popup.query == query && popup.range == range);
332 if unchanged {
333 return;
334 }
335 let commands = matching(&query, self.slash_context(cx));
336 self.slash_popup = Some(SlashPopup::new(range, query, commands));
337 }
338
339 pub(super) fn accept_slash(&mut self, window: &mut Window, cx: &mut Context<Self>) {
340 let Some(popup) = self.slash_popup.take() else {
341 return;
342 };
343 let Some(command) = popup.selected() else {
344 return;
345 };
346 let typed_end = popup.range.end;
347 self.replace_text(popup.range, "", typed_end, 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())
454 .iter()
455 .map(|command| command.name())
456 .collect();
457 let mut sorted = names.clone();
458 sorted.sort_unstable();
459 assert_eq!(names, sorted);
460 assert!(names.contains(&"mute") && !names.contains(&"unmute"));
461 assert!(!names.contains(&"leavechat"));
462 }
463
464 #[test]
465 fn name_prefix_matches_come_before_description_matches() {
466 let found = matching("b", chat());
467 assert_eq!(found[0].name(), "brb");
468 assert_eq!(found[1].name(), "busy");
469 assert!(found.iter().any(|command| command.name() == "available"));
470 assert_eq!(matching("status", chat())[0].name(), "available");
471 }
472
473 #[test]
474 fn commands_follow_the_conversation() {
475 let group_muted = SlashContext {
476 chat: true,
477 group: true,
478 muted: true,
479 notes: false,
480 };
481 let names: Vec<&str> = matching("", group_muted)
482 .iter()
483 .map(|command| command.name())
484 .collect();
485 assert!(
486 names.contains(&"leavechat") && names.contains(&"unmute") && !names.contains(&"mute")
487 );
488 let notes = SlashContext {
489 chat: true,
490 notes: true,
491 ..SlashContext::default()
492 };
493 let names: Vec<&str> = matching("", notes)
494 .iter()
495 .map(|command| command.name())
496 .collect();
497 assert!(!names.contains(&"mute") && !names.contains(&"schedulemessage"));
498 let channel: Vec<&str> = matching("", SlashContext::default())
499 .iter()
500 .map(|command| command.name())
501 .collect();
502 assert!(channel.contains(&"goto") && !channel.contains(&"leavechat"));
503 }
504}