Skip to main content

gpui_component/
kbd.rs

1use gpui::{
2    Action, FocusHandle, Half, InteractiveElement as _, IntoElement, KeyBinding, KeyContext,
3    KeybindingKeystroke, Keystroke, ParentElement as _, RenderOnce, StyleRefinement, Styled,
4    Window, div, prelude::FluentBuilder as _, relative,
5};
6
7use gpui_base::TestTextExt as _;
8
9use crate::{ActiveTheme, StyledExt};
10
11/// A tag for displaying keyboard keybindings.
12#[derive(IntoElement, Clone, Debug)]
13pub struct Kbd {
14    style: StyleRefinement,
15    stroke: Keystroke,
16    appearance: bool,
17    outline: bool,
18}
19
20impl From<Keystroke> for Kbd {
21    fn from(stroke: Keystroke) -> Self {
22        Self {
23            style: StyleRefinement::default(),
24            stroke,
25            appearance: true,
26            outline: false,
27        }
28    }
29}
30
31impl Kbd {
32    /// Create a new Kbd element with the given [`Keystroke`].
33    pub fn new(stroke: Keystroke) -> Self {
34        Self {
35            style: StyleRefinement::default(),
36            stroke,
37            appearance: true,
38            outline: false,
39        }
40    }
41
42    /// The keystroke this tag shows.
43    pub(crate) fn keystroke(&self) -> &Keystroke {
44        &self.stroke
45    }
46
47    /// Set the appearance of the keybinding, default is `true`.
48    pub fn appearance(mut self, appearance: bool) -> Self {
49        self.appearance = appearance;
50        self
51    }
52
53    /// Use outline style for the keybinding, default is `false`.
54    pub fn outline(mut self) -> Self {
55        self.outline = true;
56        self
57    }
58
59    /// Return the first keybinding for the given action and context.
60    pub fn binding_for_action(
61        action: &dyn Action,
62        context: Option<&str>,
63        window: &Window,
64    ) -> Option<Self> {
65        let key_context = context.and_then(|context| KeyContext::parse(context).ok());
66        let binding = match key_context {
67            Some(context) => {
68                window.highest_precedence_binding_for_action_in_context(action, context)
69            }
70            None => window.highest_precedence_binding_for_action(action),
71        }?;
72
73        Self::from_binding(&binding)
74    }
75
76    /// Return the first keybinding for the given action and focus handle.
77    ///
78    /// GPUI resolves the handle in the previously rendered frame, so this
79    /// finds nothing for a handle whose element is drawn for the first time
80    /// in the current frame.
81    pub fn binding_for_action_in(
82        action: &dyn Action,
83        focus_handle: &FocusHandle,
84        window: &Window,
85    ) -> Option<Self> {
86        let binding = window.highest_precedence_binding_for_action_in(action, focus_handle)?;
87        Self::from_binding(&binding)
88    }
89
90    /// Return the first keybinding for the given action that was registered
91    /// without a key context, so it applies wherever focus is.
92    pub fn global_binding_for_action(action: &dyn Action, window: &Window) -> Option<Self> {
93        let binding = window
94            .highest_precedence_binding_for_action_in_context(action, KeyContext::default())?;
95        Self::from_binding(&binding)
96    }
97
98    fn from_binding(binding: &KeyBinding) -> Option<Self> {
99        binding
100            .keystrokes()
101            .first()
102            .map(Self::from_keybinding_keystroke)
103    }
104
105    /// Show a keystroke as it was bound. On Windows its inner keystroke is
106    /// what the keyboard reports instead: `alt-+` for `alt-shift-=`.
107    fn from_keybinding_keystroke(key: &KeybindingKeystroke) -> Self {
108        Self::new(Keystroke {
109            modifiers: *key.modifiers(),
110            key: key.key().into(),
111            key_char: None,
112        })
113    }
114
115    /// Return the Platform specific keybinding string by KeyStroke
116    ///
117    /// macOS: https://support.apple.com/en-us/HT201236
118    /// Windows: https://support.microsoft.com/en-us/windows/keyboard-shortcuts-in-windows-dcc61a57-8ff0-cffe-9796-cb9706c75eec
119    pub fn format(key: &Keystroke) -> String {
120        #[cfg(target_os = "macos")]
121        const SEPARATOR: &str = "";
122        #[cfg(not(target_os = "macos"))]
123        const SEPARATOR: &str = "+";
124
125        let mut parts = vec![];
126
127        // The key map order in macOS is: ⌃⌥⇧⌘
128        // And in Windows is: Ctrl+Alt+Shift+Win
129
130        if key.modifiers.control {
131            #[cfg(target_os = "macos")]
132            parts.push("⌃");
133
134            #[cfg(not(target_os = "macos"))]
135            parts.push("Ctrl");
136        }
137
138        if key.modifiers.alt {
139            #[cfg(target_os = "macos")]
140            parts.push("⌥");
141
142            #[cfg(not(target_os = "macos"))]
143            parts.push("Alt");
144        }
145
146        if key.modifiers.shift {
147            #[cfg(target_os = "macos")]
148            parts.push("⇧");
149
150            #[cfg(not(target_os = "macos"))]
151            parts.push("Shift");
152        }
153
154        if key.modifiers.platform {
155            #[cfg(target_os = "macos")]
156            parts.push("⌘");
157
158            #[cfg(not(target_os = "macos"))]
159            parts.push("Win");
160        }
161
162        let mut keys = String::new();
163        let key_str = key.key.as_str();
164        match key_str {
165            #[cfg(target_os = "macos")]
166            "ctrl" => keys.push('⌃'),
167            #[cfg(not(target_os = "macos"))]
168            "ctrl" => keys.push_str("Ctrl"),
169            #[cfg(target_os = "macos")]
170            "alt" => keys.push('⌥'),
171            #[cfg(not(target_os = "macos"))]
172            "alt" => keys.push_str("Alt"),
173            #[cfg(target_os = "macos")]
174            "shift" => keys.push('⇧'),
175            #[cfg(not(target_os = "macos"))]
176            "shift" => keys.push_str("Shift"),
177            #[cfg(target_os = "macos")]
178            "cmd" => keys.push('⌘'),
179            #[cfg(not(target_os = "macos"))]
180            "cmd" => keys.push_str("Win"),
181            #[cfg(target_os = "macos")]
182            "space" => keys.push_str("Space"),
183            #[cfg(target_os = "macos")]
184            "backspace" => keys.push('⌫'),
185            #[cfg(not(target_os = "macos"))]
186            "backspace" => keys.push_str("Backspace"),
187            #[cfg(target_os = "macos")]
188            "delete" => keys.push('⌫'),
189            #[cfg(not(target_os = "macos"))]
190            "delete" => keys.push_str("Delete"),
191            #[cfg(target_os = "macos")]
192            "escape" => keys.push('⎋'),
193            #[cfg(not(target_os = "macos"))]
194            "escape" => keys.push_str("Esc"),
195            #[cfg(target_os = "macos")]
196            "enter" => keys.push('⏎'),
197            #[cfg(not(target_os = "macos"))]
198            "enter" => keys.push_str("Enter"),
199            "pagedown" => keys.push_str("Page Down"),
200            "pageup" => keys.push_str("Page Up"),
201            #[cfg(target_os = "macos")]
202            "left" => keys.push('←'),
203            #[cfg(not(target_os = "macos"))]
204            "left" => keys.push_str("Left"),
205            #[cfg(target_os = "macos")]
206            "right" => keys.push('→'),
207            #[cfg(not(target_os = "macos"))]
208            "right" => keys.push_str("Right"),
209            #[cfg(target_os = "macos")]
210            "up" => keys.push('↑'),
211            #[cfg(not(target_os = "macos"))]
212            "up" => keys.push_str("Up"),
213            #[cfg(target_os = "macos")]
214            "down" => keys.push('↓'),
215            #[cfg(not(target_os = "macos"))]
216            "down" => keys.push_str("Down"),
217            _ => {
218                if key_str.len() == 1 {
219                    keys.push_str(&key_str.to_uppercase());
220                } else {
221                    let mut chars = key_str.chars();
222                    if let Some(first_char) = chars.next() {
223                        keys.push_str(&format!(
224                            "{}{}",
225                            first_char.to_uppercase(),
226                            chars.collect::<String>()
227                        ));
228                    } else {
229                        keys.push_str(&key_str);
230                    }
231                }
232            }
233        }
234
235        parts.push(&keys);
236        parts.join(SEPARATOR)
237    }
238}
239
240impl Styled for Kbd {
241    fn style(&mut self) -> &mut StyleRefinement {
242        &mut self.style
243    }
244}
245
246impl RenderOnce for Kbd {
247    fn render(self, _: &mut gpui::Window, cx: &mut gpui::App) -> impl gpui::IntoElement {
248        if !self.appearance {
249            return Self::format(&self.stroke).into_any_element();
250        }
251
252        div()
253            // Lets a test ask whether a given shortcut hint was painted this
254            // frame; a no-op outside test-support builds.
255            .debug_selector(|| format!("kbd:{}", self.stroke.unparse(cx.platform_info().os)))
256            .text_color(cx.theme().muted_foreground)
257            .bg(cx.theme().tokens.muted)
258            .when(self.outline, |this| {
259                this.border_1()
260                    .border_color(cx.theme().border)
261                    .bg(cx.theme().tokens.background)
262            })
263            .py_0p5()
264            .px_1()
265            .min_w_5()
266            .text_center()
267            .rounded(cx.theme().radius.half())
268            .line_height(relative(1.))
269            .text_xs()
270            .whitespace_normal()
271            .flex_shrink_0()
272            .refine_style(&self.style)
273            .child(Self::format(&self.stroke))
274            .test_text(Self::format(&self.stroke))
275            .into_any_element()
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    #[test]
282    fn test_format() {
283        use super::Kbd;
284        use gpui::Keystroke;
285
286        if cfg!(target_os = "macos") {
287            assert_eq!(Kbd::format(&Keystroke::parse("cmd-a").unwrap()), "⌘A");
288            assert_eq!(Kbd::format(&Keystroke::parse("cmd--").unwrap()), "⌘-");
289            assert_eq!(Kbd::format(&Keystroke::parse("cmd-+").unwrap()), "⌘+");
290            assert_eq!(Kbd::format(&Keystroke::parse("cmd-enter").unwrap()), "⌘⏎");
291            assert_eq!(Kbd::format(&Keystroke::parse("cmd-f12").unwrap()), "⌘F12");
292            assert_eq!(
293                Kbd::format(&Keystroke::parse("shift-pagedown").unwrap()),
294                "⇧Page Down"
295            );
296            assert_eq!(
297                Kbd::format(&Keystroke::parse("shift-pageup").unwrap()),
298                "⇧Page Up"
299            );
300            assert_eq!(
301                Kbd::format(&Keystroke::parse("shift-space").unwrap()),
302                "⇧Space"
303            );
304            assert_eq!(Kbd::format(&Keystroke::parse("cmd-ctrl-a").unwrap()), "⌃⌘A");
305            assert_eq!(
306                Kbd::format(&Keystroke::parse("cmd-alt-backspace").unwrap()),
307                "⌥⌘⌫"
308            );
309            assert_eq!(
310                Kbd::format(&Keystroke::parse("shift-delete").unwrap()),
311                "⇧⌫"
312            );
313            assert_eq!(
314                Kbd::format(&Keystroke::parse("cmd-ctrl-shift-a").unwrap()),
315                "⌃⇧⌘A"
316            );
317            assert_eq!(
318                Kbd::format(&Keystroke::parse("cmd-ctrl-shift-alt-a").unwrap()),
319                "⌃⌥⇧⌘A"
320            );
321        } else {
322            assert_eq!(Kbd::format(&Keystroke::parse("a").unwrap()), "A");
323            assert_eq!(Kbd::format(&Keystroke::parse("ctrl-a").unwrap()), "Ctrl+A");
324            assert_eq!(
325                Kbd::format(&Keystroke::parse("shift-space").unwrap()),
326                "Shift+Space"
327            );
328            assert_eq!(
329                Kbd::format(&Keystroke::parse("ctrl-alt-a").unwrap()),
330                "Ctrl+Alt+A"
331            );
332            assert_eq!(
333                Kbd::format(&Keystroke::parse("ctrl-alt-shift-a").unwrap()),
334                "Ctrl+Alt+Shift+A"
335            );
336            assert_eq!(
337                Kbd::format(&Keystroke::parse("ctrl-alt-shift-win-a").unwrap()),
338                "Ctrl+Alt+Shift+Win+A"
339            );
340            assert_eq!(
341                Kbd::format(&Keystroke::parse("ctrl-shift-backspace").unwrap()),
342                "Ctrl+Shift+Backspace"
343            );
344            assert_eq!(
345                Kbd::format(&Keystroke::parse("alt-delete").unwrap()),
346                "Alt+Delete"
347            );
348            assert_eq!(
349                Kbd::format(&Keystroke::parse("alt-tab").unwrap()),
350                "Alt+Tab"
351            );
352        }
353    }
354
355    #[cfg(target_os = "windows")]
356    #[test]
357    fn test_from_keybinding_keystroke() {
358        use super::Kbd;
359        use gpui::{KeybindingKeystroke, Keystroke, Modifiers};
360
361        // What the Windows keyboard mapper makes of `alt-shift-=`.
362        let key = KeybindingKeystroke::new(
363            Keystroke::parse("alt-+").unwrap(),
364            Modifiers {
365                alt: true,
366                shift: true,
367                ..Default::default()
368            },
369            "=".into(),
370        );
371        assert_eq!(
372            Kbd::format(Kbd::from_keybinding_keystroke(&key).keystroke()),
373            "Alt+Shift+="
374        );
375    }
376}