BlueGit

ict rusty-teams

Files

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

shortcuts.rs

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