widgetui/
events.rs

1use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind};
2
3use crate::State;
4
5/// A state that wraps over the events from crossterm
6#[derive(Default, Clone, State)]
7pub struct Events {
8    pub event: Option<Event>,
9    pub(crate) exit: bool,
10}
11
12impl Events {
13    /// Returns whether a key was pressed this frame.
14    pub fn key(&self, code: KeyCode) -> bool {
15        if let Some(Event::Key(key_event)) = self.event {
16            if key_event.code == code && key_event.kind == KeyEventKind::Press {
17                return true;
18            }
19        }
20
21        false
22    }
23
24    /// Returns whether a Key Event was completed this frame.
25    pub fn key_event(&self, check_event: KeyEvent) -> bool {
26        if let Some(Event::Key(key_event)) = self.event {
27            if key_event == check_event && key_event.kind == KeyEventKind::Press {
28                return true;
29            }
30        }
31
32        false
33    }
34
35    /// Returns whether a key was pressed this frame.
36    /// This will consume the key, not passing it on to future widgets.
37    pub fn consume_key(&mut self, code: KeyCode) -> bool {
38        if let Some(Event::Key(key_event)) = self.event {
39            if key_event.code == code && key_event.kind == KeyEventKind::Press {
40                self.event = None;
41                return true;
42            }
43        }
44
45        false
46    }
47
48    /// Let the app know you want to quit.
49    pub fn register_exit(&mut self) {
50        self.exit = true;
51    }
52}