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
use discard::DiscardOnDrop;
use futures_signals::{cancelable_future, CancelableFutureHandle};
use wasm_bindgen_futures::spawn_local;
use std::future::Future;

/// Makes it easier to spawn and cancel a future-signal
/// Copied with permission from Dominator's pub(crate) function
#[inline]
pub fn spawn_future<F>(future: F) -> DiscardOnDrop<CancelableFutureHandle>
    where F: Future<Output = ()> + 'static {
    let (handle, future) = cancelable_future(future, || ());

    spawn_local(future);

    handle
}

/// pass in a HtmlElement
#[macro_export]
macro_rules! elem {
    ($elem:expr, { $($methods:tt)* }) => {
        dominator::apply_methods!(dominator::DomBuilder::new($elem), { $($methods)* }).into_dom()
    };
}

/// example:
/// .with_data_id!("status", {
///     .event(...)
#[macro_export]
macro_rules! with_data_id {
    ($this:ident, $id:expr, { $($methods:tt)* }) => {
        dominator::with_node!($this, element => {
            .__internal_transfer_callbacks({
                let child = element.query_selector(&format!("[data-id='{}']", $id)).unwrap_throw().unwrap_throw();
                dominator::apply_methods!(dominator::DomBuilder::new(child), { $($methods)* })
            })
        })
    };
}


/// example:
/// .with_query!("[data-id='status']", {
///     .event(...)
#[macro_export]
macro_rules! with_query {
    ($this:ident, $query:expr, { $($methods:tt)* }) => {
        dominator::with_node!($this, element => {
            .__internal_transfer_callbacks({
                let child = element.query_selector($query).unwrap_throw().unwrap_throw();
                dominator::apply_methods!(dominator::DomBuilder::new(child), { $($methods)* })
            })
        })
    };
}

/// simple helper for adding Dom to a slot
//e.g. this will create the "todo-input" element with its "slot" attribute set to "input"
// html_at_slot!("todo-input", "input", { ... }
#[macro_export]
macro_rules! html_at_slot {
    ($name:expr, $slot:expr, { $($rest:tt)* }) => {
        dominator::html!($name, {
            .attribute("slot", $slot)
            $($rest)*
        })
    };
}

/**** NOTE! The event macros rely on dominator exporting make_event which isn't done yet! ****/

/// takes a literal and an ident and does the following:
/// 1. impls what's needed for dominator
/// 2. calls make_custom_event_serde! to enable the .data() helper (also for dominator)
/// 3. creates a function for testing the round-tripping from typescript (when ts_test feature is enabled)

#[macro_export]
macro_rules! make_ts_event {
    ($literal:literal, $data:ident) => {
        paste::item! {
            make_custom_event_serde!($literal, [<$data Event>], $data);
            cfg_if::cfg_if! {
                if #[cfg(feature = "ts_test")] {

                    use web_sys::CustomEvent;
                    use wasm_bindgen::prelude::*;

                    #[wasm_bindgen]
                    pub fn [<check_rust_event_ $data>](event:CustomEvent) -> Result<JsValue, JsValue> {
                        let literal = event.type_();
                        let event:[<$data Event>] = unsafe {
                            std::mem::transmute::<CustomEvent, [<$data Event>]>(event)
                        };

                        if literal == $literal {
                            let data:$data = event.data(); 
                            let expected = serde_json::to_string(&$data::default()).unwrap();
                            let got = serde_json::to_string(&data).unwrap();
                            if expected != got {
                                Err(JsValue::from_str(&format!("did not match default! should be {} but is {}", expected, got)))
                            } else {
                                Ok(JsValue::from_str(&got))
                            }
                        } else {
                            Err(JsValue::from_str(&format!("wrong type! should be {} but is {}", $literal, literal)))
                        }
                    }
                }
            }
        }
    }
}

#[macro_export]
macro_rules! make_custom_event {
    ($name:ident, $type:literal) => {
        dominator::make_event!($name, $type => web_sys::CustomEvent);
        impl $name {
            pub fn detail(&self) -> JsValue { self.event.detail() }
        }
    }
}

/// first arg is name of the new struct to create
/// second arg is literal name of the event
/// third arg is the data structure. 
/// 
/// the data structure needs to already be defined and derive `Deserialize`
/// 
/// requires that the serde_wasm_bindgen crate be installed 
/// however, since this is only a macro, there's no need to feature-gate it here
/// Example:
/// 
/// JS (e.g. from a CustomElement)
/// 
/// ```javascript
/// this.dispatchEvent(new CustomEvent('todo-input', {
///     detail: {label: value}
/// }));
/// ```
/// 
/// Rust - first register the event
/// 
/// ```rust
/// 
/// #[derive(Deserialize)]
/// pub struct TodoInputEventData {
///     pub label: String 
/// }
/// make_custom_event_serde!("todo-input", TodoInputEvent, TodoInputEventData);
/// ``` 
/// 
/// then use it
///
/// ```
/// html!("todo-custom", {
///     .event(|event:TodoInputEvent| {
///         //event.data() is a TodoInputEventData
///         let label:&str = event.data().label;
///     })
/// })
/// ```
#[macro_export]
macro_rules! make_custom_event_serde {
    ($type:literal, $name:ident, $data:ident) => {
        make_custom_event!($name, $type);
        impl $name {
            pub fn data(&self) -> $data { 
                serde_wasm_bindgen::from_value(self.detail()).unwrap()
            }
        }
    }
}