dioxus_web_component/
event.rs

1use dioxus::logger::tracing::debug;
2use dioxus::prelude::EventHandler;
3use wasm_bindgen::{JsValue, UnwrapThrowExt};
4use web_sys::{CustomEvent, EventTarget};
5
6/// HTML custom event options
7///
8/// See [MDN - custom event](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent)
9///
10/// Note that by default `can_bubble` & `cancelable` are `true`
11#[derive(Clone, Copy)]
12pub struct CustomEventOptions {
13    /// Is the event bubble up through the DOM tree
14    ///
15    /// See [MDN - bubbles](https://developer.mozilla.org/en-US/docs/Web/API/Event/bubbles)
16    pub can_bubble: bool,
17
18    /// Is the event is cancelable
19    ///
20    /// See [MDN - cancelable](https://developer.mozilla.org/en-US/docs/Web/API/Event/cancelable)
21    pub cancelable: bool,
22}
23
24impl Default for CustomEventOptions {
25    fn default() -> Self {
26        Self {
27            can_bubble: true,
28            cancelable: true,
29        }
30    }
31}
32
33/// Create a Dioxus event handler that send an HTML custom event
34pub fn custom_event_handler<T>(
35    target: impl AsRef<EventTarget> + 'static,
36    event_type: &'static str,
37    options: CustomEventOptions,
38) -> EventHandler<T>
39where
40    T: Into<JsValue> + 'static,
41{
42    EventHandler::new(move |value: T| {
43        let CustomEventOptions {
44            can_bubble,
45            cancelable,
46        } = options;
47        let event = CustomEvent::new(event_type).unwrap_throw();
48        let detail = value.into();
49        event.init_custom_event_with_can_bubble_and_cancelable_and_detail(
50            event_type, can_bubble, cancelable, &detail,
51        );
52        debug!(?event, "dispatch event");
53        let target = target.as_ref();
54        target.dispatch_event(&event).unwrap_throw();
55    })
56}