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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
use std::{
    cell::RefCell,
    collections::{HashMap, HashSet},
    ops::Deref,
    rc::Rc,
};
use wasm_bindgen::{prelude::*, 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 mut BUBBLE_EVENTS: bool = 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) {
    unsafe {
        BUBBLE_EVENTS = bubble;
    }
}

/// The [Listener] trait is an universal implementation of an event listener
/// which is used to bind Rust-listener to JS-listener (DOM).
pub trait Listener {
    /// Returns the name of the event
    fn kind(&self) -> ListenerKind;

    /// Handles an event firing
    fn handle(&self, event: web_sys::Event);

    /// Makes the event listener passive. See
    /// [addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener).
    fn passive(&self) -> bool;
}

impl std::fmt::Debug for dyn Listener {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Listener {{ kind: {}, passive: {:?} }}",
            self.kind().as_ref(),
            self.passive(),
        )
    }
}

macro_rules! gen_listener_kinds {
    ($($kind:ident)*) => {
        /// Supported kinds of DOM event listeners
        // Using instead of strings to optimise registry collection performance by simplifying
        // hashmap hash calculation.
        #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
        #[allow(non_camel_case_types)]
        #[allow(missing_docs)]
        pub enum ListenerKind {
            $( $kind, )*
        }

        impl AsRef<str> for ListenerKind {
            fn as_ref(&self) -> &str {
                match self {
                    $( Self::$kind => stringify!($kind), )*
                }
            }
        }
    };
}

gen_listener_kinds! {
    onabort
    onauxclick
    onblur
    oncancel
    oncanplay
    oncanplaythrough
    onchange
    onclick
    onclose
    oncontextmenu
    oncuechange
    ondblclick
    ondrag
    ondragend
    ondragenter
    ondragexit
    ondragleave
    ondragover
    ondragstart
    ondrop
    ondurationchange
    onemptied
    onended
    onerror
    onfocus
    onfocusin
    onfocusout
    onformdata
    oninput
    oninvalid
    onkeydown
    onkeypress
    onkeyup
    onload
    onloadeddata
    onloadedmetadata
    onloadstart
    onmousedown
    onmouseenter
    onmouseleave
    onmousemove
    onmouseout
    onmouseover
    onmouseup
    onpause
    onplay
    onplaying
    onprogress
    onratechange
    onreset
    onresize
    onscroll
    onsecuritypolicyviolation
    onseeked
    onseeking
    onselect
    onslotchange
    onstalled
    onsubmit
    onsuspend
    ontimeupdate
    ontoggle
    onvolumechange
    onwaiting
    onwheel
    oncopy
    oncut
    onpaste
    onanimationcancel
    onanimationend
    onanimationiteration
    onanimationstart
    ongotpointercapture
    onloadend
    onlostpointercapture
    onpointercancel
    onpointerdown
    onpointerenter
    onpointerleave
    onpointerlockchange
    onpointerlockerror
    onpointermove
    onpointerout
    onpointerover
    onpointerup
    onselectionchange
    onselectstart
    onshow
    ontouchcancel
    ontouchend
    ontouchmove
    ontouchstart
    ontransitioncancel
    ontransitionend
    ontransitionrun
    ontransitionstart
}

/// A list of event listeners
#[derive(Debug)]
pub enum Listeners {
    /// No listeners registered or pending.
    /// Distinct from `Pending` with an empty slice to avoid an allocation.
    None,

    /// Added to global registry by ID
    Registered(u32),

    /// Not yet added to the element or registry
    Pending(Box<[Option<Rc<dyn Listener>>]>),
}

impl Listeners {
    /// 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));
        }
    }
}

impl super::Apply for Listeners {
    type Element = Element;

    fn apply(&mut self, el: &Self::Element) {
        if let Self::Pending(pending) = self {
            *self = Self::register(el, pending);
        }
    }

    fn apply_diff(&mut self, el: &Self::Element, ancestor: Self) {
        use Listeners::*;

        match (std::mem::take(self), ancestor) {
            (Pending(pending), Registered(id)) => {
                // Reuse the ID
                Registry::with(|reg| reg.patch(&id, &*pending));
                *self = Registered(id);
            }
            (Pending(pending), None) => {
                *self = Self::register(el, &pending);
            }
            (None, Registered(id)) => {
                Registry::with(|reg| reg.unregister(&id));
            }
            _ => (),
        };
    }
}

impl PartialEq for Listeners {
    fn eq(&self, rhs: &Self) -> bool {
        use Listeners::*;

        match (self, rhs) {
            (None, None) => true,
            (Registered(lhs), Registered(rhs)) => lhs == rhs,
            (Registered(registered_id), Pending(pending))
            | (Pending(pending), Registered(registered_id)) => {
                use std::option::Option::None;

                Registry::with(|reg| match reg.by_id.get(registered_id) {
                    Some(reg) => {
                        if reg.len() != pending.len() {
                            return false;
                        }

                        pending.iter().filter_map(|l| l.as_ref()).all(|l| {
                            match reg.get(&EventDescriptor::from(l.deref())) {
                                Some(reg) => reg.iter().any(|reg| {
                                    #[allow(clippy::vtable_address_comparisons)]
                                    Rc::ptr_eq(reg, l)
                                }),
                                None => false,
                            }
                        })
                    }
                    None => false,
                })
            }
            (Pending(lhs), Pending(rhs)) => {
                if lhs.len() != rhs.len() {
                    false
                } else {
                    use std::option::Option::None;

                    lhs.iter()
                        .zip(rhs.iter())
                        .all(|(lhs, rhs)| match (lhs, rhs) {
                            (Some(lhs), Some(rhs)) =>
                            {
                                #[allow(clippy::vtable_address_comparisons)]
                                Rc::ptr_eq(lhs, rhs)
                            }
                            (None, None) => true,
                            _ => false,
                        })
                }
            }
            _ => false,
        }
    }
}

impl Clone for Listeners {
    fn clone(&self) -> Self {
        match self {
            Self::None | Self::Registered(_) => Self::None,
            Self::Pending(v) => Self::Pending(v.clone()),
        }
    }
}

impl Default for Listeners {
    fn default() -> Self {
        Self::None
    }
}

#[derive(Clone, Copy, 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)]
    #[allow(clippy::type_complexity)]
    registered: Vec<(ListenerKind, Closure<dyn Fn(web_sys::Event)>)>,
}

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 = BODY.with(|body| {
                let cl = Closure::wrap(
                    Box::new(move |e: Event| Registry::handle(desc, e)) as Box<dyn Fn(Event)>
                );
                AsRef::<web_sys::EventTarget>::as_ref(body)
                    .add_event_listener_with_callback_and_add_event_listener_options(
                        &desc.kind.as_ref()[2..],
                        cl.as_ref().unchecked_ref(),
                        &{
                            let mut opts = web_sys::AddEventListenerOptions::new();
                            opts.capture(true);
                            // We need to explicitly set passive to override any browser defaults
                            opts.passive(desc.passive);
                            opts
                        },
                    )
                    .map_err(|e| format!("could not register global listener: {:?}", e))
                    .unwrap();
                cl
            });

            // Never drop the closure as this event handler is static
            #[cfg(not(test))]
            cl.forget();
            #[cfg(test)]
            self.registered.push((desc.kind, cl));

            self.handling.insert(desc);
        }
    }
}

// Enable resetting between tests
#[cfg(test)]
impl Drop for GlobalHandlers {
    fn drop(&mut self) {
        BODY.with(|body| {
            for (kind, cl) in std::mem::take(&mut self.registered) {
                AsRef::<web_sys::EventTarget>::as_ref(body)
                    .remove_event_listener_with_callback(
                        &kind.as_ref()[2..],
                        cl.as_ref().unchecked_ref(),
                    )
                    .unwrap();
            }
        });
    }
}

/// 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);
            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);
                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()
            .map(|el| el.dyn_into::<web_sys::Element>().ok())
            .flatten()
        {
            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())
                .map(|v| v.dyn_into().ok())
                .flatten()
                .map(|num: js_sys::Number| {
                    Registry::with(|r| {
                        r.by_id
                            .get(&(num.value_of() as u32))
                            .map(|s| s.get(&desc))
                            .flatten()
                            .cloned()
                    })
                })
                .flatten()
            {
                for l in l {
                    l.handle(event.clone());
                }
            }
        };

        run_handler(&target);

        if unsafe { BUBBLE_EVENTS } {
            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, AppHandle, Component, Context, Html};
    use gloo_utils::document;
    use wasm_bindgen::JsCast;
    use wasm_bindgen_futures::JsFuture;

    #[derive(Clone)]
    enum Message {
        Action,
        StopListening,
        SetText(String),
    }

    #[derive(Default)]
    struct State {
        stop_listening: bool,
        action: u32,
        text: String,
    }

    trait Mixin {
        fn passive() -> Option<bool> {
            None
        }

        fn view<C>(ctx: &Context<C>, state: &State) -> Html
        where
            C: Component<Message = Message>,
        {
            if state.stop_listening {
                html! {
                    <a>{state.action}</a>
                }
            } else {
                html! {
                    <a onclick={ctx.link().callback_with_passive(
                        Self::passive(),
                        |_| Message::Action,
                    )}>
                        {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);

        (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);
        el.click();
        assert_count(&el, 2);
    }

    async fn await_animation_frame() {
        JsFuture::from(js_sys::Promise::new(&mut |resolve, _| {
            gloo_utils::window()
                .request_animation_frame(&resolve)
                .unwrap();
        }))
        .await
        .unwrap();
    }

    #[test]
    async fn passive() {
        struct Passive;

        impl Mixin for Passive {
            fn passive() -> Option<bool> {
                Some(true)
            }
        }

        assert_async::<Passive>().await;
    }

    async fn assert_async<M: Mixin + 'static>() {
        let (link, el) = init::<M>("a");

        macro_rules! assert_after_click {
            ($c:expr) => {
                el.click();
                await_animation_frame().await;
                assert_count(&el, $c);
            };
        }

        assert_count(&el, 0);

        assert_after_click!(1);

        assert_after_click!(2);

        link.send_message(Message::StopListening);
        assert_after_click!(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 onblur = ctx.link().callback(|_| Message::Action);
                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 cb = ctx.link().callback(|_| Message::Action);
                    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);
        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>,
            {
                html! {
                    <div onclick={ctx.link().callback(|_| Message::Action)}>
                        <a onclick={ctx.link().callback(|mouse_event: MouseEvent| {
                            let event: Event = mouse_event.dyn_into().unwrap();
                            event.stop_propagation();
                            Message::Action
                        })}>
                            {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>,
            {
                html! {
                    <div onclick={ctx.link().callback(|_| Message::Action)}>
                        <div onclick={ctx.link().callback(|event: MouseEvent|  {
                                event.stop_propagation();
                                Message::Action
                            })}>
                            <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 {
                    html! {
                        <div>
                            <input
                                type="text"
                                onchange={ctx.link().callback(|e: web_sys::Event| {
                                    let el: web_sys::HtmlInputElement = e.target_unchecked_into();
                                    Message::SetText(el.value())
                                })}
                                oninput={ctx.link().callback(|e: web_sys::InputEvent| {
                                    let el: web_sys::HtmlInputElement = e.target_unchecked_into();
                                    Message::SetText(el.value())
                                })}
                            />
                            <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);
                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()
        })
    }
}