termrs_core 0.3.0

The core library of termrs
Documentation
pub use crossterm::event::{
    KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers, MouseButton, MouseEventKind,
};

use crate::render::{Position, Size};

/// All possible events that
/// can be handled by widgets.
pub enum Event {
    Key(KeyEvent),
    Mouse(MouseEvent),
    GotFocus,
    LostFocus,
}

/// All possible events, which can be handled
/// by terminal application.
pub enum TerminalEvent {
    App(Event),
    Resize(Size),
}

impl TryFrom<crossterm::event::Event> for TerminalEvent {
    type Error = ();

    fn try_from(value: crossterm::event::Event) -> Result<Self, Self::Error> {
        match value {
            crossterm::event::Event::FocusGained => Ok(TerminalEvent::App(Event::GotFocus)),
            crossterm::event::Event::FocusLost => Ok(TerminalEvent::App(Event::LostFocus)),
            crossterm::event::Event::Key(key_event) => {
                Ok(TerminalEvent::App(Event::Key(key_event)))
            }
            crossterm::event::Event::Mouse(mouse_event) => {
                Ok(TerminalEvent::App(Event::Mouse(mouse_event.into())))
            }
            crossterm::event::Event::Resize(width, height) => {
                Ok(TerminalEvent::Resize(Size::new(width, height)))
            }
            _ => Err(()),
        }
    }
}

/// Represents a mouse event.
///
/// # Platform-specific Notes
///
/// ## Mouse Buttons
///
/// Some platforms/terminals do not report mouse button for the
/// `MouseEventKind::Up` and `MouseEventKind::Drag` events. `MouseButton::Left`
/// is returned if we don't know which button was used.
///
/// ## Key Modifiers
///
/// Some platforms/terminals does not report all key modifiers
/// combinations for all mouse event types. For example - macOS reports
/// `Ctrl` + left mouse button click as a right mouse button click.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct MouseEvent {
    /// The kind of mouse event that was caused.
    pub kind: MouseEventKind,
    /// The position of cell that the event occurred on.
    pub position: Position,
    /// The key modifiers active when the event occurred.
    pub modifiers: KeyModifiers,
}

impl From<crossterm::event::MouseEvent> for MouseEvent {
    fn from(value: crossterm::event::MouseEvent) -> Self {
        MouseEvent {
            position: Position::new(value.column, value.row),
            kind: value.kind,
            modifiers: value.modifiers,
        }
    }
}

/// Possible results of event handler methods.
pub enum EventStatus {
    /// Event was ignored and
    /// can be propogated futher.
    Ignored,

    /// Event was handled and
    /// the propogation should be stopped.
    Handled,
}