keybinding.rs

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