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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
//! everything that has to do with HTML event handling

use crate::{prelude::*, AsEntity, AsElement};

/// A dom event subscription, that will unsubscribe from dom when dropped
pub struct EventHandler {
	target: web_sys::EventTarget,
	name: &'static str,
	cb: Box<dyn std::convert::AsRef<JsValue>>,
}

impl Drop for EventHandler {
	fn drop(&mut self) {
		let res = self.target.remove_event_listener_with_callback(self.name, (*self.cb).as_ref().unchecked_ref());
		if let Err(_e) = res {
			// TODO?
			// log::warn!("remove_event_listener_with_callback failed with error: {}", serde_json::to_string_pretty(&e.into_serde::<serde_json::Value>().unwrap()).unwrap());
		}
	}
}

macro_rules! generate_events {
	($($([$maybe_cfg:ident],)? $event_kind:ident, $name:ident, $f:ident);+$(;)*) => {paste::item!{

		#[extend::ext(name = RawDomEvents)]
		pub impl web_sys::EventTarget {$(
			$(#[cfg($maybe_cfg)])?
			fn $f(&self, f: impl FnMut(web_sys::$event_kind) + 'static) -> EventHandler {
				let handler = Closure::wrap(Box::new(f) as Box<dyn FnMut(web_sys::$event_kind) + 'static>);
				self.add_event_listener_with_callback(web_str::$name(), handler.as_ref().unchecked_ref()).expect("can't add event listener");
				EventHandler {
					target: self.clone(),
					name: web_str::$name(),
					cb: Box::new(handler),
				}
			}
		)+}

		pub trait DomEvents: AsElement {$(
			$(#[cfg($maybe_cfg)])?
			fn [<add_ $f>](&self, f: impl FnMut(web_sys::$event_kind) + 'static) {
				let entity = self.as_entity();
				if entity.is_dead() { log::warn!("callback handler entity dead {:?}", entity); return; }
				let target = entity.get_cmp::<web_sys::EventTarget>();
				entity.get_cmp_mut_or_default::<Vec<EventHandler>>().push(target.$f(f));
			}

			$(#[cfg($maybe_cfg)])?
			fn $f(self, f: impl FnMut(web_sys::$event_kind) + 'static) -> Self where Self: Sized { self.[<add_ $f>](f); self }

			$(#[cfg($maybe_cfg)])?
			fn [<with_ $f>](self, mut f: impl FnMut(&Self, web_sys::$event_kind) + 'static) -> Self where Self: Sized + Clone + 'static {
				let self_clone = self.clone();
				self.[<add_ $f>](move |event| f(&self_clone, event));
				self
			}
		)+}

		impl<T: AsElement> DomEvents for T {}
	}};
}

generate_events! {
	MouseEvent,      click,              on_click;
	MouseEvent,      contextmenu,        on_context_menu;
	MouseEvent,      dblclick,           on_dbl_click;
	MouseEvent,      mousedown,          on_mouse_down;
	MouseEvent,      mouseenter,         on_mouse_enter;
	MouseEvent,      mouseleave,         on_mouse_leave;
	MouseEvent,      mousemove,          on_mouse_move;
	MouseEvent,      mouseover,          on_mouse_over;
	MouseEvent,      mouseout,           on_mouse_out;
	MouseEvent,      mouseup,            on_mouse_up;
	KeyboardEvent,   keydown,            on_key_down;
	KeyboardEvent,   keyup,              on_key_up;
	Event,           change,             on_change;
	Event,           scroll,             on_scroll;
	UiEvent,         resize,             on_resize;
	FocusEvent,      blur,               on_blur;
	FocusEvent,      focus,              on_focus;
	TouchEvent,      touchstart,         on_touch_start;
	TouchEvent,      touchend,           on_touch_end;
	TouchEvent,      touchmove,          on_touch_move;
	TouchEvent,      touchcancel,        on_touch_cancel;
	WheelEvent,      wheel,              on_wheel;
	Event,           load,               on_load;
	Event,           canplay,            on_can_play;
	DragEvent,       drag,               on_drag;
	SubmitEvent,     submit,             on_submit;
	InputEvent,      input,              on_input;
	AnimationEvent,  animationcancel,    on_animation_cancel;
	AnimationEvent,  animationend,       on_animation_end;
	AnimationEvent,  animationiteration, on_animation_iteration;
	AnimationEvent,  animationstart,     on_animation_start;
	PopStateEvent,   popstate,           on_pop_state;
	HashChangeEvent, hashchange,         on_hash_change;

	[web_sys_unstable_apis], ClipboardEvent, cut,   on_cut;
	[web_sys_unstable_apis], ClipboardEvent, copy,  on_copy;
	[web_sys_unstable_apis], ClipboardEvent, paste, on_paste;
}

// DeviceMotionEvent
// DeviceOrientationEvent
// DeviceProximityEvent
// ErrorEvent
// ExtendableEvent
// ExtendableMessageEvent
// FetchEvent
// AudioProcessingEvent
// FontFaceSetLoadEvent
// GamepadAxisMoveEvent
// GamepadButtonEvent
// GamepadEvent
// GpuUncapturedErrorEvent
// IdbVersionChangeEvent
// ImageCaptureErrorEvent
// BeforeUnloadEvent
// MediaEncryptedEvent
// MediaKeyError
// MediaKeyMessageEvent
// MediaQueryListEvent
// MediaRecorderErrorEvent
// MediaStreamEvent
// MediaStreamTrackEvent
// MessageEvent
// MidiConnectionEvent
// MidiMessageEvent
// BlobEvent
// NotificationEvent
// OfflineAudioCompletionEvent
// PageTransitionEvent
// PaymentMethodChangeEvent
// PaymentRequestUpdateEvent
// PointerEvent
// PopupBlockedEvent
// PresentationConnectionAvailableEvent
// PresentationConnectionCloseEvent
// ProgressEvent
// PromiseRejectionEvent
// PushEvent
// RtcDataChannelEvent
// RtcPeerConnectionIceEvent
// RtcTrackEvent
// RtcdtmfToneChangeEvent
// CloseEvent
// ScrollAreaEvent
// SecurityPolicyViolationEvent
// SpeechRecognitionError
// SpeechRecognitionEvent
// SpeechSynthesisErrorEvent
// SpeechSynthesisEvent
// StorageEvent
// TcpServerSocketEvent
// TcpSocketErrorEvent
// TcpSocketEvent
// CompositionEvent
// TimeEvent
// TrackEvent
// TransitionEvent
// UserProximityEvent
// WebGlContextEvent
// DeviceLightEvent