use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crate::tui::line_editor::LineEditor;
#[derive(Clone, Debug, Default)]
pub(in crate::tui) enum SurfaceFocus {
#[default]
Idle,
Navigating { surface: String, index: usize },
Editing {
surface: String,
index: usize,
editor: LineEditor,
invalid: Option<&'static str>,
},
}
impl SurfaceFocus {
pub(super) fn place(&self) -> Option<(&str, usize)> {
match self {
Self::Idle => None,
Self::Navigating { surface, index } | Self::Editing { surface, index, .. } => {
Some((surface, *index))
}
}
}
}
pub(super) fn is_focus_chord(key: KeyEvent) -> bool {
key.modifiers == KeyModifiers::ALT && key.code == KeyCode::Char('u')
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum NavKey {
Next,
Previous,
Left,
Right,
Activate,
Leave,
Type(char),
}
impl NavKey {
pub(super) fn of(key: KeyEvent) -> Option<Self> {
let plain = !key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT);
match key.code {
KeyCode::BackTab => Some(Self::Previous),
_ if !plain => None,
KeyCode::Tab | KeyCode::Down => Some(Self::Next),
KeyCode::Up => Some(Self::Previous),
KeyCode::Left => Some(Self::Left),
KeyCode::Right => Some(Self::Right),
KeyCode::Enter | KeyCode::Char(' ') => Some(Self::Activate),
KeyCode::Esc => Some(Self::Leave),
KeyCode::Char(ch) => Some(Self::Type(ch)),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum EditKey {
Edited,
Done,
DoneThen(NavKey),
}
impl EditKey {
pub(super) fn apply(
key: KeyEvent,
editor: &mut LineEditor,
accepts: impl Fn(char) -> bool,
) -> Option<Self> {
let plain = !key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT);
match key.code {
KeyCode::BackTab => return Some(Self::DoneThen(NavKey::Previous)),
_ if !plain => return None,
KeyCode::Enter | KeyCode::Esc => return Some(Self::Done),
KeyCode::Tab | KeyCode::Down => return Some(Self::DoneThen(NavKey::Next)),
KeyCode::Up => return Some(Self::DoneThen(NavKey::Previous)),
KeyCode::Char(ch) if accepts(ch) => editor.insert_char(ch),
KeyCode::Char(_) => {}
KeyCode::Backspace => editor.backspace(),
KeyCode::Delete => editor.delete(),
KeyCode::Left => editor.move_cursor_left(),
KeyCode::Right => editor.move_cursor_right(),
KeyCode::Home => editor.move_cursor_home(),
KeyCode::End => editor.move_cursor_end(),
_ => return None,
}
Some(Self::Edited)
}
}