lighthouse_protocol/input/
key_event.rs

1use serde::{Deserialize, Serialize};
2
3use crate::Direction;
4
5use super::{EventSource, KeyModifiers};
6
7/// A keyboard event.
8#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
9#[serde(rename_all = "camelCase")]
10pub struct KeyEvent {
11    /// The client identifier.
12    pub source: EventSource,
13    /// Whether the key was pressed.
14    pub down: bool,
15    /// Whether the event is a repeat event.
16    pub repeat: bool,
17    /// The key pressed, see the docs on JS's `KeyboardEvent.code` for details.
18    pub code: String, // TODO: Extract stronger `Key` type
19    /// The held key modifiers.
20    pub modifiers: KeyModifiers,
21}
22
23impl KeyEvent {
24    /// The direction if either the WASD or arrow keys were pressed.
25    pub fn direction(&self) -> Option<Direction> {
26        self.wasd_direction().or_else(|| self.arrow_direction())
27    }
28
29    /// The direction if one of the WASD keys was pressed.
30    pub fn wasd_direction(&self) -> Option<Direction> {
31        match self.code.as_str() {
32            "KeyW" => Some(Direction::Up),
33            "KeyA" => Some(Direction::Left),
34            "KeyS" => Some(Direction::Down),
35            "KeyD" => Some(Direction::Right),
36            _ => None,
37        }
38    }
39
40    /// The direction if one of the arrow keys was pressed.
41    pub fn arrow_direction(&self) -> Option<Direction> {
42        match self.code.as_str() {
43            "ArrowUp" => Some(Direction::Up),
44            "ArrowLeft" => Some(Direction::Left),
45            "ArrowDown" => Some(Direction::Down),
46            "ArrowRight" => Some(Direction::Right),
47            _ => None,
48        }
49    }
50}