keyboard_types/
key_state.rs

1#[cfg(feature = "serde")]
2use serde::{Deserialize, Serialize};
3
4/// Describes the state a key is in.
5#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
6#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7pub enum KeyState {
8    /// The key is pressed down.
9    ///
10    /// Often emitted in a [keydown] event, see also [the MDN documentation][mdn] on that.
11    ///
12    /// [keydown]: https://w3c.github.io/uievents/#event-type-keydown
13    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/API/Element/keydown_event
14    Down,
15    /// The key is not pressed / was just released.
16    ///
17    /// Often emitted in a [keyup] event, see also [the MDN documentation][mdn] on that.
18    ///
19    /// [keyup]: https://w3c.github.io/uievents/#event-type-keyup
20    /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/API/Element/keyup_event
21    Up,
22}
23
24impl Default for KeyState {
25    fn default() -> KeyState {
26        KeyState::Down
27    }
28}
29
30impl KeyState {
31    /// The [type] name of the corresponding key event.
32    ///
33    /// This is either `"keydown"` or `"keyup"`.
34    ///
35    /// [type]: https://w3c.github.io/uievents/#events-keyboard-types
36    pub const fn event_type(self) -> &'static str {
37        match self {
38            Self::Down => "keydown",
39            Self::Up => "keyup",
40        }
41    }
42
43    /// True if the key is pressed down.
44    pub const fn is_down(self) -> bool {
45        matches!(self, Self::Down)
46    }
47
48    /// True if the key is released.
49    pub const fn is_up(self) -> bool {
50        matches!(self, Self::Up)
51    }
52}