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
/*!
Using event listeners with [`web-sys`](https://crates.io/crates/web-sys) is hard! This crate
provides an [`EventListener`] type which makes it easy!

See the documentation for [`EventListener`] for more information.

[`EventListener`]: struct.EventListener.html
*/
#![deny(missing_docs, missing_debug_implementations)]

use std::borrow::Cow;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::{JsCast, UnwrapThrowExt};
use web_sys::{AddEventListenerOptions, Event, EventTarget};

/// Specifies whether the event listener is run during the capture or bubble phase.
///
/// The official specification has [a good explanation](https://www.w3.org/TR/DOM-Level-3-Events/#event-flow)
/// of capturing vs bubbling.
///
/// # Default
///
/// ```rust
/// # use gloo_events::EventListenerPhase;
/// #
/// EventListenerPhase::Bubble
/// # ;
/// ```
#[derive(Debug, Clone, Copy)]
pub enum EventListenerPhase {
    #[allow(missing_docs)]
    Bubble,

    #[allow(missing_docs)]
    Capture,
}

impl EventListenerPhase {
    #[inline]
    fn is_capture(&self) -> bool {
        match self {
            EventListenerPhase::Bubble => false,
            EventListenerPhase::Capture => true,
        }
    }
}

impl Default for EventListenerPhase {
    #[inline]
    fn default() -> Self {
        EventListenerPhase::Bubble
    }
}

/// Specifies options for [`EventListener::new_with_options`](struct.EventListener.html#method.new_with_options) and
/// [`EventListener::once_with_options`](struct.EventListener.html#method.once_with_options).
///
/// # Default
///
/// ```rust
/// # use gloo_events::{EventListenerOptions, EventListenerPhase};
/// #
/// EventListenerOptions {
///     phase: EventListenerPhase::Bubble,
///     passive: true,
/// }
/// # ;
/// ```
///
/// # Examples
///
/// Sets `phase` to `EventListenerPhase::Capture`, using the default for the rest:
///
/// ```rust
/// # use gloo_events::EventListenerOptions;
/// #
/// let options = EventListenerOptions::run_in_capture_phase();
/// ```
///
/// Sets `passive` to `false`, using the default for the rest:
///
/// ```rust
/// # use gloo_events::EventListenerOptions;
/// #
/// let options = EventListenerOptions::enable_prevent_default();
/// ```
///
/// Specifies all options:
///
/// ```rust
/// # use gloo_events::{EventListenerOptions, EventListenerPhase};
/// #
/// let options = EventListenerOptions {
///     phase: EventListenerPhase::Capture,
///     passive: false,
/// };
/// ```
#[derive(Debug, Clone, Copy)]
pub struct EventListenerOptions {
    /// The phase that the event listener should be run in.
    pub phase: EventListenerPhase,

    /// If this is `true` then performance is improved, but it is not possible to use
    /// [`event.prevent_default()`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Event.html#method.prevent_default).
    ///
    /// If this is `false` then performance might be reduced, but now it is possible to use
    /// [`event.prevent_default()`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Event.html#method.prevent_default).
    ///
    /// You can read more about the performance costs
    /// [here](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Improving_scrolling_performance_with_passive_listeners).
    pub passive: bool,
}

impl EventListenerOptions {
    /// Returns an `EventListenerOptions` with `phase` set to `EventListenerPhase::Capture`.
    ///
    /// This is the same as:
    ///
    /// ```rust
    /// # use gloo_events::{EventListenerOptions, EventListenerPhase};
    /// #
    /// EventListenerOptions {
    ///     phase: EventListenerPhase::Capture,
    ///     ..Default::default()
    /// }
    /// # ;
    /// ```
    #[inline]
    pub fn run_in_capture_phase() -> Self {
        Self {
            phase: EventListenerPhase::Capture,
            ..Self::default()
        }
    }

    /// Returns an `EventListenerOptions` with `passive` set to `false`.
    ///
    /// This is the same as:
    ///
    /// ```rust
    /// # use gloo_events::EventListenerOptions;
    /// #
    /// EventListenerOptions {
    ///     passive: false,
    ///     ..Default::default()
    /// }
    /// # ;
    /// ```
    #[inline]
    pub fn enable_prevent_default() -> Self {
        Self {
            passive: false,
            ..Self::default()
        }
    }

    #[inline]
    fn as_js(&self, once: bool) -> AddEventListenerOptions {
        let mut options = AddEventListenerOptions::new();

        options.capture(self.phase.is_capture());
        options.once(once);
        options.passive(self.passive);

        options
    }
}

impl Default for EventListenerOptions {
    #[inline]
    fn default() -> Self {
        Self {
            phase: Default::default(),
            passive: true,
        }
    }
}

// This defaults passive to true to avoid performance issues in browsers:
// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Improving_scrolling_performance_with_passive_listeners
thread_local! {
    static NEW_OPTIONS: AddEventListenerOptions = EventListenerOptions::default().as_js(false);
    static ONCE_OPTIONS: AddEventListenerOptions = EventListenerOptions::default().as_js(true);
}

/// RAII type which is used to manage DOM event listeners.
///
/// When the `EventListener` is dropped, it will automatically deregister the event listener and
/// clean up the closure's memory.
///
/// Normally the `EventListener` is stored inside of another struct, like this:
///
/// ```rust
/// # use gloo_events::EventListener;
/// # use wasm_bindgen::UnwrapThrowExt;
/// use std::pin::Pin;
/// use std::task::{Context, Poll};
/// use futures::stream::Stream;
/// use futures::channel::mpsc;
/// use web_sys::EventTarget;
///
/// pub struct OnClick {
///     receiver: mpsc::UnboundedReceiver<()>,
///     // Automatically removed from the DOM on drop!
///     listener: EventListener,
/// }
///
/// impl OnClick {
///     pub fn new(target: &EventTarget) -> Self {
///         let (sender, receiver) = mpsc::unbounded();
///
///         // Attach an event listener
///         let listener = EventListener::new(&target, "click", move |_event| {
///             sender.unbounded_send(()).unwrap_throw();
///         });
///
///         Self {
///             receiver,
///             listener,
///         }
///     }
/// }
///
/// impl Stream for OnClick {
///     type Item = ();
///
///     fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
///         Pin::new(&mut self.receiver).poll_next(cx)
///     }
/// }
/// ```
#[derive(Debug)]
#[must_use = "event listener will never be called after being dropped"]
pub struct EventListener {
    target: EventTarget,
    event_type: Cow<'static, str>,
    callback: Option<Closure<dyn FnMut(&Event)>>,
    phase: EventListenerPhase,
}

impl EventListener {
    #[inline]
    fn raw_new(
        target: &EventTarget,
        event_type: Cow<'static, str>,
        callback: Closure<dyn FnMut(&Event)>,
        options: &AddEventListenerOptions,
        phase: EventListenerPhase,
    ) -> Self {
        target
            .add_event_listener_with_callback_and_add_event_listener_options(
                &event_type,
                callback.as_ref().unchecked_ref(),
                options,
            )
            .unwrap_throw();

        Self {
            target: target.clone(),
            event_type,
            callback: Some(callback),
            phase,
        }
    }

    /// Registers an event listener on an [`EventTarget`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.EventTarget.html).
    ///
    /// For specifying options, there is a corresponding [`EventListener::new_with_options`](#method.new_with_options) method.
    ///
    /// If you only need the event to fire once, you can use [`EventListener::once`](#method.once) instead,
    /// which accepts an `FnOnce` closure.
    ///
    /// # Event type
    ///
    /// The event type can be either a `&'static str` like `"click"`, or it can be a dynamically constructed `String`.
    ///
    /// All event types are supported. Here is a [partial list](https://developer.mozilla.org/en-US/docs/Web/Events) of the available event types.
    ///
    /// # Passive
    ///
    /// [For performance reasons](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Improving_scrolling_performance_with_passive_listeners),
    /// it is not possible to use [`event.prevent_default()`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Event.html#method.prevent_default).
    ///
    /// If you need to use `prevent_default`, you must use [`EventListener::new_with_options`](#method.new_with_options), like this:
    ///
    /// ```rust,no_run
    /// # use gloo_events::{EventListener, EventListenerOptions};
    /// # let target = unimplemented!();
    /// # let event_type = "click";
    /// # fn callback(_: &web_sys::Event) {}
    /// #
    /// let options = EventListenerOptions::enable_prevent_default();
    ///
    /// EventListener::new_with_options(target, event_type, options, callback)
    /// # ;
    /// ```
    ///
    /// # Capture
    ///
    /// By default, event listeners are run in the bubble phase, *not* the capture phase. The official specification has
    /// [a good explanation](https://www.w3.org/TR/DOM-Level-3-Events/#event-flow) of capturing vs bubbling.
    ///
    /// If you want it to run in the capture phase, you must use [`EventListener::new_with_options`](#method.new_with_options), like this:
    ///
    /// ```rust,no_run
    /// # use gloo_events::{EventListener, EventListenerOptions};
    /// # let target = unimplemented!();
    /// # let event_type = "click";
    /// # fn callback(_: &web_sys::Event) {}
    /// #
    /// // This runs the event listener in the capture phase, rather than the bubble phase
    /// let options = EventListenerOptions::run_in_capture_phase();
    ///
    /// EventListener::new_with_options(target, event_type, options, callback)
    /// # ;
    /// ```
    ///
    /// # Examples
    ///
    /// Registers a [`"click"`](https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event) event and downcasts it to the correct `Event` subtype
    /// (which is [`MouseEvent`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.MouseEvent.html)):
    ///
    /// ```rust,no_run
    /// # use gloo_events::EventListener;
    /// # use wasm_bindgen::{JsCast, UnwrapThrowExt};
    /// # let target = unimplemented!();
    /// #
    /// let listener = EventListener::new(&target, "click", move |event| {
    ///     let event = event.dyn_ref::<web_sys::MouseEvent>().unwrap_throw();
    ///
    ///     // ...
    /// });
    /// ```
    #[inline]
    pub fn new<S, F>(target: &EventTarget, event_type: S, callback: F) -> Self
    where
        S: Into<Cow<'static, str>>,
        F: FnMut(&Event) + 'static,
    {
        let callback = Closure::wrap(Box::new(callback) as Box<dyn FnMut(&Event)>);

        NEW_OPTIONS.with(move |options| {
            Self::raw_new(
                target,
                event_type.into(),
                callback,
                options,
                EventListenerPhase::Bubble,
            )
        })
    }

    /// This is exactly the same as [`EventListener::new`](#method.new), except the event will only fire once,
    /// and it accepts `FnOnce` instead of `FnMut`.
    ///
    /// For specifying options, there is a corresponding [`EventListener::once_with_options`](#method.once_with_options) method.
    ///
    /// # Examples
    ///
    /// Registers a [`"load"`](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/load_event) event and casts it to the correct type
    /// (which is [`ProgressEvent`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.ProgressEvent.html)):
    ///
    /// ```rust,no_run
    /// # use gloo_events::EventListener;
    /// # use wasm_bindgen::{JsCast, UnwrapThrowExt};
    /// # let target = unimplemented!();
    /// #
    /// let listener = EventListener::once(&target, "load", move |event| {
    ///     let event = event.dyn_ref::<web_sys::ProgressEvent>().unwrap_throw();
    ///
    ///     // ...
    /// });
    /// ```
    #[inline]
    pub fn once<S, F>(target: &EventTarget, event_type: S, callback: F) -> Self
    where
        S: Into<Cow<'static, str>>,
        F: FnOnce(&Event) + 'static,
    {
        let callback = Closure::once(callback);

        ONCE_OPTIONS.with(move |options| {
            Self::raw_new(
                target,
                event_type.into(),
                callback,
                options,
                EventListenerPhase::Bubble,
            )
        })
    }

    /// Registers an event listener on an [`EventTarget`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.EventTarget.html).
    ///
    /// It is recommended to use [`EventListener::new`](#method.new) instead, because it has better performance, and it is more convenient.
    ///
    /// If you only need the event to fire once, you can use [`EventListener::once_with_options`](#method.once_with_options) instead,
    /// which accepts an `FnOnce` closure.
    ///
    /// # Event type
    ///
    /// The event type can be either a `&'static str` like `"click"`, or it can be a dynamically constructed `String`.
    ///
    /// All event types are supported. Here is a [partial list](https://developer.mozilla.org/en-US/docs/Web/Events)
    /// of the available event types.
    ///
    /// # Options
    ///
    /// See the documentation for [`EventListenerOptions`](struct.EventListenerOptions.html) for more details.
    ///
    /// # Examples
    ///
    /// Registers a [`"touchstart"`](https://developer.mozilla.org/en-US/docs/Web/API/Element/touchstart_event)
    /// event and uses
    /// [`event.prevent_default()`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Event.html#method.prevent_default):
    ///
    /// ```rust,no_run
    /// # use gloo_events::{EventListener, EventListenerOptions};
    /// # let target = unimplemented!();
    /// #
    /// let options = EventListenerOptions::enable_prevent_default();
    ///
    /// let listener = EventListener::new_with_options(&target, "touchstart", options, move |event| {
    ///     event.prevent_default();
    ///
    ///     // ...
    /// });
    /// ```
    ///
    /// Registers a [`"click"`](https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event)
    /// event in the capturing phase and uses
    /// [`event.stop_propagation()`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Event.html#method.stop_propagation)
    /// to stop the event from bubbling:
    ///
    /// ```rust,no_run
    /// # use gloo_events::{EventListener, EventListenerOptions};
    /// # let target = unimplemented!();
    /// #
    /// let options = EventListenerOptions::run_in_capture_phase();
    ///
    /// let listener = EventListener::new_with_options(&target, "click", options, move |event| {
    ///     // Stop the event from bubbling
    ///     event.stop_propagation();
    ///
    ///     // ...
    /// });
    /// ```
    #[inline]
    pub fn new_with_options<S, F>(
        target: &EventTarget,
        event_type: S,
        options: EventListenerOptions,
        callback: F,
    ) -> Self
    where
        S: Into<Cow<'static, str>>,
        F: FnMut(&Event) + 'static,
    {
        let callback = Closure::wrap(Box::new(callback) as Box<dyn FnMut(&Event)>);

        Self::raw_new(
            target,
            event_type.into(),
            callback,
            &options.as_js(false),
            options.phase,
        )
    }

    /// This is exactly the same as [`EventListener::new_with_options`](#method.new_with_options), except the event will only fire once,
    /// and it accepts `FnOnce` instead of `FnMut`.
    ///
    /// It is recommended to use [`EventListener::once`](#method.once) instead, because it has better performance, and it is more convenient.
    ///
    /// # Examples
    ///
    /// Registers a [`"load"`](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/load_event)
    /// event and uses
    /// [`event.prevent_default()`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Event.html#method.prevent_default):
    ///
    /// ```rust,no_run
    /// # use gloo_events::{EventListener, EventListenerOptions};
    /// # let target = unimplemented!();
    /// #
    /// let options = EventListenerOptions::enable_prevent_default();
    ///
    /// let listener = EventListener::once_with_options(&target, "load", options, move |event| {
    ///     event.prevent_default();
    ///
    ///     // ...
    /// });
    /// ```
    ///
    /// Registers a [`"click"`](https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event)
    /// event in the capturing phase and uses
    /// [`event.stop_propagation()`](https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Event.html#method.stop_propagation)
    /// to stop the event from bubbling:
    ///
    /// ```rust,no_run
    /// # use gloo_events::{EventListener, EventListenerOptions};
    /// # let target = unimplemented!();
    /// #
    /// let options = EventListenerOptions::run_in_capture_phase();
    ///
    /// let listener = EventListener::once_with_options(&target, "click", options, move |event| {
    ///     // Stop the event from bubbling
    ///     event.stop_propagation();
    ///
    ///     // ...
    /// });
    /// ```
    #[inline]
    pub fn once_with_options<S, F>(
        target: &EventTarget,
        event_type: S,
        options: EventListenerOptions,
        callback: F,
    ) -> Self
    where
        S: Into<Cow<'static, str>>,
        F: FnOnce(&Event) + 'static,
    {
        let callback = Closure::once(callback);

        Self::raw_new(
            target,
            event_type.into(),
            callback,
            &options.as_js(true),
            options.phase,
        )
    }

    /// Keeps the `EventListener` alive forever, so it will never be dropped.
    ///
    /// This should only be used when you want the `EventListener` to last forever, otherwise it will leak memory!
    #[inline]
    pub fn forget(mut self) {
        // take() is necessary because of Rust's restrictions about Drop
        // This will never panic, because `callback` is always `Some`
        self.callback.take().unwrap_throw().forget()
    }

    /// Returns the `EventTarget`.
    #[inline]
    pub fn target(&self) -> &EventTarget {
        &self.target
    }

    /// Returns the event type.
    #[inline]
    pub fn event_type(&self) -> &str {
        &self.event_type
    }

    /// Returns the callback.
    #[inline]
    pub fn callback(&self) -> &Closure<dyn FnMut(&Event)> {
        // This will never panic, because `callback` is always `Some`
        self.callback.as_ref().unwrap_throw()
    }

    /// Returns whether the event listener is run during the capture or bubble phase.
    ///
    /// The official specification has [a good explanation](https://www.w3.org/TR/DOM-Level-3-Events/#event-flow)
    /// of capturing vs bubbling.
    #[inline]
    pub fn phase(&self) -> EventListenerPhase {
        self.phase
    }
}

impl Drop for EventListener {
    #[inline]
    fn drop(&mut self) {
        // This will only be None if forget() was called
        if let Some(callback) = &self.callback {
            self.target
                .remove_event_listener_with_callback_and_bool(
                    self.event_type(),
                    callback.as_ref().unchecked_ref(),
                    self.phase.is_capture(),
                )
                .unwrap_throw();
        }
    }
}