virtual_node/event/
event_handlers.rs

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