1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use crate::EventAttribFn;
use std::cell::{Cell, RefCell};
use std::fmt::{Debug, Formatter};
use std::ops::Deref;
use std::rc::Rc;

/// Event handlers such as the closure in `onclick = |event| {}`.
///
/// ## Cloning
///
/// Can be cheaply cloned since since inner types are reference counted.
#[derive(Clone)]
pub enum EventHandler {
    /// A callback that does not contain any arguments.
    NoArgs(Rc<RefCell<dyn FnMut()>>),
    /// Handle mouse events such as `onclick` and `oninput`
    MouseEvent(Rc<RefCell<dyn FnMut(MouseEvent)>>),
    /// EventHandler's that we do not have a dedicated type for.
    /// This is useful for custom events.
    UnsupportedSignature(EventAttribFn),
}

/// A mouse event.
///
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent)
#[derive(Clone)]
pub struct MouseEvent {
    event: web_sys::MouseEvent,
    should_propagate: Rc<Cell<bool>>,
}

impl MouseEvent {
    /// Create a new MouseEvent.
    pub fn new(event: web_sys::MouseEvent) -> Self {
        MouseEvent {
            event,
            should_propagate: Rc::new(Cell::new(true)),
        }
    }

    /// Prevent the event from propagating.
    pub fn stop_propagation(&self) {
        self.should_propagate.set(false);
        self.event.stop_propagation();
    }

    /// Whether or not the event should propagate.
    pub fn should_propagate(&self) -> &Rc<Cell<bool>> {
        &self.should_propagate
    }
}

impl Deref for MouseEvent {
    type Target = web_sys::MouseEvent;

    fn deref(&self) -> &Self::Target {
        &self.event
    }
}

// Allows us to easily derive PartialEq for some of the types that contain events.
// Those PartialEq implementations are used for testing.
// Maybe we can put some of the event related PartialEq implementations
// behind a #[cfg(any(test, feature = "__test-utils"))].
impl PartialEq for EventHandler {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Debug for EventHandler {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str("event handler")
    }
}