-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
listeners.rs
709 lines (611 loc) · 20.9 KB
/
listeners.rs
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
use super::Apply;
use crate::dom_bundle::test_log;
use crate::virtual_dom::{Listener, ListenerKind, Listeners};
use gloo::events::{EventListener, EventListenerOptions, EventListenerPhase};
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::ops::Deref;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use wasm_bindgen::JsCast;
use web_sys::{Element, Event};
thread_local! {
/// Global event listener registry
static REGISTRY: RefCell<Registry> = Default::default();
/// Key used to store listener id on element
static LISTENER_ID_PROP: wasm_bindgen::JsValue = "__yew_listener_id".into();
/// Cached reference to the document body
static BODY: web_sys::HtmlElement = gloo_utils::document().body().unwrap();
}
/// Bubble events during delegation
static BUBBLE_EVENTS: AtomicBool = AtomicBool::new(true);
/// Set, if events should bubble up the DOM tree, calling any matching callbacks.
///
/// Bubbling is enabled by default. Disabling bubbling can lead to substantial improvements in event
/// handling performance.
///
/// Note that yew uses event delegation and implements internal even bubbling for performance
/// reasons. Calling `Event.stopPropagation()` or `Event.stopImmediatePropagation()` in the event
/// handler has no effect.
///
/// This function should be called before any component is mounted.
pub fn set_event_bubbling(bubble: bool) {
BUBBLE_EVENTS.store(bubble, Ordering::Relaxed);
}
/// An active set of listeners on an element
#[derive(Debug)]
pub(super) enum ListenerRegistration {
/// No listeners registered.
NoReg,
/// Added to global registry by ID
Registered(u32),
}
impl Apply for Listeners {
type Element = Element;
type Bundle = ListenerRegistration;
fn apply(self, el: &Self::Element) -> ListenerRegistration {
match self {
Self::Pending(pending) => ListenerRegistration::register(el, &pending),
Self::None => ListenerRegistration::NoReg,
}
}
fn apply_diff(self, el: &Self::Element, bundle: &mut ListenerRegistration) {
use ListenerRegistration::*;
use Listeners::*;
match (self, bundle) {
(Pending(pending), Registered(ref id)) => {
// Reuse the ID
test_log!("reusing listeners for {}", id);
Registry::with(|reg| reg.patch(id, &*pending));
}
(Pending(pending), bundle @ NoReg) => {
*bundle = ListenerRegistration::register(el, &pending);
test_log!(
"registering listeners for {}",
match bundle {
ListenerRegistration::Registered(id) => id,
_ => unreachable!(),
}
);
}
(None, bundle @ Registered(_)) => {
let id = match bundle {
ListenerRegistration::Registered(ref id) => id,
_ => unreachable!(),
};
test_log!("unregistering listeners for {}", id);
Registry::with(|reg| reg.unregister(id));
*bundle = NoReg;
}
(None, NoReg) => {
test_log!("{}", &"unchanged empty listeners");
}
};
}
}
impl ListenerRegistration {
/// Register listeners and return their handle ID
fn register(el: &Element, pending: &[Option<Rc<dyn Listener>>]) -> Self {
Self::Registered(Registry::with(|reg| {
let id = reg.set_listener_id(el);
reg.register(id, pending);
id
}))
}
/// Remove any registered event listeners from the global registry
pub(super) fn unregister(&self) {
if let Self::Registered(id) = self {
Registry::with(|r| r.unregister(id));
}
}
}
#[derive(Clone, Hash, Eq, PartialEq, Debug)]
struct EventDescriptor {
kind: ListenerKind,
passive: bool,
}
impl From<&dyn Listener> for EventDescriptor {
fn from(l: &dyn Listener) -> Self {
Self {
kind: l.kind(),
passive: l.passive(),
}
}
}
/// Ensures global event handler registration.
//
// Separate struct to DRY, while avoiding partial struct mutability.
#[derive(Default, Debug)]
struct GlobalHandlers {
/// Events with registered handlers that are possibly passive
handling: HashSet<EventDescriptor>,
/// Keep track of all listeners to drop them on registry drop.
/// The registry is never dropped in production.
#[cfg(test)]
registered: Vec<(ListenerKind, EventListener)>,
}
impl GlobalHandlers {
/// Ensure a descriptor has a global event handler assigned
fn ensure_handled(&mut self, desc: EventDescriptor) {
if !self.handling.contains(&desc) {
let cl = {
let desc = desc.clone();
BODY.with(move |body| {
let options = EventListenerOptions {
phase: EventListenerPhase::Capture,
passive: desc.passive,
};
EventListener::new_with_options(
body,
desc.kind.type_name(),
options,
move |e: &Event| Registry::handle(desc.clone(), e.clone()),
)
})
};
// Never drop the closure as this event handler is static
#[cfg(not(test))]
cl.forget();
#[cfg(test)]
self.registered.push((desc.kind.clone(), cl));
self.handling.insert(desc);
}
}
}
/// Global multiplexing event handler registry
#[derive(Default, Debug)]
struct Registry {
/// Counter for assigning new IDs
id_counter: u32,
/// Registered global event handlers
global: GlobalHandlers,
/// Contains all registered event listeners by listener ID
by_id: HashMap<u32, HashMap<EventDescriptor, Vec<Rc<dyn Listener>>>>,
}
impl Registry {
/// Run f with access to global Registry
#[inline]
fn with<R>(f: impl FnOnce(&mut Registry) -> R) -> R {
REGISTRY.with(|r| f(&mut *r.borrow_mut()))
}
/// Register all passed listeners under ID
fn register(&mut self, id: u32, listeners: &[Option<Rc<dyn Listener>>]) {
let mut by_desc =
HashMap::<EventDescriptor, Vec<Rc<dyn Listener>>>::with_capacity(listeners.len());
for l in listeners.iter().filter_map(|l| l.as_ref()).cloned() {
let desc = EventDescriptor::from(l.deref());
self.global.ensure_handled(desc.clone());
by_desc.entry(desc).or_default().push(l);
}
self.by_id.insert(id, by_desc);
}
/// Patch an already registered set of handlers
fn patch(&mut self, id: &u32, listeners: &[Option<Rc<dyn Listener>>]) {
if let Some(by_desc) = self.by_id.get_mut(id) {
// Keeping empty vectors is fine. Those don't do much and should happen rarely.
for v in by_desc.values_mut() {
v.clear()
}
for l in listeners.iter().filter_map(|l| l.as_ref()).cloned() {
let desc = EventDescriptor::from(l.deref());
self.global.ensure_handled(desc.clone());
by_desc.entry(desc).or_default().push(l);
}
}
}
/// Unregister any existing listeners for ID
fn unregister(&mut self, id: &u32) {
self.by_id.remove(id);
}
/// Set unique listener ID onto element and return it
fn set_listener_id(&mut self, el: &Element) -> u32 {
let id = self.id_counter;
self.id_counter += 1;
LISTENER_ID_PROP.with(|prop| {
if !js_sys::Reflect::set(el, prop, &js_sys::Number::from(id)).unwrap() {
panic!("failed to set listener ID property");
}
});
id
}
/// Handle a global event firing
fn handle(desc: EventDescriptor, event: Event) {
let target = match event
.target()
.and_then(|el| el.dyn_into::<web_sys::Element>().ok())
{
Some(el) => el,
None => return,
};
Self::run_handlers(desc, event, target);
}
fn run_handlers(desc: EventDescriptor, event: Event, target: web_sys::Element) {
let run_handler = |el: &web_sys::Element| {
if let Some(l) = LISTENER_ID_PROP
.with(|prop| js_sys::Reflect::get(el, prop).ok())
.and_then(|v| v.dyn_into().ok())
.and_then(|num: js_sys::Number| {
Registry::with(|r| {
r.by_id
.get(&(num.value_of() as u32))
.and_then(|s| s.get(&desc))
.cloned()
})
})
{
for l in l {
l.handle(event.clone());
}
}
};
run_handler(&target);
if BUBBLE_EVENTS.load(Ordering::Relaxed) {
let mut el = target;
while !event.cancel_bubble() {
el = match el.parent_element() {
Some(el) => el,
None => break,
};
run_handler(&el);
}
}
}
}
#[cfg(all(test, feature = "wasm_test"))]
mod tests {
use std::marker::PhantomData;
use wasm_bindgen_test::{wasm_bindgen_test as test, wasm_bindgen_test_configure};
use web_sys::{Event, EventInit, MouseEvent};
wasm_bindgen_test_configure!(run_in_browser);
use crate::{html, html::TargetCast, scheduler, AppHandle, Component, Context, Html};
use gloo_utils::document;
use wasm_bindgen::JsCast;
use yew::Callback;
#[derive(Clone)]
enum Message {
Action,
StopListening,
SetText(String),
}
#[derive(Default)]
struct State {
stop_listening: bool,
action: u32,
text: String,
}
trait Mixin {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message>,
{
let link = ctx.link().clone();
let onclick = Callback::from(move |_| {
link.send_message(Message::Action);
scheduler::start_now();
});
if state.stop_listening {
html! {
<a>{state.action}</a>
}
} else {
html! {
<a {onclick}>
{state.action}
</a>
}
}
}
}
struct Comp<M>
where
M: Mixin + 'static,
{
state: State,
pd: PhantomData<M>,
}
impl<M> Component for Comp<M>
where
M: Mixin + 'static,
{
type Message = Message;
type Properties = ();
fn create(_: &Context<Self>) -> Self {
Comp {
state: Default::default(),
pd: PhantomData,
}
}
fn update(&mut self, _: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Message::Action => {
self.state.action += 1;
}
Message::StopListening => {
self.state.stop_listening = true;
}
Message::SetText(s) => {
self.state.text = s;
}
};
true
}
fn view(&self, ctx: &Context<Self>) -> crate::Html {
M::view(ctx, &self.state)
}
}
fn assert_count(el: &web_sys::HtmlElement, count: isize) {
assert_eq!(el.text_content(), Some(count.to_string()))
}
fn get_el_by_tag(tag: &str) -> web_sys::HtmlElement {
document()
.query_selector(tag)
.unwrap()
.unwrap()
.dyn_into::<web_sys::HtmlElement>()
.unwrap()
}
fn init<M>(tag: &str) -> (AppHandle<Comp<M>>, web_sys::HtmlElement)
where
M: Mixin,
{
// Remove any existing listeners and elements
super::Registry::with(|r| *r = Default::default());
if let Some(el) = document().query_selector(tag).unwrap() {
el.parent_element().unwrap().remove();
}
let root = document().create_element("div").unwrap();
document().body().unwrap().append_child(&root).unwrap();
let app = crate::start_app_in_element::<Comp<M>>(root);
scheduler::start_now();
(app, get_el_by_tag(tag))
}
#[test]
fn synchronous() {
struct Synchronous;
impl Mixin for Synchronous {}
let (link, el) = init::<Synchronous>("a");
assert_count(&el, 0);
el.click();
assert_count(&el, 1);
el.click();
assert_count(&el, 2);
link.send_message(Message::StopListening);
scheduler::start_now();
el.click();
assert_count(&el, 2);
}
#[test]
async fn non_bubbling_event() {
struct NonBubbling;
impl Mixin for NonBubbling {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message>,
{
let link = ctx.link().clone();
let onblur = Callback::from(move |_| {
link.send_message(Message::Action);
scheduler::start_now();
});
html! {
<div>
<a>
<input id="input" {onblur} type="text" />
{state.action}
</a>
</div>
}
}
}
let (_, el) = init::<NonBubbling>("a");
assert_count(&el, 0);
let input = document().get_element_by_id("input").unwrap();
input
.dispatch_event(
&Event::new_with_event_init_dict("blur", &{
let mut dict = EventInit::new();
dict.bubbles(false);
dict
})
.unwrap(),
)
.unwrap();
assert_count(&el, 1);
}
#[test]
fn bubbling() {
struct Bubbling;
impl Mixin for Bubbling {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message>,
{
if state.stop_listening {
html! {
<div>
<a>
{state.action}
</a>
</div>
}
} else {
let link = ctx.link().clone();
let cb = Callback::from(move |_| {
link.send_message(Message::Action);
scheduler::start_now();
});
html! {
<div onclick={cb.clone()}>
<a onclick={cb}>
{state.action}
</a>
</div>
}
}
}
}
let (link, el) = init::<Bubbling>("a");
assert_count(&el, 0);
el.click();
assert_count(&el, 2);
el.click();
assert_count(&el, 4);
link.send_message(Message::StopListening);
scheduler::start_now();
el.click();
assert_count(&el, 4);
}
#[test]
fn cancel_bubbling() {
struct CancelBubbling;
impl Mixin for CancelBubbling {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message>,
{
let link = ctx.link().clone();
let onclick = Callback::from(move |_| {
link.send_message(Message::Action);
scheduler::start_now();
});
let link = ctx.link().clone();
let onclick2 = Callback::from(move |e: MouseEvent| {
e.stop_propagation();
link.send_message(Message::Action);
scheduler::start_now();
});
html! {
<div onclick={onclick}>
<a onclick={onclick2}>
{state.action}
</a>
</div>
}
}
}
let (_, el) = init::<CancelBubbling>("a");
assert_count(&el, 0);
el.click();
assert_count(&el, 1);
el.click();
assert_count(&el, 2);
}
#[test]
fn cancel_bubbling_nested() {
// Here an event is being delivered to a DOM node which does
// _not_ have a listener but which is contained within an
// element that does and which cancels the bubble.
struct CancelBubbling;
impl Mixin for CancelBubbling {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message>,
{
let link = ctx.link().clone();
let onclick = Callback::from(move |_| {
link.send_message(Message::Action);
scheduler::start_now();
});
let link = ctx.link().clone();
let onclick2 = Callback::from(move |e: MouseEvent| {
e.stop_propagation();
link.send_message(Message::Action);
scheduler::start_now();
});
html! {
<div onclick={onclick}>
<div onclick={onclick2}>
<a>
{state.action}
</a>
</div>
</div>
}
}
}
let (_, el) = init::<CancelBubbling>("a");
assert_count(&el, 0);
el.click();
assert_count(&el, 1);
el.click();
assert_count(&el, 2);
}
fn test_input_listener<E>(make_event: impl Fn() -> E)
where
E: JsCast + std::fmt::Debug,
{
struct Input;
impl Mixin for Input {
fn view<C>(ctx: &Context<C>, state: &State) -> Html
where
C: Component<Message = Message>,
{
if state.stop_listening {
html! {
<div>
<input type="text" />
<p>{state.text.clone()}</p>
</div>
}
} else {
let link = ctx.link().clone();
let onchange = Callback::from(move |e: web_sys::Event| {
let el: web_sys::HtmlInputElement = e.target_unchecked_into();
link.send_message(Message::SetText(el.value()));
scheduler::start_now();
});
let link = ctx.link().clone();
let oninput = Callback::from(move |e: web_sys::InputEvent| {
let el: web_sys::HtmlInputElement = e.target_unchecked_into();
link.send_message(Message::SetText(el.value()));
scheduler::start_now();
});
html! {
<div>
<input type="text" {onchange} {oninput} />
<p>{state.text.clone()}</p>
</div>
}
}
}
}
let (link, input_el) = init::<Input>("input");
let input_el = input_el.dyn_into::<web_sys::HtmlInputElement>().unwrap();
let p_el = get_el_by_tag("p");
assert_eq!(&p_el.text_content().unwrap(), "");
for mut s in ["foo", "bar", "baz"].iter() {
input_el.set_value(s);
if s == &"baz" {
link.send_message(Message::StopListening);
scheduler::start_now();
s = &"bar";
}
input_el
.dyn_ref::<web_sys::EventTarget>()
.unwrap()
.dispatch_event(&make_event().dyn_into().unwrap())
.unwrap();
assert_eq!(&p_el.text_content().unwrap(), s);
}
}
#[test]
fn oninput() {
test_input_listener(|| {
web_sys::InputEvent::new_with_event_init_dict(
"input",
web_sys::InputEventInit::new().bubbles(true),
)
.unwrap()
})
}
#[test]
fn onchange() {
test_input_listener(|| {
web_sys::Event::new_with_event_init_dict(
"change",
web_sys::EventInit::new().bubbles(true),
)
.unwrap()
})
}
}