BlueGit

ict rusty-teams

Files

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

shortcuts.rs

shortcuts.rs 12.8 KiB Download Raw
1use gpui_kit::*;
2
3use super::actions::{
4 COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLink, NewChat, OpenSwitcher, ReplyToHovered,
5 ScheduleSend, ToggleBold, ToggleCode, ToggleItalic, ToggleStrike, ToggleSubscript,
6 ToggleSuperscript, ToggleUnderline, ToggleCallMute,
7};
8
9const TEXT_FIELD_CONTEXT: &str = "Input";
10const OUTSIDE_COMPOSER_CONTEXT: &str = "!Composer";
11const OUTSIDE_TEXT_FIELD_CONTEXT: &str = "!Input";
12const ALTERNATE_KEYS: &[(&str, &str)] = &[("alt-shift-=", "alt-shift-+")];
13
14actions!(
15 teams,
16 [
17 OpenActivity,
18 OpenChatsTab,
19 OpenChannelsTab,
20 OpenSaved,
21 OpenCallsTab,
22 PreviousConversation,
23 NextConversation,
24 AcceptCall,
25 DeclineCall,
26 JoinMeetingFromToast,
27 HangUpCall,
28 ToggleCallCamera,
29 ToggleCallShare,
30 ToggleCallHand,
31 OpenLobbyList,
32 StartAudioCall,
33 StartVideoCall,
34 ToggleCallFullscreen,
35 PushToTalk,
36 ZoomShareIn,
37 ZoomShareOut,
38 ZoomShareReset,
39 ShowShortcuts
40 ]
41);
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum Group {
45 General,
46 Navigation,
47 Composer,
48 Calls,
49}
50
51impl Group {
52 pub const ALL: [Group; 4] = [
53 Group::General,
54 Group::Navigation,
55 Group::Composer,
56 Group::Calls,
57 ];
58
59 pub fn title(self) -> &'static str {
60 match self {
61 Group::General => "General",
62 Group::Navigation => "Navigation",
63 Group::Composer => "Messages and composer",
64 Group::Calls => "Calls",
65 }
66 }
67}
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum Scope {
71 Global,
72 OutsideComposer,
73 GlobalOverTextFields,
74 OutsideTextFields,
75 Composer,
76}
77
78pub struct Shortcut {
79 pub group: Group,
80 pub label: &'static str,
81 pub keys: &'static str,
82 pub mac_keys: Option<&'static str>,
83 pub scope: Scope,
84 bind: fn(&str, Option<&str>) -> KeyBinding,
85}
86
87macro_rules! shortcut {
88 ($group:ident, $scope:ident, $label:expr, $keys:expr, $mac_keys:expr, $action:expr) => {
89 Shortcut {
90 group: Group::$group,
91 label: $label,
92 keys: $keys,
93 mac_keys: $mac_keys,
94 scope: Scope::$scope,
95 bind: |keys, context| KeyBinding::new(keys, $action, context),
96 }
97 };
98}
99
100#[rustfmt::skip]
101pub const SHORTCUTS: &[Shortcut] = &[
102 shortcut!(General, OutsideComposer, "Search and switch chats", "ctrl-k", Some("cmd-k"), OpenSwitcher),
103 shortcut!(General, Global, "New chat", "ctrl-n", Some("cmd-n"), NewChat),
104 shortcut!(General, GlobalOverTextFields, "Keyboard shortcuts", "ctrl-.", Some("cmd-."), ShowShortcuts),
105 shortcut!(Navigation, GlobalOverTextFields, "Open Activity", "ctrl-1", Some("cmd-1"), OpenActivity),
106 shortcut!(Navigation, GlobalOverTextFields, "Show Chats", "ctrl-2", Some("cmd-2"), OpenChatsTab),
107 shortcut!(Navigation, GlobalOverTextFields, "Show Channels", "ctrl-3", Some("cmd-3"), OpenChannelsTab),
108 shortcut!(Navigation, GlobalOverTextFields, "Open Saved", "ctrl-4", Some("cmd-4"), OpenSaved),
109 shortcut!(Navigation, GlobalOverTextFields, "Show Calls", "ctrl-5", Some("cmd-5"), OpenCallsTab),
110 shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),
111 shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),
112 shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
113 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
114 shortcut!(Composer, Composer, "Italic", "ctrl-i", Some("cmd-i"), ToggleItalic),
115 shortcut!(Composer, Composer, "Underline", "ctrl-u", Some("cmd-u"), ToggleUnderline),
116 shortcut!(Composer, Composer, "Strikethrough", "ctrl-shift-x", None, ToggleStrike),
117 shortcut!(Composer, Composer, "Superscript", "ctrl-shift-=", None, ToggleSuperscript),
118 shortcut!(Composer, Composer, "Subscript", "ctrl-=", None, ToggleSubscript),
119 shortcut!(Composer, Composer, "Code", "ctrl-shift-c", None, ToggleCode),
120 shortcut!(Composer, Composer, "Insert link", "ctrl-k", Some("cmd-k"), EditLink),
121 shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),
122 shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),
123 shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),
124 shortcut!(Calls, GlobalOverTextFields, "Join the meeting from its reminder", "ctrl-shift-j", Some("cmd-shift-j"), JoinMeetingFromToast),
125 shortcut!(Calls, GlobalOverTextFields, "Hang up or leave", "ctrl-shift-h", Some("cmd-shift-h"), HangUpCall),
126 shortcut!(Calls, GlobalOverTextFields, "Mute or unmute", "ctrl-shift-m", None, ToggleCallMute),
127 shortcut!(Calls, GlobalOverTextFields, "Turn camera on or off", "ctrl-shift-o", Some("cmd-shift-o"), ToggleCallCamera),
128 shortcut!(Calls, GlobalOverTextFields, "Open the share menu or stop sharing", "ctrl-shift-e", Some("cmd-shift-e"), ToggleCallShare),
129 shortcut!(Calls, GlobalOverTextFields, "Raise or lower hand", "ctrl-shift-k", Some("cmd-shift-k"), ToggleCallHand),
130 shortcut!(Calls, GlobalOverTextFields, "Open the lobby list", "ctrl-shift-y", Some("cmd-shift-y"), OpenLobbyList),
131 shortcut!(Calls, GlobalOverTextFields, "Start an audio call in this chat", "alt-shift-a", None, StartAudioCall),
132 shortcut!(Calls, GlobalOverTextFields, "Start a video call in this chat", "alt-shift-v", None, StartVideoCall),
133 shortcut!(Calls, GlobalOverTextFields, "Full screen", "f11", None, ToggleCallFullscreen),
134 shortcut!(Calls, GlobalOverTextFields, "Zoom in on shared content", "alt-shift-=", None, ZoomShareIn),
135 shortcut!(Calls, GlobalOverTextFields, "Zoom out on shared content", "alt-shift--", None, ZoomShareOut),
136 shortcut!(Calls, GlobalOverTextFields, "Reset zoom on shared content", "alt-shift-0", None, ZoomShareReset),
137 shortcut!(Calls, OutsideTextFields, "Hold to talk while muted", "ctrl-space", None, PushToTalk),
138];
139
140impl Shortcut {
141 pub fn keys_for_platform(&self) -> &'static str {
142 match self.mac_keys {
143 Some(mac_keys) if cfg!(target_os = "macos") => mac_keys,
144 _ => self.keys,
145 }
146 }
147
148 pub fn display_keys(&self) -> String {
149 display_keys(self.keys_for_platform())
150 }
151
152 fn bindings(&self) -> Vec<KeyBinding> {
153 let contexts: &[Option<&str>] = match self.scope {
154 Scope::Global => &[None],
155 Scope::OutsideComposer => &[Some(OUTSIDE_COMPOSER_CONTEXT)],
156 Scope::GlobalOverTextFields => &[None, Some(TEXT_FIELD_CONTEXT)],
157 Scope::OutsideTextFields => &[Some(OUTSIDE_TEXT_FIELD_CONTEXT)],
158 Scope::Composer => &[Some(COMPOSER_CONTEXT)],
159 };
160 let mut keys = vec![self.keys];
161 keys.extend(ALTERNATE_KEYS.iter().filter(|(primary, _)| *primary == self.keys).map(|(_, alternate)| *alternate));
162 keys.extend(self.mac_keys.filter(|_| cfg!(target_os = "macos")));
163 keys.iter()
164 .flat_map(|keys| contexts.iter().map(|context| (self.bind)(keys, *context)))
165 .collect()
166 }
167}
168
169pub fn keys_for_label(label: &str) -> Option<String> {
170 SHORTCUTS
171 .iter()
172 .find(|shortcut| shortcut.label == label)
173 .map(Shortcut::display_keys)
174}
175
176pub fn display_keys(keys: &str) -> String {
177 let (modifiers, key) = match keys.strip_suffix("--") {
178 Some(modifiers) => (modifiers, "-"),
179 None => keys.rsplit_once('-').unwrap_or(("", keys)),
180 };
181 modifiers
182 .split('-')
183 .filter(|part| !part.is_empty())
184 .chain([key])
185 .map(|part| match part {
186 "ctrl" => "Ctrl".to_owned(),
187 "cmd" => "Cmd".to_owned(),
188 "alt" => "Alt".to_owned(),
189 "shift" => "Shift".to_owned(),
190 "up" => "Up".to_owned(),
191 "down" => "Down".to_owned(),
192 "enter" => "Enter".to_owned(),
193 "space" => "Space".to_owned(),
194 "=" => "Plus".to_owned(),
195 "-" => "Minus".to_owned(),
196 other => other.to_uppercase(),
197 })
198 .collect::<Vec<_>>()
199 .join("+")
200}
201
202pub fn bind_scopes(cx: &mut App, scopes: &[Scope]) {
203 cx.bind_keys(
204 SHORTCUTS
205 .iter()
206 .filter(|shortcut| scopes.contains(&shortcut.scope))
207 .flat_map(Shortcut::bindings),
208 );
209}
210
211pub fn shortcuts_in(group: Group) -> impl Iterator<Item = &'static Shortcut> {
212 SHORTCUTS
213 .iter()
214 .filter(move |shortcut| shortcut.group == group)
215}
216
217#[cfg(test)]
218mod tests {
219 use std::collections::HashSet;
220
221 use gpui_kit::{KeyContext, Keystroke, TestAppContext};
222
223 use super::{Group, SHORTCUTS, Scope, Shortcut, display_keys, shortcuts_in};
224 use crate::views::shell::bind_keys;
225
226 fn bound_action(cx: &mut TestAppContext, keys: &str, contexts: &[&str]) -> Option<String> {
227 let stack: Vec<KeyContext> = contexts
228 .iter()
229 .map(|context| KeyContext::parse(context).unwrap())
230 .collect();
231 let keystroke = Keystroke::parse(keys).unwrap();
232 cx.update(|cx| {
233 let keymap = cx.key_bindings();
234 let (bindings, _) = keymap.borrow().bindings_for_input(&[keystroke], &stack);
235 bindings
236 .first()
237 .map(|binding| binding.action().name().to_owned())
238 })
239 }
240
241 fn registered(cx: &mut TestAppContext) {
242 cx.update(gpui_kit::init);
243 cx.update(bind_keys);
244 }
245
246 fn action_name(shortcut: &Shortcut) -> String {
247 shortcut.bindings()[0].action().name().to_owned()
248 }
249
250 #[gpui_kit::test]
251 fn every_listed_shortcut_resolves_to_its_action(cx: &mut TestAppContext) {
252 registered(cx);
253 for shortcut in SHORTCUTS {
254 let contexts: &[&str] = match shortcut.scope {
255 Scope::Global | Scope::OutsideComposer => &["AppShell"],
256 Scope::GlobalOverTextFields | Scope::OutsideTextFields => &["AppShell"],
257 Scope::Composer => &["AppShell", "Composer"],
258 };
259 assert_eq!(
260 bound_action(cx, shortcut.keys, contexts),
261 Some(action_name(shortcut)),
262 "{} ({})",
263 shortcut.label,
264 shortcut.keys
265 );
266 }
267 }
268
269 #[gpui_kit::test]
270 fn global_shortcuts_survive_typing_in_the_composer(cx: &mut TestAppContext) {
271 registered(cx);
272 for shortcut in SHORTCUTS
273 .iter()
274 .filter(|shortcut| shortcut.scope == Scope::GlobalOverTextFields)
275 {
276 assert_eq!(
277 bound_action(cx, shortcut.keys, &["AppShell", "Composer", "Input"]),
278 Some(action_name(shortcut)),
279 "{} ({})",
280 shortcut.label,
281 shortcut.keys
282 );
283 }
284 }
285
286 #[gpui_kit::test]
287 fn push_to_talk_is_not_bound_while_typing_in_a_text_field(cx: &mut TestAppContext) {
288 registered(cx);
289 assert!(bound_action(cx, "ctrl-space", &["AppShell"]).is_some());
290 assert_eq!(
291 bound_action(cx, "ctrl-space", &["AppShell", "Composer", "Input"]),
292 None
293 );
294 }
295
296 #[gpui_kit::test]
297 fn composer_link_shortcut_still_beats_the_switcher_while_typing(cx: &mut TestAppContext) {
298 registered(cx);
299 let typing = ["AppShell", "Composer", "Input"];
300 assert_eq!(
301 bound_action(cx, "ctrl-k", &typing),
302 Some(action_name(
303 SHORTCUTS
304 .iter()
305 .find(|shortcut| shortcut.label == "Insert link")
306 .unwrap()
307 ))
308 );
309 assert_eq!(
310 bound_action(cx, "ctrl-k", &["AppShell"]),
311 Some(action_name(
312 SHORTCUTS
313 .iter()
314 .find(|shortcut| shortcut.label == "Search and switch chats")
315 .unwrap()
316 ))
317 );
318 }
319
320 #[test]
321 fn no_two_shortcuts_share_keys_in_the_same_scope() {
322 let mut seen = HashSet::new();
323 for shortcut in SHORTCUTS {
324 let scope = matches!(shortcut.scope, Scope::Composer);
325 assert!(seen.insert((shortcut.keys, scope)), "{}", shortcut.keys);
326 }
327 }
328
329 #[test]
330 fn every_group_lists_shortcuts_and_keys_read_like_teams() {
331 for group in Group::ALL {
332 assert!(shortcuts_in(group).next().is_some(), "{group:?}");
333 }
334 assert_eq!(display_keys("ctrl-shift-a"), "Ctrl+Shift+A");
335 assert_eq!(display_keys("alt-up"), "Alt+Up");
336 assert_eq!(display_keys("ctrl-."), "Ctrl+.");
337 assert_eq!(display_keys("ctrl-space"), "Ctrl+Space");
338 assert_eq!(display_keys("alt-shift-="), "Alt+Shift+Plus");
339 assert_eq!(display_keys("alt-shift--"), "Alt+Shift+Minus");
340 assert_eq!(display_keys("alt-shift-0"), "Alt+Shift+0");
341 }
342}