use crate::event::MoveSelection;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PaletteKey {
Accept,
Cancel,
Move(MoveSelection),
Insert(char),
Backspace,
Ignore,
}
#[cfg(feature = "crossterm")]
impl PaletteKey {
pub fn from_crossterm(event: crossterm::event::KeyEvent) -> Self {
use crossterm::event::{KeyCode, KeyEventKind};
if event.kind != KeyEventKind::Press {
return Self::Ignore;
}
match event.code {
KeyCode::Esc => Self::Cancel,
KeyCode::Enter => Self::Accept,
KeyCode::Backspace => Self::Backspace,
KeyCode::Down => Self::Move(MoveSelection::Next),
KeyCode::Up => Self::Move(MoveSelection::Previous),
KeyCode::PageDown => Self::Move(MoveSelection::PageDown(5)),
KeyCode::PageUp => Self::Move(MoveSelection::PageUp(5)),
KeyCode::Home => Self::Move(MoveSelection::First),
KeyCode::End => Self::Move(MoveSelection::Last),
KeyCode::Char(character) => Self::Insert(character),
_ => Self::Ignore,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "crossterm")]
#[test]
fn converts_crossterm_key_presses() {
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
let event =
KeyEvent::new_with_kind(KeyCode::Char('q'), KeyModifiers::NONE, KeyEventKind::Press);
assert_eq!(PaletteKey::from_crossterm(event), PaletteKey::Insert('q'));
}
#[cfg(feature = "crossterm")]
#[test]
fn ignores_crossterm_key_releases() {
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
let event =
KeyEvent::new_with_kind(KeyCode::Enter, KeyModifiers::NONE, KeyEventKind::Release);
assert_eq!(PaletteKey::from_crossterm(event), PaletteKey::Ignore);
}
}