BlueGit

ict rusty-teams

Files

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

slash.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
slash.rs 16.9 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 self.replace_text(popup.range, "", 0, window, cx);
347 self.run_slash_command(command, window, cx);
348 cx.notify();
349 }
350
351 fn run_slash_command(
352 &mut self,
353 command: SlashCommand,
354 window: &mut Window,
355 cx: &mut Context<Self>,
356 ) {
357 let chat_id = self.conversation_id.clone().unwrap_or_default();
358 match command {
359 SlashCommand::Presence(kind) => self.set_presence(
360 Some(ForcedAvailability {
361 kind,
362 expires_at: None,
363 }),
364 command,
365 cx,
366 ),
367 SlashCommand::ResetPresence => self.set_presence(None, command, cx),
368 SlashCommand::Goto => window.dispatch_action(Box::new(OpenSwitcher), cx),
369 SlashCommand::Settings => window.dispatch_action(Box::new(OpenSettings), cx),
370 SlashCommand::Shortcuts => window.dispatch_action(Box::new(ShowShortcuts), cx),
371 SlashCommand::ScheduleMessage => self.open_schedule_menu(cx),
372 SlashCommand::Mute | SlashCommand::Unmute => {
373 let muted = command == SlashCommand::Mute;
374 self.app
375 .update(cx, |state, cx| state.set_chat_muted(&chat_id, muted, cx));
376 }
377 SlashCommand::LeaveChat => {
378 let Some(chat) = self
379 .app
380 .read(cx)
381 .sidebar
382 .chats
383 .iter()
384 .find(|chat| chat.id == chat_id)
385 .cloned()
386 else {
387 return;
388 };
389 let title = crate::app_state::chat_title(&chat);
390 confirm_leave(&self.app, &chat_id, &title, chat.members.len(), window, cx);
391 }
392 }
393 }
394
395 fn set_presence(
396 &mut self,
397 forced: Option<ForcedAvailability>,
398 command: SlashCommand,
399 cx: &mut Context<Self>,
400 ) {
401 self.app.update(cx, |state, cx| {
402 state.set_own_availability(forced, cx);
403 if let Some(text) = command.confirmation() {
404 state.raise_notice(text.to_owned(), None, cx);
405 }
406 });
407 }
408
409 pub(super) fn render_slash_popup(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
410 let popup = self.slash_popup.as_ref()?;
411 let composer = cx.entity().downgrade();
412 Some(render(popup, move |index, window, cx| {
413 composer
414 .update(cx, |this, cx| {
415 if let Some(popup) = this.slash_popup.as_mut() {
416 popup.highlighted = index;
417 }
418 this.accept_slash(window, cx);
419 })
420 .ok();
421 }))
422 }
423}
424
425#[cfg(test)]
426mod tests {
427 use super::{SlashContext, active_query, matching};
428
429 fn chat() -> SlashContext {
430 SlashContext {
431 chat: true,
432 ..SlashContext::default()
433 }
434 }
435
436 #[test]
437 fn a_slash_at_the_start_opens_the_list() {
438 assert_eq!(active_query("/", 1), Some((0..1, String::new())));
439 assert_eq!(active_query("/Aw", 3), Some((0..3, "aw".to_owned())));
440 }
441
442 #[test]
443 fn a_slash_later_in_the_text_or_after_a_space_does_not_open() {
444 assert_eq!(active_query("hi /away", 8), None);
445 assert_eq!(active_query("/away now", 9), None);
446 assert_eq!(active_query("/away", 0), None);
447 assert_eq!(active_query("/away", 2), None);
448 }
449
450 #[test]
451 fn the_list_is_sorted_by_name_like_teams() {
452 let names: Vec<&str> = matching("", chat())
453 .iter()
454 .map(|command| command.name())
455 .collect();
456 let mut sorted = names.clone();
457 sorted.sort_unstable();
458 assert_eq!(names, sorted);
459 assert!(names.contains(&"mute") && !names.contains(&"unmute"));
460 assert!(!names.contains(&"leavechat"));
461 }
462
463 #[test]
464 fn name_prefix_matches_come_before_description_matches() {
465 let found = matching("b", chat());
466 assert_eq!(found[0].name(), "brb");
467 assert_eq!(found[1].name(), "busy");
468 assert!(found.iter().any(|command| command.name() == "available"));
469 assert_eq!(matching("status", chat())[0].name(), "available");
470 }
471
472 #[test]
473 fn commands_follow_the_conversation() {
474 let group_muted = SlashContext {
475 chat: true,
476 group: true,
477 muted: true,
478 notes: false,
479 };
480 let names: Vec<&str> = matching("", group_muted)
481 .iter()
482 .map(|command| command.name())
483 .collect();
484 assert!(
485 names.contains(&"leavechat") && names.contains(&"unmute") && !names.contains(&"mute")
486 );
487 let notes = SlashContext {
488 chat: true,
489 notes: true,
490 ..SlashContext::default()
491 };
492 let names: Vec<&str> = matching("", notes)
493 .iter()
494 .map(|command| command.name())
495 .collect();
496 assert!(!names.contains(&"mute") && !names.contains(&"schedulemessage"));
497 let channel: Vec<&str> = matching("", SlashContext::default())
498 .iter()
499 .map(|command| command.name())
500 .collect();
501 assert!(channel.contains(&"goto") && !channel.contains(&"leavechat"));
502 }
503}