avalanche_web/
events.rs

1use std::ops::Deref;
2use wasm_bindgen::JsCast;
3
4pub(crate) use web_sys::AnimationEvent;
5pub(crate) use web_sys::CompositionEvent;
6pub(crate) use web_sys::DragEvent;
7pub(crate) use web_sys::Event;
8pub(crate) use web_sys::FocusEvent;
9pub(crate) use web_sys::KeyboardEvent;
10pub(crate) use web_sys::MouseEvent;
11pub(crate) use web_sys::PointerEvent;
12pub(crate) use web_sys::ProgressEvent;
13pub(crate) use web_sys::TouchEvent;
14pub(crate) use web_sys::TransitionEvent;
15pub(crate) use web_sys::WheelEvent;
16
17/// A typed wrapper over `web_sys`'s event types, allowing for typed access to the native element
18/// reference returned by [current_target](TypedEvent::current_target), as well as access to the methods of
19/// event `E`.
20pub struct TypedEvent<E: JsCast + Clone + Into<Event>, C: JsCast> {
21    event: E,
22    current_target: Option<C>,
23}
24
25impl<E: JsCast + Clone + Into<Event>, C: JsCast + Clone> TypedEvent<E, C> {
26    /// Constructs a new [`TypedEvent`] using the given event. It is the caller's
27    /// responsibility to ensure the component type `C` is correct in context.
28    pub(crate) fn new(event: E) -> Self {
29        let event_clone: Event = event.clone().into();
30        Self {
31            event,
32            current_target: event_clone
33                .current_target()
34                .and_then(|ct| ct.dyn_into::<C>().ok()),
35        }
36    }
37
38    /// Returns the event's current target, or [`None`](Option::None) if not available or the type of the
39    /// current target does not match type `C`.
40    pub fn current_target(&self) -> Option<C> {
41        self.current_target.clone()
42    }
43}
44
45impl<E: JsCast + Clone + Into<Event>, C: JsCast> Deref for TypedEvent<E, C> {
46    type Target = E;
47
48    fn deref(&self) -> &Self::Target {
49        &self.event
50    }
51}