BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / shortcuts.rs

shortcuts.rs

a698af47 History
shortcuts.rs 18.4 KiB Download Raw
1use gpui_kit::component::input::Enter;
2use gpui_kit::*;
3
4use super::actions::{
5 COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLink, InsertTableLine, NewChat, OpenSwitcher,
6 PastePlainText, RemoveTableLine, ReplyToHovered, ScheduleSend, ToggleBold, ToggleCallMute,
7 ToggleCode, ToggleFormatBar, ToggleItalic, ToggleStrike, ToggleSubscript, ToggleSuperscript,
8 ToggleUnderline, SetParagraph, SetHeading1, SetHeading2, SetHeading3, ToggleCodeBlock,
9 ToggleQuote,
10};
11
12const TEXT_FIELD_CONTEXT: &str = "Input";
13const OUTSIDE_COMPOSER_CONTEXT: &str = "!Composer";
14const OUTSIDE_TEXT_FIELD_CONTEXT: &str = "!Input";
15const ALTERNATE_KEYS: &[(&str, &str)] = &[
16 ("Zoom in on shared content", "alt-shift-+"),
17 ("Insert column or row", "ctrl-alt-+"),
18 ("Zoom in", "ctrl-+"),
19 ("Zoom in", "ctrl-shift-="),
20 ("Zoom in", "ctrl-shift-+"),
21 ("Zoom out", "ctrl-_"),
22 ("Zoom out", "ctrl-shift--"),
23];
24
25actions!(
26 teams,
27 [
28 OpenActivity,
29 OpenChatsTab,
30 OpenChannelsTab,
31 OpenSaved,
32 OpenCallsTab,
33 OpenAgents,
34 OpenChatFilter,
35 FindInChat,
36 FilterUnreadChats,
37 FilterNonMeetingChats,
38 FilterMeetingChats,
39 FilterMutedChats,
40 ClearChatFilters,
41 PreviousConversation,
42 NextConversation,
43 JumpToLastReadOrNewest,
44 AcceptCall,
45 DeclineCall,
46 JoinMeetingFromToast,
47 HangUpCall,
48 ToggleCallCamera,
49 ToggleCallShare,
50 ToggleCallHand,
51 OpenLobbyList,
52 StartAudioCall,
53 StartVideoCall,
54 ToggleCallFullscreen,
55 PushToTalk,
56 ZoomShareIn,
57 ZoomShareOut,
58 ZoomShareReset,
59 ShowShortcuts,
60 OpenSettings,
61 ZoomIn,
62 ZoomOut,
63 ZoomReset
64 ]
65);
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum Group {
69 General,
70 Navigation,
71 Composer,
72 Calls,
73}
74
75impl Group {
76 pub const ALL: [Group; 4] = [
77 Group::General,
78 Group::Navigation,
79 Group::Composer,
80 Group::Calls,
81 ];
82
83 pub fn title(self) -> &'static str {
84 match self {
85 Group::General => "General",
86 Group::Navigation => "Navigation",
87 Group::Composer => "Messages and composer",
88 Group::Calls => "Calls",
89 }
90 }
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum Scope {
95 Global,
96 OutsideComposer,
97 GlobalOverTextFields,
98 OutsideTextFields,
99 Composer,
100}
101
102pub struct Shortcut {
103 pub group: Group,
104 pub label: &'static str,
105 pub keys: &'static str,
106 pub mac_keys: Option<&'static str>,
107 pub scope: Scope,
108 bind: fn(&str, Option<&str>) -> KeyBinding,
109}
110
111macro_rules! shortcut {
112 ($group:ident, $scope:ident, $label:expr, $keys:expr, $mac_keys:expr, $action:expr) => {
113 Shortcut {
114 group: Group::$group,
115 label: $label,
116 keys: $keys,
117 mac_keys: $mac_keys,
118 scope: Scope::$scope,
119 bind: |keys, context| KeyBinding::new(keys, $action, context),
120 }
121 };
122}
123
124#[rustfmt::skip]
125pub const SHORTCUTS: &[Shortcut] = &[
126 shortcut!(General, OutsideComposer, "Search and switch chats", "ctrl-k", Some("cmd-k"), OpenSwitcher),
127 shortcut!(General, Global, "New chat", "ctrl-n", Some("cmd-n"), NewChat),
128 shortcut!(General, GlobalOverTextFields, "Keyboard shortcuts", "ctrl-.", Some("cmd-."), ShowShortcuts),
129 shortcut!(General, GlobalOverTextFields, "Settings", "ctrl-,", Some("cmd-,"), OpenSettings),
130 shortcut!(General, OutsideComposer, "Zoom in", "ctrl-=", Some("cmd-="), ZoomIn),
131 shortcut!(General, GlobalOverTextFields, "Zoom out", "ctrl--", Some("cmd--"), ZoomOut),
132 shortcut!(General, GlobalOverTextFields, "Reset zoom level", "ctrl-0", Some("cmd-0"), ZoomReset),
133 shortcut!(Navigation, GlobalOverTextFields, "Open Activity", "ctrl-1", Some("cmd-1"), OpenActivity),
134 shortcut!(Navigation, GlobalOverTextFields, "Show Chats", "ctrl-2", Some("cmd-2"), OpenChatsTab),
135 shortcut!(Navigation, GlobalOverTextFields, "Show Channels", "ctrl-3", Some("cmd-3"), OpenChannelsTab),
136 shortcut!(Navigation, GlobalOverTextFields, "Open Saved", "ctrl-4", Some("cmd-4"), OpenSaved),
137 shortcut!(Navigation, GlobalOverTextFields, "Show Calls", "ctrl-5", Some("cmd-5"), OpenCallsTab),
138 shortcut!(Navigation, GlobalOverTextFields, "Open Agents", "ctrl-6", Some("cmd-6"), OpenAgents),
139 shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),
140 shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),
141 shortcut!(Navigation, GlobalOverTextFields, "Open filter", "ctrl-shift-f", Some("cmd-shift-f"), OpenChatFilter),
142 shortcut!(Navigation, OutsideTextFields, "Filter chat list by unread chats only", "ctrl-alt-u", None, FilterUnreadChats),
143 shortcut!(Navigation, OutsideTextFields, "Filter chat list by chats only", "ctrl-alt-c", None, FilterNonMeetingChats),
144 shortcut!(Navigation, OutsideTextFields, "Filter chat list by meeting chats only", "ctrl-alt-b", None, FilterMeetingChats),
145 shortcut!(Navigation, OutsideTextFields, "Filter chat list by muted chats only", "ctrl-alt-q", None, FilterMutedChats),
146 shortcut!(Navigation, OutsideTextFields, "Remove all filters in the chat list", "ctrl-alt-z", None, ClearChatFilters),
147 shortcut!(Composer, GlobalOverTextFields, "Find in chat", "ctrl-f", Some("cmd-f"), FindInChat),
148 shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
149 shortcut!(Composer, Global, "Jump to last read or newest message", "ctrl-j", Some("cmd-j"), JumpToLastReadOrNewest),
150 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
151 shortcut!(Composer, Composer, "Italic", "ctrl-i", Some("cmd-i"), ToggleItalic),
152 shortcut!(Composer, Composer, "Underline", "ctrl-u", Some("cmd-u"), ToggleUnderline),
153 shortcut!(Composer, Composer, "Expand compose box", "ctrl-shift-x", Some("cmd-shift-x"), ToggleFormatBar),
154 shortcut!(Composer, Composer, "Send (expanded compose box)", "ctrl-enter", Some("cmd-enter"), Enter { secondary: true, shift: false }),
155 shortcut!(Composer, Composer, "Strikethrough", "ctrl-alt-x", None, ToggleStrike),
156 shortcut!(Composer, Composer, "Superscript", "ctrl-shift-=", None, ToggleSuperscript),
157 shortcut!(Composer, Composer, "Subscript", "ctrl-=", None, ToggleSubscript),
158 shortcut!(Composer, Composer, "Code", "ctrl-shift-c", None, ToggleCode),
159 shortcut!(Composer, Composer, "Insert link", "ctrl-k", Some("cmd-k"), EditLink),
160 shortcut!(Composer, Composer, "Paste as plain text", "ctrl-shift-v", Some("cmd-shift-v"), PastePlainText),
161 shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),
162 shortcut!(Composer, Composer, "Insert column or row", "ctrl-alt-=", None, InsertTableLine),
163 shortcut!(Composer, Composer, "Delete column, row, or table", "ctrl-alt--", None, RemoveTableLine),
164 shortcut!(Composer, Composer, "Code block", "ctrl-shift-b", None, ToggleCodeBlock),
165 shortcut!(Composer, Composer, "Quote", "ctrl-alt-4", None, ToggleQuote),
166 shortcut!(Composer, Composer, "Heading 1", "ctrl-alt-1", None, SetHeading1),
167 shortcut!(Composer, Composer, "Heading 2", "ctrl-alt-2", None, SetHeading2),
168 shortcut!(Composer, Composer, "Heading 3", "ctrl-alt-3", None, SetHeading3),
169 shortcut!(Composer, Composer, "Paragraph", "ctrl-alt-p", None, SetParagraph),
170 shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),
171 shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),
172 shortcut!(Calls, GlobalOverTextFields, "Join the meeting from its reminder", "ctrl-shift-j", Some("cmd-shift-j"), JoinMeetingFromToast),
173 shortcut!(Calls, GlobalOverTextFields, "Hang up or leave", "ctrl-shift-h", Some("cmd-shift-h"), HangUpCall),
174 shortcut!(Calls, GlobalOverTextFields, "Mute or unmute", "ctrl-shift-m", None, ToggleCallMute),
175 shortcut!(Calls, GlobalOverTextFields, "Turn camera on or off", "ctrl-shift-o", Some("cmd-shift-o"), ToggleCallCamera),
176 shortcut!(Calls, GlobalOverTextFields, "Open the share menu or stop sharing", "ctrl-shift-e", Some("cmd-shift-e"), ToggleCallShare),
177 shortcut!(Calls, GlobalOverTextFields, "Raise or lower hand", "ctrl-shift-k", Some("cmd-shift-k"), ToggleCallHand),
178 shortcut!(Calls, GlobalOverTextFields, "Open the lobby list", "ctrl-shift-y", Some("cmd-shift-y"), OpenLobbyList),
179 shortcut!(Calls, GlobalOverTextFields, "Start an audio call in this chat", "alt-shift-a", None, StartAudioCall),
180 shortcut!(Calls, GlobalOverTextFields, "Start a video call in this chat", "alt-shift-v", None, StartVideoCall),
181 shortcut!(Calls, GlobalOverTextFields, "Full screen", "f11", None, ToggleCallFullscreen),
182 shortcut!(Calls, GlobalOverTextFields, "Zoom in on shared content", "alt-shift-=", None, ZoomShareIn),
183 shortcut!(Calls, GlobalOverTextFields, "Zoom out on shared content", "alt-shift--", None, ZoomShareOut),
184 shortcut!(Calls, GlobalOverTextFields, "Reset zoom on shared content", "alt-shift-0", None, ZoomShareReset),
185 shortcut!(Calls, OutsideTextFields, "Hold to talk while muted", "ctrl-space", None, PushToTalk),
186];
187
188impl Shortcut {
189 pub fn keys_for_platform(&self) -> &'static str {
190 match self.mac_keys {
191 Some(mac_keys) if cfg!(target_os = "macos") => mac_keys,
192 _ => self.keys,
193 }
194 }
195
196 pub fn display_keys(&self) -> String {
197 display_keys(self.keys_for_platform())
198 }
199
200 fn bindings(&self) -> Vec<KeyBinding> {
201 let contexts: &[Option<&str>] = match self.scope {
202 Scope::Global => &[None],
203 Scope::OutsideComposer => &[Some(OUTSIDE_COMPOSER_CONTEXT)],
204 Scope::GlobalOverTextFields => &[None, Some(TEXT_FIELD_CONTEXT)],
205 Scope::OutsideTextFields => &[Some(OUTSIDE_TEXT_FIELD_CONTEXT)],
206 Scope::Composer => &[Some(COMPOSER_CONTEXT)],
207 };
208 let mut keys = vec![self.keys];
209 keys.extend(
210 ALTERNATE_KEYS
211 .iter()
212 .filter(|(label, _)| *label == self.label)
213 .map(|(_, alternate)| *alternate),
214 );
215 keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));
216 keys.iter()
217 .flat_map(|keys| contexts.iter().map(|context| (self.bind)(keys, *context)))
218 .collect()
219 }
220}
221
222pub fn keys_for_label(label: &str) -> Option<String> {
223 SHORTCUTS
224 .iter()
225 .find(|shortcut| shortcut.label == label)
226 .map(Shortcut::display_keys)
227}
228
229pub fn display_keys(keys: &str) -> String {
230 let (modifiers, key) = match keys.strip_suffix("--") {
231 Some(modifiers) => (modifiers, "-"),
232 None => keys.rsplit_once('-').unwrap_or(("", keys)),
233 };
234 modifiers
235 .split('-')
236 .filter(|part| !part.is_empty())
237 .chain([key])
238 .map(|part| match part {
239 "ctrl" => "Ctrl".to_owned(),
240 "cmd" => "Cmd".to_owned(),
241 "alt" => "Alt".to_owned(),
242 "shift" => "Shift".to_owned(),
243 "up" => "Up".to_owned(),
244 "down" => "Down".to_owned(),
245 "enter" => "Enter".to_owned(),
246 "space" => "Space".to_owned(),
247 "=" => "Plus".to_owned(),
248 "-" => "Minus".to_owned(),
249 other => other.to_uppercase(),
250 })
251 .collect::<Vec<_>>()
252 .join("+")
253}
254
255pub fn bind_scopes(cx: &mut App, scopes: &[Scope]) {
256 cx.bind_keys(
257 SHORTCUTS
258 .iter()
259 .filter(|shortcut| scopes.contains(&shortcut.scope))
260 .flat_map(Shortcut::bindings),
261 );
262}
263
264pub fn shortcuts_in(group: Group) -> impl Iterator<Item = &'static Shortcut> {
265 SHORTCUTS
266 .iter()
267 .filter(move |shortcut| shortcut.group == group)
268}
269
270#[cfg(test)]
271mod tests {
272 use std::collections::HashSet;
273
274 use gpui_kit::{KeyContext, Keystroke, TestAppContext};
275
276 use super::{Group, SHORTCUTS, Scope, Shortcut, display_keys, shortcuts_in};
277 use crate::views::shell::bind_keys;
278
279 fn bound_action(cx: &mut TestAppContext, keys: &str, contexts: &[&str]) -> Option<String> {
280 let stack: Vec<KeyContext> = contexts
281 .iter()
282 .map(|context| KeyContext::parse(context).unwrap())
283 .collect();
284 let keystroke = Keystroke::parse(keys).unwrap();
285 cx.update(|cx| {
286 let keymap = cx.key_bindings();
287 let (bindings, _) = keymap.borrow().bindings_for_input(&[keystroke], &stack);
288 bindings
289 .first()
290 .map(|binding| binding.action().name().to_owned())
291 })
292 }
293
294 fn registered(cx: &mut TestAppContext) {
295 cx.update(gpui_kit::init);
296 cx.update(bind_keys);
297 }
298
299 fn action_name(shortcut: &Shortcut) -> String {
300 shortcut.bindings()[0].action().name().to_owned()
301 }
302
303 #[gpui_kit::test]
304 fn every_listed_shortcut_resolves_to_its_action(cx: &mut TestAppContext) {
305 registered(cx);
306 for shortcut in SHORTCUTS {
307 let contexts: &[&str] = match shortcut.scope {
308 Scope::Global | Scope::OutsideComposer => &["AppShell"],
309 Scope::GlobalOverTextFields | Scope::OutsideTextFields => &["AppShell"],
310 Scope::Composer => &["AppShell", "Composer"],
311 };
312 assert_eq!(
313 bound_action(cx, shortcut.keys, contexts),
314 Some(action_name(shortcut)),
315 "{} ({})",
316 shortcut.label,
317 shortcut.keys
318 );
319 }
320 }
321
322 #[gpui_kit::test]
323 fn global_shortcuts_survive_typing_in_the_composer(cx: &mut TestAppContext) {
324 registered(cx);
325 for shortcut in SHORTCUTS
326 .iter()
327 .filter(|shortcut| shortcut.scope == Scope::GlobalOverTextFields)
328 {
329 assert_eq!(
330 bound_action(cx, shortcut.keys, &["AppShell", "Composer", "Input"]),
331 Some(action_name(shortcut)),
332 "{} ({})",
333 shortcut.label,
334 shortcut.keys
335 );
336 }
337 }
338
339 #[gpui_kit::test]
340 fn push_to_talk_is_not_bound_while_typing_in_a_text_field(cx: &mut TestAppContext) {
341 registered(cx);
342 assert!(bound_action(cx, "ctrl-space", &["AppShell"]).is_some());
343 assert_eq!(
344 bound_action(cx, "ctrl-space", &["AppShell", "Composer", "Input"]),
345 None
346 );
347 }
348
349 #[gpui_kit::test]
350 fn composer_link_shortcut_still_beats_the_switcher_while_typing(cx: &mut TestAppContext) {
351 registered(cx);
352 let typing = ["AppShell", "Composer", "Input"];
353 assert_eq!(
354 bound_action(cx, "ctrl-k", &typing),
355 Some(action_name(
356 SHORTCUTS
357 .iter()
358 .find(|shortcut| shortcut.label == "Insert link")
359 .unwrap()
360 ))
361 );
362 assert_eq!(
363 bound_action(cx, "ctrl-k", &["AppShell"]),
364 Some(action_name(
365 SHORTCUTS
366 .iter()
367 .find(|shortcut| shortcut.label == "Search and switch chats")
368 .unwrap()
369 ))
370 );
371 }
372
373 #[test]
374 fn no_two_shortcuts_share_keys_in_the_same_scope() {
375 let mut seen = HashSet::new();
376 for shortcut in SHORTCUTS {
377 let scope = matches!(shortcut.scope, Scope::Composer);
378 assert!(seen.insert((shortcut.keys, scope)), "{}", shortcut.keys);
379 }
380 }
381
382 #[test]
383 fn every_group_lists_shortcuts_and_keys_read_like_teams() {
384 for group in Group::ALL {
385 assert!(shortcuts_in(group).next().is_some(), "{group:?}");
386 }
387 assert_eq!(display_keys("ctrl-shift-a"), "Ctrl+Shift+A");
388 assert_eq!(display_keys("alt-up"), "Alt+Up");
389 assert_eq!(display_keys("ctrl-."), "Ctrl+.");
390 assert_eq!(display_keys("ctrl-space"), "Ctrl+Space");
391 assert_eq!(display_keys("alt-shift-="), "Alt+Shift+Plus");
392 assert_eq!(display_keys("alt-shift--"), "Alt+Shift+Minus");
393 assert_eq!(display_keys("alt-shift-0"), "Alt+Shift+0");
394 assert_eq!(display_keys("ctrl-alt--"), "Ctrl+Alt+Minus");
395 }
396
397 #[gpui_kit::test]
398 fn zoom_keys_match_teams_and_leave_the_composer_subscript_alone(cx: &mut TestAppContext) {
399 registered(cx);
400 let action_of = |label: &str| {
401 action_name(
402 SHORTCUTS
403 .iter()
404 .find(|shortcut| shortcut.label == label)
405 .unwrap(),
406 )
407 };
408 for (keys, label) in [
409 ("ctrl-=", "Zoom in"),
410 ("ctrl-+", "Zoom in"),
411 ("ctrl-shift-=", "Zoom in"),
412 ("ctrl--", "Zoom out"),
413 ("ctrl-_", "Zoom out"),
414 ("ctrl-0", "Reset zoom level"),
415 ] {
416 assert_eq!(
417 bound_action(cx, keys, &["AppShell"]),
418 Some(action_of(label)),
419 "{keys}"
420 );
421 }
422 let typing = ["AppShell", "Composer", "Input"];
423 assert_eq!(
424 bound_action(cx, "ctrl-=", &typing),
425 Some(action_of("Subscript"))
426 );
427 assert_eq!(
428 bound_action(cx, "ctrl--", &typing),
429 Some(action_of("Zoom out"))
430 );
431 assert_eq!(display_keys("ctrl-="), "Ctrl+Plus");
432 }
433
434 #[gpui_kit::test]
435 fn composer_format_and_table_keys_match_teams(cx: &mut TestAppContext) {
436 registered(cx);
437 let typing = ["AppShell", "Composer", "Input"];
438 let action_of = |label: &str| {
439 action_name(
440 SHORTCUTS
441 .iter()
442 .find(|shortcut| shortcut.label == label)
443 .unwrap(),
444 )
445 };
446 for (keys, label) in [
447 ("ctrl-shift-x", "Expand compose box"),
448 ("ctrl-enter", "Send (expanded compose box)"),
449 ("ctrl-alt-x", "Strikethrough"),
450 ("ctrl-alt-=", "Insert column or row"),
451 ("ctrl-alt-+", "Insert column or row"),
452 ("ctrl-alt--", "Delete column, row, or table"),
453 ("ctrl-shift-b", "Code block"),
454 ("ctrl-alt-4", "Quote"),
455 ("ctrl-alt-1", "Heading 1"),
456 ("ctrl-alt-3", "Heading 3"),
457 ("ctrl-alt-p", "Paragraph"),
458 ] {
459 assert_eq!(
460 bound_action(cx, keys, &typing),
461 Some(action_of(label)),
462 "{keys}"
463 );
464 }
465 }
466}