Skip to main content

virtual_node/event/
event_handlers.rs

1use crate::event::RealDom;
2use std::cell::RefCell;
3use std::fmt::{Debug, Formatter};
4use std::rc::Rc;
5
6/// Event handlers such as the closure in `onclick = |mouse_event| {}`.
7pub enum EventHandler<Dom: RealDom> {
8    /// A callback that does not contain any arguments.
9    NoArgs(Rc<RefCell<dyn FnMut()>>),
10    /// Handle mouse events such as `onclick` and `oninput`
11    MouseEvent(Rc<RefCell<dyn FnMut(Dom::MouseEvent)>>),
12    /// EventHandler's that we do not have a dedicated type for.
13    /// This is useful for custom events.
14    Custom(Dom::EventCallback),
15}
16impl<Dom: RealDom> Clone for EventHandler<Dom> {
17    fn clone(&self) -> Self {
18        match self {
19            Self::NoArgs(func) => Self::NoArgs(func.clone()),
20            Self::MouseEvent(func) => Self::MouseEvent(func.clone()),
21            Self::Custom(func) => Self::Custom(func.clone()),
22        }
23    }
24}
25
26/// A mouse event.
27///
28/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent)
29#[derive(Clone)]
30#[cfg(feature = "web")]
31pub struct MouseEventWebSys {
32    event: web_sys::MouseEvent,
33    should_propagate: Rc<std::cell::Cell<bool>>,
34}
35
36#[cfg(feature = "web")]
37impl MouseEventWebSys {
38    /// Create a new MouseEvent.
39    pub fn new(event: web_sys::MouseEvent) -> Self {
40        MouseEventWebSys {
41            event,
42            should_propagate: Rc::new(std::cell::Cell::new(true)),
43        }
44    }
45
46    /// Prevent the event from propagating.
47    pub fn stop_propagation(&self) {
48        self.should_propagate.set(false);
49        self.event.stop_propagation();
50    }
51
52    /// Whether or not the event should propagate.
53    pub fn should_propagate(&self) -> &Rc<std::cell::Cell<bool>> {
54        &self.should_propagate
55    }
56}
57
58#[cfg(feature = "web")]
59impl std::ops::Deref for MouseEventWebSys {
60    type Target = web_sys::MouseEvent;
61
62    fn deref(&self) -> &Self::Target {
63        &self.event
64    }
65}
66
67// Allows us to easily derive PartialEq for some of the types that contain events.
68// Those PartialEq implementations are used for testing.
69// Maybe we can put some of the event related PartialEq implementations
70// behind a #[cfg(any(test, feature = "__test-utils"))].
71impl<Dom: RealDom> PartialEq for EventHandler<Dom> {
72    fn eq(&self, _other: &Self) -> bool {
73        true
74    }
75}
76
77impl<Dom: RealDom> Debug for EventHandler<Dom> {
78    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
79        f.write_str("event handler")
80    }
81}