cmdsys: separate match and handle phases

This commit is contained in:
🪞👃🪞 2024-11-07 02:13:43 +01:00
parent a4925082ca
commit dd72cea679
2 changed files with 130 additions and 126 deletions

View file

@ -25,25 +25,35 @@ pub const fn shift (key: KeyEvent) -> KeyEvent {
KeyEvent { modifiers: key.modifiers.union(KeyModifiers::SHIFT), ..key }
}
pub trait HandleKey<C: Command<Self> + 'static>: Sized {
pub trait HandleKey<C: Command<Self> + Clone + 'static>: Sized {
const HANDLE_KEY_MAP: &'static [(KeyEvent, C)] = &[]; // FIXME: needs to be method
#[inline] fn match_input (from: &TuiInput) -> Option<&'static C> {
#[inline] fn match_input_static (from: &TuiInput) -> Option<C> {
if let TuiEvent::Input(crossterm::event::Event::Key(key)) = from.event() {
return Self::match_key_static(&key)
}
None
}
#[inline] fn match_key_static (key: &KeyEvent) -> Option<&'static C> {
#[inline] fn match_key_static (key: &KeyEvent) -> Option<C> {
for (binding, command) in Self::HANDLE_KEY_MAP.iter() {
if key == binding {
return Some(command);
return Some(command.clone());
}
}
None
}
#[inline] fn match_key (&self, key: &KeyEvent) -> Option<&'static C> {
#[inline] fn match_key (&self, key: &KeyEvent) -> Option<C> {
Self::match_key_static(key)
}
#[inline] fn match_input (&self, input: &TuiInput) -> Option<C> {
Self::match_input_static(input)
}
#[inline] fn handle_input (&mut self, input: &TuiInput) -> Perhaps<C> {
if let Some(command) = self.match_input(input) {
command.run(self)
} else {
Ok(None)
}
}
#[inline] fn handle_key (&mut self, key: &KeyEvent) -> Perhaps<C> {
if let Some(command) = self.match_key(key) {
command.run(self)