use crossterm::event::KeyEvent;
use super::bindings::KeyBindings;
pub struct NavigationHelper<'a> {
bindings: &'a KeyBindings,
}
impl<'a> NavigationHelper<'a> {
pub fn new(bindings: &'a KeyBindings) -> Self {
Self { bindings }
}
pub fn is_move_up(&self, key: &KeyEvent) -> bool {
KeyBindings::matches_any(&self.bindings.move_up, key)
}
pub fn is_move_down(&self, key: &KeyEvent) -> bool {
KeyBindings::matches_any(&self.bindings.move_down, key)
}
pub fn is_move_left(&self, key: &KeyEvent) -> bool {
KeyBindings::matches_any(&self.bindings.move_left, key)
}
pub fn is_move_right(&self, key: &KeyEvent) -> bool {
KeyBindings::matches_any(&self.bindings.move_right, key)
}
pub fn is_select(&self, key: &KeyEvent) -> bool {
KeyBindings::matches_any(&self.bindings.select, key)
}
pub fn is_cancel(&self, key: &KeyEvent) -> bool {
KeyBindings::matches_any(&self.bindings.cancel, key)
}
pub fn is_submit(&self, key: &KeyEvent) -> bool {
KeyBindings::matches_any(&self.bindings.submit, key)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crossterm::event::{KeyCode, KeyModifiers};
#[test]
fn test_navigation_helper_emacs_bindings() {
let bindings = KeyBindings::emacs();
let nav = NavigationHelper::new(&bindings);
let ctrl_p = KeyEvent::new(KeyCode::Char('p'), KeyModifiers::CONTROL);
assert!(nav.is_move_up(&ctrl_p));
let up = KeyEvent::new(KeyCode::Up, KeyModifiers::NONE);
assert!(nav.is_move_up(&up));
let ctrl_n = KeyEvent::new(KeyCode::Char('n'), KeyModifiers::CONTROL);
assert!(nav.is_move_down(&ctrl_n));
let down = KeyEvent::new(KeyCode::Down, KeyModifiers::NONE);
assert!(nav.is_move_down(&down));
}
#[test]
fn test_navigation_helper_select_cancel() {
let bindings = KeyBindings::emacs();
let nav = NavigationHelper::new(&bindings);
let enter = KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE);
assert!(nav.is_select(&enter));
let space = KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE);
assert!(nav.is_select(&space));
let esc = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
assert!(nav.is_cancel(&esc));
}
#[test]
fn test_navigation_helper_minimal_bindings() {
let bindings = KeyBindings::minimal();
let nav = NavigationHelper::new(&bindings);
let up = KeyEvent::new(KeyCode::Up, KeyModifiers::NONE);
assert!(nav.is_move_up(&up));
let ctrl_p = KeyEvent::new(KeyCode::Char('p'), KeyModifiers::CONTROL);
assert!(!nav.is_move_up(&ctrl_p));
}
}