BlueGit

ict rusty-teams

Files

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

slash.rs

feat(parity): chat header like Teams
metis Daniel Däschle · pushed by metis · 3 weeks ago
3b37290b History
slash.rs 16.8 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::shortcuts::{OpenSettings, ShowShortcuts};
14use crate::views::chat_menu::confirm_leave;
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) => {
90 "Set your status to do not disturb"
91 }
92 SlashCommand::Presence(ForcedKind::Offline) => "Set your status to offline",
93 SlashCommand::ResetPresence => "Reset your presence status",
94 SlashCommand::Goto => "Go right to a chat or channel",
95 SlashCommand::LeaveChat => "Leave the chat",
96 SlashCommand::Mute => "Mute the chat",
97 SlashCommand::Unmute => "Unmute the chat",
98 SlashCommand::ScheduleMessage => "Schedule a message",
99 SlashCommand::Settings => "Open Settings",
100 SlashCommand::Shortcuts => "Open keyboard shortcuts",
101 }
102 }
103
104 pub fn confirmation(self) -> Option<&'static str> {
105 match self {
106 SlashCommand::Presence(ForcedKind::Available) => {
107 Some("Your status is set to available.")
108 }
109 SlashCommand::Presence(ForcedKind::Away) => Some("Your status is set to away."),
110 SlashCommand::Presence(ForcedKind::BeRightBack) => {
111 Some("Your status is set to be right back.")
112 }
113 SlashCommand::Presence(ForcedKind::Busy) => Some("Your status is set to busy."),
114 SlashCommand::Presence(ForcedKind::DoNotDisturb) => {
115 Some("Your status is set to do not disturb.")
116 }
117 SlashCommand::Presence(ForcedKind::Offline) => Some("Your status is set to offline."),
118 SlashCommand::ResetPresence => Some("Your presence status is reset."),
119 _ => None,
120 }
121 }
122
123 fn available_in(self, context: SlashContext) -> bool {
124 match self {
125 SlashCommand::LeaveChat => context.chat && context.group,
126 SlashCommand::Mute => context.chat && !context.notes && !context.muted,
127 SlashCommand::Unmute => context.chat && !context.notes && context.muted,
128 SlashCommand::ScheduleMessage => context.chat && !context.notes,
129 _ => true,
130 }
131 }
132}
133
134fn commands() -> impl Iterator<Item = SlashCommand> {
135 SlashCommand::ALL.iter().copied()
136}
137
138/// The command query while the draft starts with "/" and the caret is still in its first word.
139pub fn active_query(value: &str, cursor: usize) -> Option<(Range<usize>, String)> {
140 if !value.starts_with('/') || cursor == 0 || cursor > value.len() {
141 return None;
142 }
143 let typed = value.get(1..cursor)?;
144 if typed.chars().any(char::is_whitespace) {
145 return None;
146 }
147 let word_end = value
148 .char_indices()
149 .find(|(_, character)| character.is_whitespace())
150 .map_or(value.len(), |(index, _)| index);
151 if cursor < word_end {
152 return None;
153 }
154 Some((0..cursor, typed.to_lowercase()))
155}
156
157pub fn matching(query: &str, context: SlashContext) -> Vec<SlashCommand> {
158 let available: Vec<SlashCommand> = commands()
159 .filter(|command| command.available_in(context))
160 .collect();
161 let starts = available
162 .iter()
163 .filter(|command| command.name().starts_with(query));
164 let contains = available
165 .iter()
166 .filter(|command| !command.name().starts_with(query) && command.name().contains(query));
167 let described = available.iter().filter(|command| {
168 !command.name().contains(query) && command.description().to_lowercase().contains(query)
169 });
170 starts.chain(contains).chain(described).copied().collect()
171}
172
173pub struct SlashPopup {
174 pub range: Range<usize>,
175 pub query: String,
176 pub commands: Vec<SlashCommand>,
177 pub highlighted: usize,
178 scroll: ScrollHandle,
179}
180
181impl SlashPopup {
182 pub fn new(range: Range<usize>, query: String, commands: Vec<SlashCommand>) -> Self {
183 SlashPopup {
184 range,
185 query,
186 commands,
187 highlighted: 0,
188 scroll: ScrollHandle::new(),
189 }
190 }
191
192 pub fn move_highlight(&mut self, delta: isize) {
193 let count = self.commands.len() as isize;
194 if count > 0 {
195 self.highlighted = (self.highlighted as isize + delta).rem_euclid(count) as usize;
196 self.scroll.scroll_to_item(self.highlighted);
197 }
198 }
199
200 pub fn selected(&self) -> Option<SlashCommand> {
201 self.commands.get(self.highlighted).copied()
202 }
203}
204
205fn row(index: usize, command: SlashCommand, selected: bool) -> Stateful<Div> {
206 h_flex()
207 .id(ElementId::Name(format!("slash-row-{index}").into()))
208 .flex_none()
209 .h(px(ROW_HEIGHT))
210 .px(px(8.))
211 .gap(px(8.))
212 .items_center()
213 .rounded(px(6.))
214 .cursor_pointer()
215 .when(selected, |row| row.bg(theme::popup_hover()))
216 .hover(|row| row.bg(theme::popup_hover()))
217 .child(
218 div()
219 .w(px(NAME_WIDTH))
220 .flex_none()
221 .truncate()
222 .text_size(px(13.))
223 .font_weight(FontWeight::SEMIBOLD)
224 .text_color(theme::text())
225 .child(format!("/{}", command.name())),
226 )
227 .child(
228 div()
229 .flex_1()
230 .min_w_0()
231 .truncate()
232 .text_size(px(12.))
233 .text_color(theme::text_muted())
234 .child(command.description()),
235 )
236}
237
238fn label(text: &'static str) -> Div {
239 h_flex()
240 .h(px(HEADER_HEIGHT))
241 .px(px(8.))
242 .items_center()
243 .text_size(px(12.))
244 .font_weight(FontWeight::SEMIBOLD)
245 .text_color(theme::text_muted())
246 .child(text)
247}
248
249pub fn render(
250 popup: &SlashPopup,
251 on_pick: impl Fn(usize, &mut Window, &mut App) + 'static,
252) -> AnyElement {
253 let on_pick = Rc::new(on_pick);
254 let rows = popup.commands.iter().enumerate().map(|(index, command)| {
255 let on_pick = on_pick.clone();
256 row(index, *command, index == popup.highlighted)
257 .on_click(move |_, window, cx| on_pick(index, window, cx))
258 });
259 let visible = popup.commands.len().clamp(1, VISIBLE_ROWS) as f32;
260 v_flex()
261 .id("slash-popup")
262 .absolute()
263 .bottom(relative(1.))
264 .left_0()
265 .mb(px(6.))
266 .w(px(WIDTH))
267 .p(px(4.))
268 .rounded(px(10.))
269 .flyout_surface()
270 .occlude()
271 .child(label(HEADER))
272 .when(popup.commands.is_empty(), |panel| {
273 panel.child(
274 h_flex()
275 .h(px(ROW_HEIGHT))
276 .flex_none()
277 .px(px(8.))
278 .items_center()
279 .text_size(px(13.))
280 .text_color(theme::text_muted())
281 .child(NO_RESULTS),
282 )
283 })
284 .when(!popup.commands.is_empty(), |panel| {
285 panel.child(
286 v_flex()
287 .id("slash-rows")
288 .max_h(px(ROW_HEIGHT * visible))
289 .overflow_y_scrollbar()
290 .track_scroll(&popup.scroll)
291 .children(rows),
292 )
293 })
294 .into_any_element()
295}
296
297impl Composer {
298 fn slash_context(&self, cx: &App) -> SlashContext {
299 let Some(conversation_id) = self.conversation_id.as_deref() else {
300 return SlashContext::default();
301 };
302 let state = self.app.read(cx);
303 let Some(chat) = state
304 .sidebar
305 .chats
306 .iter()
307 .find(|chat| chat.id == conversation_id)
308 else {
309 return SlashContext::default();
310 };
311 SlashContext {
312 chat: true,
313 notes: teams_core::is_notes_chat(conversation_id),
314 group: chat.kind == GROUP_KIND,
315 muted: chat.muted,
316 }
317 }
318
319 pub(super) fn update_slash(&mut self, cx: &mut Context<Self>) {
320 let state = self.input.read(cx);
321 let found = active_query(&state.value(), state.cursor()).filter(|_| self.editing.is_none());
322 let Some((range, query)) = found else {
323 self.slash_popup = None;
324 self.slash_dismissed = false;
325 return;
326 };
327 if self.slash_dismissed {
328 return;
329 }
330 let unchanged = self
331 .slash_popup
332 .as_ref()
333 .is_some_and(|popup| popup.query == query && popup.range == range);
334 if unchanged {
335 return;
336 }
337 let commands = matching(&query, self.slash_context(cx));
338 self.slash_popup = Some(SlashPopup::new(range, query, commands));
339 }
340
341 pub(super) fn accept_slash(&mut self, window: &mut Window, cx: &mut Context<Self>) {
342 let Some(popup) = self.slash_popup.take() else {
343 return;
344 };
345 let Some(command) = popup.selected() else {
346 return;
347 };
348 self.replace_text(popup.range, "", 0, window, cx);
349 self.run_slash_command(command, window, cx);
350 cx.notify();
351 }
352
353 fn run_slash_command(
354 &mut self,
355 command: SlashCommand,
356 window: &mut Window,
357 cx: &mut Context<Self>,
358 ) {
359 let chat_id = self.conversation_id.clone().unwrap_or_default();
360 match command {
361 SlashCommand::Presence(kind) => self.set_presence(
362 Some(ForcedAvailability {
363 kind,
364 expires_at: None,
365 }),
366 command,
367 cx,
368 ),
369 SlashCommand::ResetPresence => self.set_presence(None, command, cx),
370 SlashCommand::Goto => window.dispatch_action(Box::new(OpenSwitcher), cx),
371 SlashCommand::Settings => window.dispatch_action(Box::new(OpenSettings), cx),
372 SlashCommand::Shortcuts => window.dispatch_action(Box::new(ShowShortcuts), cx),
373 SlashCommand::ScheduleMessage => self.open_schedule_menu(cx),
374 SlashCommand::Mute | SlashCommand::Unmute => {
375 let muted = command == SlashCommand::Mute;
376 self.app
377 .update(cx, |state, cx| state.set_chat_muted(&chat_id, muted, cx));
378 }
379 SlashCommand::LeaveChat => {
380 let Some(chat) = self
381 .app
382 .read(cx)
383 .sidebar
384 .chats
385 .iter()
386 .find(|chat| chat.id == chat_id)
387 .cloned()
388 else {
389 return;
390 };
391 let title = crate::app_state::chat_title(&chat);
392 confirm_leave(&self.app, &chat_id, &title, chat.members.len(), window, cx);
393 }
394 }
395 }
396
397 fn set_presence(
398 &mut self,
399 forced: Option<ForcedAvailability>,
400 command: SlashCommand,
401 cx: &mut Context<Self>,
402 ) {
403 self.app.update(cx, |state, cx| {
404 state.set_own_availability(forced, cx);
405 if let Some(text) = command.confirmation() {
406 state.raise_notice(text.to_owned(), None, cx);
407 }
408 });
409 }
410
411 pub(super) fn render_slash_popup(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
412 let popup = self.slash_popup.as_ref()?;
413 let composer = cx.entity().downgrade();
414 Some(render(popup, move |index, window, cx| {
415 composer
416 .update(cx, |this, cx| {
417 if let Some(popup) = this.slash_popup.as_mut() {
418 popup.highlighted = index;
419 }
420 this.accept_slash(window, cx);
421 })
422 .ok();
423 }))
424 }
425}
426
427#[cfg(test)]
428mod tests {
429 use super::{SlashContext, active_query, matching};
430
431 fn chat() -> SlashContext {
432 SlashContext {
433 chat: true,
434 ..SlashContext::default()
435 }
436 }
437
438 #[test]
439 fn a_slash_at_the_start_opens_the_list() {
440 assert_eq!(active_query("/", 1), Some((0..1, String::new())));
441 assert_eq!(active_query("/Aw", 3), Some((0..3, "aw".to_owned())));
442 }
443
444 #[test]
445 fn a_slash_later_in_the_text_or_after_a_space_does_not_open() {
446 assert_eq!(active_query("hi /away", 8), None);
447 assert_eq!(active_query("/away now", 9), None);
448 assert_eq!(active_query("/away", 0), None);
449 assert_eq!(active_query("/away", 2), None);
450 }
451
452 #[test]
453 fn the_list_is_sorted_by_name_like_teams() {
454 let names: Vec<&str> = matching("", chat()).iter().map(|command| command.name()).collect();
455 let mut sorted = names.clone();
456 sorted.sort_unstable();
457 assert_eq!(names, sorted);
458 assert!(names.contains(&"mute") && !names.contains(&"unmute"));
459 assert!(!names.contains(&"leavechat"));
460 }
461
462 #[test]
463 fn name_prefix_matches_come_before_description_matches() {
464 let found = matching("b", chat());
465 assert_eq!(found[0].name(), "brb");
466 assert_eq!(found[1].name(), "busy");
467 assert!(found.iter().any(|command| command.name() == "available"));
468 assert_eq!(matching("status", chat())[0].name(), "available");
469 }
470
471 #[test]
472 fn commands_follow_the_conversation() {
473 let group_muted = SlashContext {
474 chat: true,
475 group: true,
476 muted: true,
477 notes: false,
478 };
479 let names: Vec<&str> = matching("", group_muted).iter().map(|command| command.name()).collect();
480 assert!(names.contains(&"leavechat") && names.contains(&"unmute") && !names.contains(&"mute"));
481 let notes = SlashContext {
482 chat: true,
483 notes: true,
484 ..SlashContext::default()
485 };
486 let names: Vec<&str> = matching("", notes).iter().map(|command| command.name()).collect();
487 assert!(!names.contains(&"mute") && !names.contains(&"schedulemessage"));
488 let channel: Vec<&str> = matching("", SlashContext::default())
489 .iter()
490 .map(|command| command.name())
491 .collect();
492 assert!(channel.contains(&"goto") && !channel.contains(&"leavechat"));
493 }
494}