BlueGit

ict rusty-teams

Files

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

shortcuts.rs

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