1use crate::prelude::*;
2use gpui::{Action, Div, IntoElement};
3
4#[derive(IntoElement, Clone)]
5pub struct KeyBinding {
6 /// A keybinding consists of a key and a set of modifier keys.
7 /// More then one keybinding produces a chord.
8 ///
9 /// This should always contain at least one element.
10 key_binding: gpui::KeyBinding,
11}
12
13impl RenderOnce for KeyBinding {
14 type Rendered = Div;
15
16 fn render(self, cx: &mut WindowContext) -> Self::Rendered {
17 div()
18 .flex()
19 .gap_2()
20 .children(self.key_binding.keystrokes().iter().map(|keystroke| {
21 div()
22 .flex()
23 .gap_1()
24 .when(keystroke.modifiers.function, |el| el.child(Key::new("fn")))
25 .when(keystroke.modifiers.control, |el| el.child(Key::new("^")))
26 .when(keystroke.modifiers.alt, |el| el.child(Key::new("⌥")))
27 .when(keystroke.modifiers.command, |el| el.child(Key::new("⌘")))
28 .when(keystroke.modifiers.shift, |el| el.child(Key::new("⇧")))
29 .child(Key::new(keystroke.key.clone()))
30 }))
31 }
32}
33
34impl KeyBinding {
35 pub fn for_action(action: &dyn Action, cx: &mut WindowContext) -> Option<Self> {
36 // todo! this last is arbitrary, we want to prefer users key bindings over defaults,
37 // and vim over normal (in vim mode), etc.
38 let key_binding = cx.bindings_for_action(action).last().cloned()?;
39 Some(Self::new(key_binding))
40 }
41
42 pub fn new(key_binding: gpui::KeyBinding) -> Self {
43 Self { key_binding }
44 }
45}
46
47#[derive(IntoElement)]
48pub struct Key {
49 key: SharedString,
50}
51
52impl RenderOnce for Key {
53 type Rendered = Div;
54
55 fn render(self, cx: &mut WindowContext) -> Self::Rendered {
56 div()
57 .px_2()
58 .py_0()
59 .rounded_md()
60 .text_ui_sm()
61 .text_color(cx.theme().colors().text)
62 .bg(cx.theme().colors().element_background)
63 .child(self.key.clone())
64 }
65}
66
67impl Key {
68 pub fn new(key: impl Into<SharedString>) -> Self {
69 Self { key: key.into() }
70 }
71}