keybinding.rs

  1use crate::prelude::*;
  2use gpui::{Action, Div, RenderOnce};
  3use strum::EnumIter;
  4
  5#[derive(RenderOnce, Clone)]
  6pub struct KeyBinding {
  7    /// A keybinding consists of a key and a set of modifier keys.
  8    /// More then one keybinding produces a chord.
  9    ///
 10    /// This should always contain at least one element.
 11    key_binding: gpui::KeyBinding,
 12}
 13
 14impl<V: 'static> Component<V> for KeyBinding {
 15    type Rendered = Div<V>;
 16
 17    fn render(self, view: &mut V, cx: &mut ViewContext<V>) -> Self::Rendered {
 18        div()
 19            .flex()
 20            .gap_2()
 21            .children(self.key_binding.keystrokes().iter().map(|keystroke| {
 22                div()
 23                    .flex()
 24                    .gap_1()
 25                    .when(keystroke.modifiers.function, |el| el.child(Key::new("fn")))
 26                    .when(keystroke.modifiers.control, |el| el.child(Key::new("^")))
 27                    .when(keystroke.modifiers.alt, |el| el.child(Key::new("")))
 28                    .when(keystroke.modifiers.command, |el| el.child(Key::new("")))
 29                    .when(keystroke.modifiers.shift, |el| el.child(Key::new("")))
 30                    .child(Key::new(keystroke.key.clone()))
 31            }))
 32    }
 33}
 34
 35impl KeyBinding {
 36    pub fn for_action(action: &dyn Action, cx: &mut WindowContext) -> Option<Self> {
 37        // todo! this last is arbitrary, we want to prefer users key bindings over defaults,
 38        // and vim over normal (in vim mode), etc.
 39        let key_binding = cx.bindings_for_action(action).last().cloned()?;
 40        Some(Self::new(key_binding))
 41    }
 42
 43    pub fn new(key_binding: gpui::KeyBinding) -> Self {
 44        Self { key_binding }
 45    }
 46}
 47
 48#[derive(RenderOnce)]
 49pub struct Key {
 50    key: SharedString,
 51}
 52
 53impl<V: 'static> Component<V> for Key {
 54    type Rendered = Div<V>;
 55
 56    fn render(self, view: &mut V, cx: &mut ViewContext<V>) -> Self::Rendered {
 57        let _view: &mut V = view;
 58        div()
 59            .px_2()
 60            .py_0()
 61            .rounded_md()
 62            .text_ui_sm()
 63            .text_color(cx.theme().colors().text)
 64            .bg(cx.theme().colors().element_background)
 65            .child(self.key.clone())
 66    }
 67}
 68
 69impl Key {
 70    pub fn new(key: impl Into<SharedString>) -> Self {
 71        Self { key: key.into() }
 72    }
 73}
 74
 75// NOTE: The order the modifier keys appear in this enum impacts the order in
 76// which they are rendered in the UI.
 77#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, EnumIter)]
 78pub enum ModifierKey {
 79    Control,
 80    Alt,
 81    Command,
 82    Shift,
 83}
 84
 85#[cfg(feature = "stories")]
 86pub use stories::*;
 87
 88#[cfg(feature = "stories")]
 89mod stories {
 90    use super::*;
 91    use crate::Story;
 92    use gpui::{actions, Div, Render};
 93    use itertools::Itertools;
 94
 95    pub struct KeybindingStory;
 96
 97    actions!(NoAction);
 98
 99    pub fn binding(key: &str) -> gpui::KeyBinding {
100        gpui::KeyBinding::new(key, NoAction {}, None)
101    }
102
103    impl Render<Self> for KeybindingStory {
104        type Element = Div<Self>;
105
106        fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
107            let all_modifier_permutations =
108                ["ctrl", "alt", "cmd", "shift"].into_iter().permutations(2);
109
110            Story::container(cx)
111                .child(Story::title_for::<_, KeyBinding>(cx))
112                .child(Story::label(cx, "Single Key"))
113                .child(KeyBinding::new(binding("Z")))
114                .child(Story::label(cx, "Single Key with Modifier"))
115                .child(
116                    div()
117                        .flex()
118                        .gap_3()
119                        .child(KeyBinding::new(binding("ctrl-c")))
120                        .child(KeyBinding::new(binding("alt-c")))
121                        .child(KeyBinding::new(binding("cmd-c")))
122                        .child(KeyBinding::new(binding("shift-c"))),
123                )
124                .child(Story::label(cx, "Single Key with Modifier (Permuted)"))
125                .child(
126                    div().flex().flex_col().children(
127                        all_modifier_permutations
128                            .chunks(4)
129                            .into_iter()
130                            .map(|chunk| {
131                                div()
132                                    .flex()
133                                    .gap_4()
134                                    .py_3()
135                                    .children(chunk.map(|permutation| {
136                                        KeyBinding::new(binding(&*(permutation.join("-") + "-x")))
137                                    }))
138                            }),
139                    ),
140                )
141                .child(Story::label(cx, "Single Key with All Modifiers"))
142                .child(KeyBinding::new(binding("ctrl-alt-cmd-shift-z")))
143                .child(Story::label(cx, "Chord"))
144                .child(KeyBinding::new(binding("a z")))
145                .child(Story::label(cx, "Chord with Modifier"))
146                .child(KeyBinding::new(binding("ctrl-a shift-z")))
147                .child(KeyBinding::new(binding("fn-s")))
148        }
149    }
150}