cmdsys: separate match_key_static

This commit is contained in:
🪞👃🪞 2024-11-07 01:18:53 +01:00
parent 1f375219db
commit a4925082ca
2 changed files with 66 additions and 30 deletions

View file

@ -1,5 +1,9 @@
use crate::*;
pub trait Command<T>: Sized {
fn run (&self, state: &mut T) -> Perhaps<Self>;
}
pub const fn key (code: KeyCode) -> KeyEvent {
KeyEvent {
code,
@ -21,13 +25,15 @@ pub const fn shift (key: KeyEvent) -> KeyEvent {
KeyEvent { modifiers: key.modifiers.union(KeyModifiers::SHIFT), ..key }
}
pub trait Command<T>: Sized {
fn run (&self, state: &mut T) -> Perhaps<Self>;
}
pub trait HandleKey<C: Command<Self> + 'static>: Sized {
const HANDLE_KEY_MAP: &'static [(KeyEvent, C)]; // FIXME: needs to be method
fn match_key (key: &KeyEvent) -> Option<&'static C> {
const HANDLE_KEY_MAP: &'static [(KeyEvent, C)] = &[]; // FIXME: needs to be method
#[inline] fn match_input (from: &TuiInput) -> Option<&'static 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> {
for (binding, command) in Self::HANDLE_KEY_MAP.iter() {
if key == binding {
return Some(command);
@ -35,8 +41,11 @@ pub trait HandleKey<C: Command<Self> + 'static>: Sized {
}
None
}
fn handle_key (&mut self, key: &KeyEvent) -> Perhaps<C> {
if let Some(command) = Self::match_key(key) {
#[inline] fn match_key (&self, key: &KeyEvent) -> Option<&'static C> {
Self::match_key_static(key)
}
#[inline] fn handle_key (&mut self, key: &KeyEvent) -> Perhaps<C> {
if let Some(command) = self.match_key(key) {
command.run(self)
} else {
Ok(None)