Skip to main content

tui_world/
keybindings.rs

1use crate::{WidgetId, World};
2use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
3
4/// Helper macro to create `Keys`.
5///
6/// # Example
7/// ```ignore
8/// kb.bind_many(ctx, keys![KeyCode::Up, 'k'], "Up", |world| { });
9/// ```
10#[macro_export]
11macro_rules! keys {
12    ($($key:expr),+ $(,)?) => {
13        $crate::Keys(vec![$($key.into()),+])
14    };
15}
16
17pub type ActionFn = Box<dyn Fn(&mut World) + Send + Sync>;
18pub type AnyKeyFn = Box<dyn Fn(&mut World, &KeyBinding) + Send + Sync>;
19
20struct Binding {
21    key: KeyBinding,
22    id: WidgetId,
23    action: ActionFn,
24    name: &'static str,
25}
26
27struct AnyKeyHandler {
28    id: WidgetId,
29    handler: AnyKeyFn,
30}
31
32/// A registry of keyboard shortcuts mapped to actions for different widgets.
33///
34/// `Keybindings` manages the association between key combinations and their
35/// corresponding actions, scoped by widget ID. It supports:
36/// - Single key bindings via [`bind`](Keybindings::bind)
37/// - Multiple keys for the same action via [`bind_many`](Keybindings::bind_many)
38/// - Catch-all handlers via [`bind_any`](Keybindings::bind_any)
39///
40/// # Example
41/// ```ignore
42/// let mut kb = Keybindings::new();
43/// kb.bind(WidgetId("list"), 'j', "Down", |world| { /* move down */ });
44/// kb.bind_many(WidgetId("list"), keys![KeyCode::Up, 'k'], "Up", |world| { /* move up */ });
45/// ```
46pub struct Keybindings {
47    bindings: Vec<Binding>,
48    any_key_handlers: Vec<AnyKeyHandler>,
49}
50
51impl Default for Keybindings {
52    fn default() -> Self {
53        Self::new()
54    }
55}
56
57impl Keybindings {
58    #[must_use]
59    pub fn new() -> Self {
60        Self {
61            bindings: Vec::new(),
62            any_key_handlers: Vec::new(),
63        }
64    }
65
66    pub fn bind(
67        &mut self,
68        id: WidgetId,
69        key: impl Into<KeyBinding>,
70        name: &'static str,
71        action: impl Fn(&mut World) + Send + Sync + 'static,
72    ) {
73        let key = key.into();
74        self.bindings.retain(|b| !(b.key == key && b.id == id));
75        self.bindings.push(Binding {
76            id,
77            key,
78            action: Box::new(action),
79            name,
80        });
81    }
82
83    /// Binds multiple keys to the same action.
84    pub fn bind_many(
85        &mut self,
86        id: WidgetId,
87        keys: impl Into<Keys>,
88        name: &'static str,
89        action: impl Fn(&mut World) + Send + Sync + Clone + 'static,
90    ) {
91        for key in keys.into().0 {
92            self.bind(id, key, name, action.clone());
93        }
94    }
95
96    /// Binds a handler that fires for any key press on the given widget
97    /// when no specific binding matches.
98    pub fn bind_any(
99        &mut self,
100        id: WidgetId,
101        handler: impl Fn(&mut World, &KeyBinding) + Send + Sync + 'static,
102    ) {
103        self.any_key_handlers.push(AnyKeyHandler {
104            id,
105            handler: Box::new(handler),
106        });
107    }
108
109    pub fn handle(&self, key: &KeyBinding, world: &mut World, ids: &[WidgetId]) -> bool {
110        for binding in &self.bindings {
111            if binding.key != *key {
112                continue;
113            }
114
115            if ids.contains(&binding.id) {
116                (binding.action)(world);
117                return true;
118            }
119        }
120
121        for handler in &self.any_key_handlers {
122            if ids.contains(&handler.id) {
123                (handler.handler)(world, key);
124                return true;
125            }
126        }
127
128        false
129    }
130
131    /// Removes all keybindings for the given context.
132    pub fn unbind(&mut self, id: WidgetId) {
133        self.bindings.retain(|b| b.id != id);
134    }
135
136    /// Returns keybindings grouped by name for the given widget IDs.
137    /// Keys with the same name and widget ID are grouped together.
138    #[must_use]
139    pub fn display_for(&self, ids: &[WidgetId]) -> Vec<DisplayInfo> {
140        use std::collections::HashMap;
141
142        let mut groups: HashMap<(WidgetId, &'static str), Vec<KeyBinding>> = HashMap::new();
143        let mut order: Vec<(WidgetId, &'static str)> = Vec::new();
144
145        for binding in &self.bindings {
146            if ids.contains(&binding.id) {
147                let key = (binding.id, binding.name);
148                if !groups.contains_key(&key) {
149                    order.push(key);
150                }
151                groups.entry(key).or_default().push(binding.key);
152            }
153        }
154
155        order
156            .into_iter()
157            .map(|(id, name)| DisplayInfo {
158                keys: groups.remove(&(id, name)).unwrap_or_default(),
159                id,
160                name,
161            })
162            .collect()
163    }
164
165    /// Returns all keybindings grouped by name.
166    /// Keys with the same name and widget ID are grouped together.
167    #[must_use]
168    pub fn display_all(&self) -> Vec<DisplayInfo> {
169        use std::collections::HashMap;
170
171        let mut groups: HashMap<(WidgetId, &'static str), Vec<KeyBinding>> = HashMap::new();
172        let mut order: Vec<(WidgetId, &'static str)> = Vec::new();
173
174        for binding in &self.bindings {
175            let key = (binding.id, binding.name);
176            if !groups.contains_key(&key) {
177                order.push(key);
178            }
179            groups.entry(key).or_default().push(binding.key);
180        }
181
182        order
183            .into_iter()
184            .map(|(id, name)| DisplayInfo {
185                keys: groups.remove(&(id, name)).unwrap_or_default(),
186                id,
187                name,
188            })
189            .collect()
190    }
191}
192
193/// Represents a keyboard shortcut consisting of a key code and optional modifiers.
194///
195/// `KeyBinding` can be created from:
196/// - A [`KeyCode`] directly (no modifiers)
197/// - A `char` (uppercase letters automatically include Shift modifier)
198/// - A [`KeyEvent`] reference
199///
200/// # Example
201/// ```ignore
202/// // Simple character key
203/// let key: KeyBinding = 'j'.into();
204///
205/// // With modifiers
206/// let ctrl_c = KeyBinding::ctrl('c');
207/// let shift_tab = KeyBinding::new(KeyCode::Tab, KeyModifiers::SHIFT);
208///
209/// // Uppercase automatically includes Shift
210/// let shift_h: KeyBinding = 'H'.into();
211/// ```
212#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
213pub struct KeyBinding {
214    pub code: KeyCode,
215    pub modifiers: KeyModifiers,
216}
217
218impl KeyBinding {
219    #[must_use]
220    pub fn new(code: KeyCode, modifiers: KeyModifiers) -> Self {
221        Self { code, modifiers }
222    }
223
224    #[must_use]
225    pub fn key(code: KeyCode) -> Self {
226        Self::new(code, KeyModifiers::NONE)
227    }
228
229    #[must_use]
230    pub fn ctrl(c: char) -> Self {
231        Self::new(KeyCode::Char(c), KeyModifiers::CONTROL)
232    }
233
234    #[must_use]
235    pub fn alt(c: char) -> Self {
236        Self::new(KeyCode::Char(c), KeyModifiers::ALT)
237    }
238
239    #[must_use]
240    pub fn shift(c: char) -> Self {
241        Self::new(KeyCode::Char(c), KeyModifiers::SHIFT)
242    }
243
244    /// Returns a compact display string using symbols for modifiers.
245    /// - Shift → `⇧`
246    /// - Ctrl → `⌃`
247    /// - Alt → `⌥`
248    ///
249    /// Examples: `⇧Tab`, `⌃c`, `⌥x`, `⇧H`
250    #[must_use]
251    pub fn display_compact(&self) -> String {
252        let mut parts = String::new();
253
254        if self.modifiers.contains(KeyModifiers::CONTROL) {
255            parts.push('⌃');
256        }
257        if self.modifiers.contains(KeyModifiers::ALT) {
258            parts.push('⌥');
259        }
260        if self.modifiers.contains(KeyModifiers::SHIFT) {
261            parts.push('⇧');
262        }
263
264        let key = match self.code {
265            KeyCode::Char(c) => {
266                if c == ' ' {
267                    "Space".to_string()
268                } else {
269                    c.to_ascii_lowercase().to_string()
270                }
271            }
272            KeyCode::Up => "↑".to_string(),
273            KeyCode::Down => "↓".to_string(),
274            KeyCode::Left => "←".to_string(),
275            KeyCode::Right => "→".to_string(),
276            KeyCode::Enter => "⏎".to_string(),
277            KeyCode::Esc => "Esc".to_string(),
278            KeyCode::BackTab | KeyCode::Tab => "Tab".to_string(),
279            KeyCode::Backspace => "⌫".to_string(),
280            KeyCode::Delete => "Del".to_string(),
281            KeyCode::Home => "Home".to_string(),
282            KeyCode::End => "End".to_string(),
283            KeyCode::PageUp => "PgUp".to_string(),
284            KeyCode::PageDown => "PgDn".to_string(),
285            KeyCode::F(n) => format!("F{n}"),
286            _ => format!("{:?}", self.code),
287        };
288
289        parts.push_str(&key);
290        parts
291    }
292
293    #[must_use]
294    pub fn display(&self) -> String {
295        let mut parts = Vec::new();
296
297        if self.modifiers.contains(KeyModifiers::CONTROL) {
298            parts.push("Ctrl");
299        }
300        if self.modifiers.contains(KeyModifiers::ALT) {
301            parts.push("Alt");
302        }
303        if self.modifiers.contains(KeyModifiers::SHIFT) {
304            parts.push("Shift");
305        }
306
307        let key = match self.code {
308            KeyCode::Char(c) => {
309                if c == ' ' {
310                    return "Space".to_string();
311                }
312                c.to_ascii_lowercase().to_string()
313            }
314            KeyCode::Up => "↑".to_string(),
315            KeyCode::Down => "↓".to_string(),
316            KeyCode::Left => "←".to_string(),
317            KeyCode::Right => "→".to_string(),
318            KeyCode::Enter => "Enter".to_string(),
319            KeyCode::Esc => "Esc".to_string(),
320            KeyCode::Tab => "Tab".to_string(),
321            KeyCode::BackTab => "Shift+Tab".to_string(),
322            KeyCode::Backspace => "Backspace".to_string(),
323            KeyCode::Delete => "Delete".to_string(),
324            KeyCode::Home => "Home".to_string(),
325            KeyCode::End => "End".to_string(),
326            KeyCode::PageUp => "PageUp".to_string(),
327            KeyCode::PageDown => "PageDown".to_string(),
328            KeyCode::F(n) => format!("F{n}"),
329            _ => format!("{:?}", self.code),
330        };
331
332        if parts.is_empty() {
333            key
334        } else {
335            parts.push(&key);
336            parts.join("+")
337        }
338    }
339}
340
341impl From<&KeyEvent> for KeyBinding {
342    fn from(event: &KeyEvent) -> Self {
343        Self::new(event.code, event.modifiers)
344    }
345}
346
347impl From<KeyCode> for KeyBinding {
348    fn from(code: KeyCode) -> Self {
349        Self::key(code)
350    }
351}
352
353impl From<char> for KeyBinding {
354    fn from(c: char) -> Self {
355        if c.is_ascii_uppercase() {
356            Self::new(KeyCode::Char(c), KeyModifiers::SHIFT)
357        } else {
358            Self::key(KeyCode::Char(c))
359        }
360    }
361}
362
363/// A collection of keybindings for use with [`Keybindings::bind_many`].
364///
365/// Can be created using the [`keys!`] macro or converted from a `Vec<KeyBinding>`.
366///
367/// # Example
368/// ```ignore
369/// // Using the keys! macro
370/// kb.bind_many(id, keys![KeyCode::Up, 'k'], "Up", |world| { });
371///
372/// // From a vector
373/// let keys: Keys = vec![KeyBinding::key(KeyCode::Up), 'k'.into()].into();
374/// ```
375#[derive(Debug, Clone)]
376pub struct Keys(pub Vec<KeyBinding>);
377
378impl From<Vec<KeyBinding>> for Keys {
379    fn from(keys: Vec<KeyBinding>) -> Self {
380        Self(keys)
381    }
382}
383
384impl std::fmt::Display for KeyBinding {
385    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
386        write!(f, "{}", self.display())
387    }
388}
389
390/// Information about keybindings for display purposes.
391///
392/// Groups multiple keys that perform the same action together,
393/// along with the widget ID and action name for UI presentation.
394#[derive(Debug)]
395pub struct DisplayInfo {
396    pub keys: Vec<KeyBinding>,
397    pub id: WidgetId,
398    pub name: &'static str,
399}
400
401impl DisplayInfo {
402    /// Returns a formatted string of all keys, e.g. "j, k, ↓"
403    ///
404    /// # Example
405    /// ```ignore
406    /// // Returns "Shift+h, j, k"
407    /// info.keys_display()
408    /// ```
409    #[must_use]
410    pub fn keys_display(&self) -> String {
411        self.keys_display_with(KeyBinding::display)
412    }
413
414    /// Returns a compact formatted string of all keys, e.g. "⇧h, ⌃c, ↓"
415    ///
416    /// # Example
417    /// ```ignore
418    /// // Returns "⇧h, j, k"
419    /// info.keys_display_compact()
420    /// ```
421    #[must_use]
422    pub fn keys_display_compact(&self) -> String {
423        self.keys_display_with(KeyBinding::display_compact)
424    }
425
426    /// Returns a formatted string of all keys using a custom formatter.
427    ///
428    /// # Example
429    /// ```ignore
430    /// // Compact: "H, j, k" (Shift+letter shown as uppercase)
431    /// info.keys_display_with(KeyBinding::display_compact)
432    ///
433    /// // Custom formatter: "[↑], [↓]"
434    /// info.keys_display_with(|k| format!("[{}]", k.display()))
435    /// ```
436    #[must_use]
437    pub fn keys_display_with(&self, formatter: impl Fn(&KeyBinding) -> String) -> String {
438        self.keys
439            .iter()
440            .map(formatter)
441            .collect::<Vec<_>>()
442            .join(", ")
443    }
444}