Skip to main content

devela/sys/os/browser/web/event/
button.rs

1// devela::sys::os::browser::web::event::button
2//
3//! Implement conversions from/into web event types.
4//
5
6use crate::{EventButton, EventButtonState, WebEventKind};
7
8impl EventButton {
9    /// Converts a DOM-compatible `button` value into a normalized button slot.
10    ///
11    /// This preserves the reported button slot. It does not assign contextual
12    /// roles such as "back", "forward", "barrel", or "eraser".
13    pub const fn from_web(js_button: u8) -> Option<Self> {
14        match js_button {
15            0 => Some(EventButton::Left),
16            1 => Some(EventButton::Middle),
17            2 => Some(EventButton::Right),
18            3 => Some(EventButton::X1),
19            4 => Some(EventButton::X2),
20            //
21            5 => Some(EventButton::X3),
22            6 => Some(EventButton::X4),
23            7 => Some(EventButton::X5),
24            255 => None, // (== -1_i8) represents "no button"
25            n => Some(EventButton::Other(n)),
26        }
27    }
28    /// Converts a normalized button slot into a DOM-compatible button value.
29    pub const fn to_web(self) -> u8 {
30        match self {
31            EventButton::Left => 0,
32            EventButton::Middle => 1,
33            EventButton::Right => 2,
34            EventButton::X1 => 3,
35            EventButton::X2 => 4,
36            //
37            EventButton::X3 => 5,
38            EventButton::X4 => 6,
39            EventButton::X5 => 7,
40            EventButton::Other(n) => n,
41        }
42    }
43}
44
45// IMPROVE: MAYBE impl try_ methods
46impl EventButtonState {
47    /// Converts a `WebEventKind` into `EventButtonState`.
48    pub const fn from_web(js_event: WebEventKind) -> Self {
49        use {EventButtonState as E, WebEventKind as J};
50        match js_event {
51            J::Click | J::MouseDown | J::PointerDown => E::Pressed,
52            J::MouseUp | J::PointerUp => E::Released,
53            _ => E::Moved,
54        }
55    }
56    /// Converts a `EventButtonState` into a `WebEventKind`.
57    pub const fn to_web_as_mouse(self) -> WebEventKind {
58        use {EventButtonState as E, WebEventKind as J};
59        match self {
60            E::Pressed => J::MouseDown,
61            E::Released => J::MouseUp,
62            E::Moved => J::MouseMove,
63        }
64    }
65    /// Converts a `EventButtonState` into a `WebEventKind`.
66    pub const fn to_web_as_pointer(self) -> WebEventKind {
67        use {EventButtonState as E, WebEventKind as J};
68        match self {
69            E::Pressed => J::PointerDown,
70            E::Released => J::PointerUp,
71            E::Moved => J::PointerMove,
72        }
73    }
74}