thedes_tui/
key_bindings.rs

1use std::collections::HashMap;
2
3use thedes_tui_core::event::KeyEvent;
4
5#[derive(Debug, Clone)]
6pub struct KeyBindingMap<C> {
7    table: HashMap<KeyEvent, C>,
8}
9
10impl<C> Default for KeyBindingMap<C> {
11    fn default() -> Self {
12        Self::new()
13    }
14}
15
16impl<C> KeyBindingMap<C> {
17    pub fn new() -> Self {
18        Self { table: HashMap::new() }
19    }
20
21    pub fn command_for(&self, key: impl Into<KeyEvent>) -> Option<&C> {
22        self.table.get(&key.into())
23    }
24
25    pub fn with(
26        mut self,
27        key: impl Into<KeyEvent>,
28        command: impl Into<C>,
29    ) -> Self {
30        self.bind(key, command);
31        self
32    }
33
34    pub fn bind(
35        &mut self,
36        key: impl Into<KeyEvent>,
37        command: impl Into<C>,
38    ) -> Option<C> {
39        self.table.insert(key.into(), command.into())
40    }
41
42    pub fn unbind(&mut self, key: impl Into<KeyEvent>) -> Option<C> {
43        self.table.remove(&key.into())
44    }
45}