use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
#[derive(Debug, Clone, PartialEq)]
pub enum Action {
NavigateUp,
NavigateDown,
NavigatePageUp,
NavigatePageDown,
NavigateTop,
NavigateBottom,
ToggleExpand,
StartEdit,
CancelEdit,
ConfirmEdit,
InsertChar(char),
Backspace,
Save,
Quit,
Search,
None,
}
pub fn handle_key(key: KeyEvent, editing: bool) -> Action {
if editing {
handle_editing_keys(key)
} else {
handle_browsing_keys(key)
}
}
fn handle_editing_keys(key: KeyEvent) -> Action {
match (key.code, key.modifiers) {
(KeyCode::Enter, KeyModifiers::NONE) => Action::ConfirmEdit,
(KeyCode::Esc, _) => Action::CancelEdit,
(KeyCode::Char(c), KeyModifiers::NONE | KeyModifiers::SHIFT) => Action::InsertChar(c),
(KeyCode::Backspace, _) => Action::Backspace,
(KeyCode::Char('c'), KeyModifiers::CONTROL) => Action::Quit,
_ => Action::None,
}
}
fn handle_browsing_keys(key: KeyEvent) -> Action {
match (key.code, key.modifiers) {
(KeyCode::Up, _) => Action::NavigateUp,
(KeyCode::Down, _) => Action::NavigateDown,
(KeyCode::Left, _) => Action::ToggleExpand, (KeyCode::Right, _) => Action::ToggleExpand,
(KeyCode::Char('k'), KeyModifiers::NONE) => Action::NavigateUp,
(KeyCode::Char('j'), KeyModifiers::NONE) => Action::NavigateDown,
(KeyCode::Char('h'), KeyModifiers::NONE) => Action::ToggleExpand,
(KeyCode::Char('l'), KeyModifiers::NONE) => Action::ToggleExpand,
(KeyCode::PageUp, _) | (KeyCode::Char('u'), KeyModifiers::CONTROL) => {
Action::NavigatePageUp
}
(KeyCode::PageDown, _) | (KeyCode::Char('d'), KeyModifiers::CONTROL) => {
Action::NavigatePageDown
}
(KeyCode::Home, _) | (KeyCode::Char('g'), KeyModifiers::NONE) => Action::NavigateTop,
(KeyCode::End, _) | (KeyCode::Char('G'), KeyModifiers::SHIFT) => Action::NavigateBottom,
(KeyCode::Enter, _) | (KeyCode::Char(' '), KeyModifiers::NONE) => Action::ToggleExpand,
(KeyCode::Char('e'), KeyModifiers::NONE) => Action::StartEdit,
(KeyCode::Char('s'), KeyModifiers::NONE) | (KeyCode::Char('w'), KeyModifiers::CONTROL) => {
Action::Save
}
(KeyCode::Char('q'), KeyModifiers::NONE) | (KeyCode::Esc, _) => Action::Quit,
(KeyCode::Char('c'), KeyModifiers::CONTROL) => Action::Quit,
(KeyCode::Char('/'), KeyModifiers::NONE) => Action::Search,
_ => Action::None,
}
}