fours 0.1.0

Four in a row in your terminal, with three levels of opponent.
Documentation
//! Key bindings.

use crate::app::Action;
use ratatui::crossterm::event::KeyCode;
use ratatui::crossterm::event::KeyEvent;
use ratatui::crossterm::event::KeyEventKind;
use ratatui::crossterm::event::KeyModifiers;

/// The action a key press asks for, if it asks for one.
///
/// The arrow keys and the vim keys move along the board, enter and space place a disc, a digit
/// points at a column, and `d` moves on to the next level.
///
/// # Examples
///
/// ```
/// use fours::app::Action;
/// use fours::app::input;
/// use ratatui::crossterm::event::KeyCode;
/// use ratatui::crossterm::event::KeyEvent;
///
/// assert_eq!(
///     input::action_for(KeyEvent::from(KeyCode::Char('d'))),
///     Some(Action::CycleDifficulty)
/// );
/// ```
pub fn action_for(key: KeyEvent) -> Option<Action> {
    if key.kind == KeyEventKind::Release {
        return None;
    }

    if is_interrupt(key) {
        return Some(Action::Quit);
    }

    match key.code {
        KeyCode::Left => Some(Action::Previous),
        KeyCode::Right => Some(Action::Next),
        KeyCode::Enter | KeyCode::Char(' ') | KeyCode::Down => Some(Action::Confirm),
        KeyCode::Esc => Some(Action::Quit),
        KeyCode::Char(character) => action_for_character(character),
        _ => None,
    }
}

fn action_for_character(character: char) -> Option<Action> {
    match character.to_ascii_lowercase() {
        'h' => Some(Action::Previous),
        'l' => Some(Action::Next),
        'j' => Some(Action::Confirm),
        'd' => Some(Action::CycleDifficulty),
        'r' => Some(Action::Restart),
        'q' => Some(Action::Quit),
        digit @ '1'..='9' => column_of(digit).map(Action::Choose),
        _ => None,
    }
}

/// The column a digit key points at. The keys are numbered from one, the columns from zero.
fn column_of(digit: char) -> Option<usize> {
    let column = digit.to_digit(10)?.checked_sub(1)?;

    usize::try_from(column).ok()
}

fn is_interrupt(key: KeyEvent) -> bool {
    key.modifiers.contains(KeyModifiers::CONTROL)
        && matches!(key.code, KeyCode::Char('c' | 'd' | 'C' | 'D'))
}