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
use crate::{
    dom::Dispatch,
    mt_dom::{AttValue, Callback},
    prelude::AttributeValue,
    Attribute, Event,
};
use std::ops::Deref;
use std::{collections::HashMap, fmt::Write, sync::Mutex};
use wasm_bindgen::{closure::Closure, JsCast};
use web_sys::{
    self, Element, EventTarget, HtmlInputElement, HtmlTextAreaElement, Node,
    Text,
};

// Used to uniquely identify elements that contain closures so that the DomUpdater can
// look them up by their unique id.
// When the DomUpdater sees that the element no longer exists it will drop all of it's
// Rc'd Closures for those events.
use lazy_static::lazy_static;
lazy_static! {
    /// This is the value of the data-sauron-vdom-id.
    static ref DATA_SAURON_VDOM_ID_VALUE: Mutex<u32> = Mutex::new(0);
}

fn create_unique_identifier() -> u32 {
    let mut elem_unique_id = DATA_SAURON_VDOM_ID_VALUE
        .lock()
        .expect("Unable to obtain lock");
    *elem_unique_id += 1;
    *elem_unique_id
}

pub(crate) const DATA_SAURON_VDOM_ID: &str = "data-sauron-vdom-id";

/// Closures that we are holding on to to make sure that they don't get invalidated after a
/// VirtualNode is dropped.
///
/// The u32 is a unique identifier that is associated with the DOM element that this closure is
/// attached to.
///
pub type ActiveClosure =
    HashMap<u32, Vec<(&'static str, Closure<dyn FnMut(web_sys::Event)>)>>;

/// A node along with all of the closures that were created for that
/// node's events and all of it's child node's events.
#[derive(Debug)]
pub struct CreatedNode<T> {
    /// A `Node` or `Element` that was created from a `Node`
    pub node: T,
    pub(crate) closures: ActiveClosure,
}

impl<T> CreatedNode<T> {
    /// create a simple node with no closure attache
    pub fn without_closures<N: Into<T>>(node: N) -> Self {
        CreatedNode {
            node: node.into(),
            closures: HashMap::with_capacity(0),
        }
    }

    /// create a text node
    pub fn create_text_node(text: &str) -> Text {
        crate::document().create_text_node(text)
    }

    /// create an element node
    pub fn create_dom_node<DSP, MSG>(
        program: &DSP,
        vnode: &crate::Node<MSG>,
    ) -> CreatedNode<Node>
    where
        MSG: 'static,
        DSP: Clone + Dispatch<MSG> + 'static,
    {
        Self::create_dom_node_opt(Some(program), vnode)
    }

    /// Create and return a `CreatedNode` instance (containing a DOM `Node`
    /// together with potentially related closures) for this virtual node.
    pub fn create_dom_node_opt<DSP, MSG>(
        program: Option<&DSP>,
        vnode: &crate::Node<MSG>,
    ) -> CreatedNode<Node>
    where
        MSG: 'static,
        DSP: Clone + Dispatch<MSG> + 'static,
    {
        match vnode {
            crate::Node::Text(text_node) => {
                CreatedNode::without_closures(Self::create_text_node(text_node))
            }
            crate::Node::Element(element_node) => {
                let created_element: CreatedNode<Node> =
                    Self::create_element_node(program, element_node).into();
                created_element
            }
        }
    }

    /// merge the plain values
    fn merge_plain_attributes_values(
        attr_values: &[&AttributeValue],
    ) -> Option<String> {
        let plain_values: Vec<String> = attr_values
            .iter()
            .flat_map(|att_value| match att_value {
                AttributeValue::Simple(simple) => Some(simple.to_string()),
                AttributeValue::Style(styles) => {
                    let mut style_str = String::new();
                    styles.iter().for_each(|s| {
                        write!(style_str, "{};", s).expect("must write")
                    });
                    Some(style_str)
                }
                AttributeValue::FunctionCall(fvalue) => {
                    Some(fvalue.to_string())
                }
                AttributeValue::Empty => None,
            })
            .collect();
        if !plain_values.is_empty() {
            Some(plain_values.join(" "))
        } else {
            None
        }
    }

    /// returns (callbacks, plain_attribtues, function_calls)
    fn partition_callbacks_from_plain_and_func_calls<MSG>(
        attr: &Attribute<MSG>,
    ) -> (
        Vec<&Callback<Event, MSG>>,
        Vec<&AttributeValue>,
        Vec<&AttributeValue>,
    ) {
        let mut callbacks = vec![];
        let mut plain_values = vec![];
        let mut func_values = vec![];
        for av in attr.value() {
            match av {
                AttValue::Plain(plain) => {
                    if plain.is_function_call() {
                        func_values.push(plain);
                    } else {
                        plain_values.push(plain);
                    }
                }
                AttValue::Callback(cb) => callbacks.push(cb),
            }
        }
        (callbacks, plain_values, func_values)
    }

    /// set the element attribute
    pub fn set_element_attributes<DSP, MSG>(
        program: Option<&DSP>,
        closures: &mut ActiveClosure,
        element: &Element,
        attrs: &[&Attribute<MSG>],
    ) where
        MSG: 'static,
        DSP: Clone + Dispatch<MSG> + 'static,
    {
        let attrs = mt_dom::merge_attributes_of_same_name(attrs);
        for att in attrs {
            Self::set_element_attribute(program, closures, element, &att);
        }
    }

    /// set the element attribute
    pub fn set_element_attribute<DSP, MSG>(
        program: Option<&DSP>,
        closures: &mut ActiveClosure,
        element: &Element,
        attr: &Attribute<MSG>,
    ) where
        MSG: 'static,
        DSP: Clone + Dispatch<MSG> + 'static,
    {
        let (callbacks, plain_values, func_values) =
            Self::partition_callbacks_from_plain_and_func_calls(attr);

        // set simple values
        if let Some(merged_plain_values) =
            Self::merge_plain_attributes_values(&plain_values)
        {
            if let Some(ref namespace) = attr.namespace() {
                // Warning NOTE: set_attribute_ns should only be called
                // when you meant to use a namespace
                // using this with None will error in the browser with:
                // NamespaceError: An attempt was made to create or change an object in a way which is incorrect with regard to namespaces
                element
                    .set_attribute_ns(
                        Some(namespace),
                        attr.name(),
                        &merged_plain_values,
                    )
                    .expect("Set element attribute_ns in create element");
            } else {
                match *attr.name() {
                    "value" => {
                        if let Some(input) =
                            element.dyn_ref::<HtmlInputElement>()
                        {
                            input.set_value(&merged_plain_values);
                        } else if let Some(textarea) =
                            element.dyn_ref::<HtmlTextAreaElement>()
                        {
                            textarea.set_value(&merged_plain_values);
                        }
                    }
                    "checked" => {
                        if let Some(input) =
                            element.dyn_ref::<HtmlInputElement>()
                        {
                            let checked = plain_values
                                .first()
                                .map(|av| {
                                    av.get_simple()
                                        .expect("must be a simple value")
                                })
                                .unwrap()
                                .to_string();
                            if !checked.is_empty() {
                                input.set_checked(true);
                            }
                        }
                    }
                    _ => {
                        element
                            .set_attribute(attr.name(), &merged_plain_values)
                            .expect("Set element attribute in create element");
                    }
                }
            }
        }

        // do function calls such as set_inner_html
        if let Some(merged_func_values) =
            Self::merge_plain_attributes_values(&func_values)
        {
            match *attr.name() {
                "inner_html" => element.set_inner_html(&merged_func_values),
                _ => (),
            }
        }

        // add callbacks using add_event_listener
        for callback in callbacks {
            let unique_id = create_unique_identifier();

            // set the data-sauron_vdom-id this will be read later on
            // when it's time to remove this element and its closures and event listeners
            element
                .set_attribute(DATA_SAURON_VDOM_ID, &unique_id.to_string())
                .expect("Could not set attribute on element");

            closures.insert(unique_id, vec![]);

            if let Some(program) = program {
                let event_str = attr.name();
                let current_elm: &EventTarget =
                    element.dyn_ref().expect("unable to cast to event targe");
                let closure_wrap: Closure<dyn FnMut(web_sys::Event)> =
                    create_closure_wrap(program, &callback);
                current_elm
                    .add_event_listener_with_callback(
                        event_str,
                        closure_wrap.as_ref().unchecked_ref(),
                    )
                    .expect("Unable to attached event listener");
                closures
                    .get_mut(&unique_id)
                    .expect("Unable to get closure")
                    .push((event_str, closure_wrap));
            }
        }
    }

    /// Build a DOM element by recursively creating DOM nodes for this element and it's
    /// children, it's children's children, etc.
    pub fn create_element_node<DSP, MSG>(
        program: Option<&DSP>,
        velem: &crate::Element<MSG>,
    ) -> CreatedNode<Element>
    where
        MSG: 'static,
        DSP: Clone + Dispatch<MSG> + 'static,
    {
        let document = crate::document();

        let element = if let Some(ref namespace) = velem.namespace() {
            document
                .create_element_ns(Some(namespace), &velem.tag())
                .expect("Unable to create element")
        } else {
            document
                .create_element(&velem.tag())
                .expect("Unable to create element")
        };

        let mut closures = ActiveClosure::new();

        // TODO: attributes can be further merge here so as not to override the previous value
        // when there are more than 1 attributes of the same name in an element
        Self::set_element_attributes(
            program,
            &mut closures,
            &element,
            &velem.get_attributes().iter().collect::<Vec<_>>(),
        );

        let mut previous_node_was_text = false;
        for child in velem.get_children().iter() {
            match child {
                crate::Node::Text(text_node) => {
                    let current_node: &web_sys::Node = element.as_ref();

                    // We ensure that the text siblings are patched by preventing the browser from merging
                    // neighboring text nodes. Originally inspired by some of React's work from 2016.
                    //  -> https://reactjs.org/blog/2016/04/07/react-v15.html#major-changes
                    //  -> https://github.com/facebook/react/pull/5753
                    //
                    // `mordor` one does not simply walk into mordor
                    if previous_node_was_text {
                        let separator = document.create_comment("mordor");
                        current_node
                            .append_child(separator.as_ref())
                            .expect("Unable to append child");
                    }

                    current_node
                        .append_child(&Self::create_text_node(&text_node))
                        .expect("Unable to append text node");

                    previous_node_was_text = true;
                }
                crate::Node::Element(element_node) => {
                    previous_node_was_text = false;

                    let child =
                        Self::create_element_node(program, element_node);
                    let child_elem: Element = child.node;
                    closures.extend(child.closures);

                    element
                        .append_child(&child_elem)
                        .expect("Unable to append element node");
                }
            }
        }

        CreatedNode {
            node: element,
            closures,
        }
    }
}

/// This wrap into a closure the function that is dispatched when the event is triggered.
pub(crate) fn create_closure_wrap<DSP, MSG>(
    program: &DSP,
    callback: &Callback<crate::Event, MSG>,
) -> Closure<dyn FnMut(web_sys::Event)>
where
    MSG: 'static,
    DSP: Clone + Dispatch<MSG> + 'static,
{
    let callback_clone = callback.clone();
    // TODO: use a weak pointer here
    // let program_weak = Rc::downgrade(&program)
    let program_clone = program.clone();

    Closure::wrap(Box::new(move |event: web_sys::Event| {
        // FIXME: need to allow users to control this
        // Note:
        // calling `event.stop_propagation()` to the containers of this element to have
        // a more fine grain control and expected results,
        // and for most cases this is what we want. We don't want the containing div of a button
        // also receives that click event.
        //event.stop_propagation();
        // FIXME: need to allow users control this
        //
        // Notes:
        // - calling event.prevent_default() prevents the reloading the page in href links, which is what we
        // want mostly in an SPA app
        // - calling event.prevent_default() prevent InputEvent to trigger when KeyPressEvent is
        // also one of the event callback
        // event.prevent_default();
        let msg = callback_clone.emit(event);
        program_clone.dispatch(msg);
    }))
}

impl From<CreatedNode<Element>> for CreatedNode<Node> {
    fn from(other: CreatedNode<Element>) -> CreatedNode<Node> {
        CreatedNode {
            node: other.node.into(),
            closures: other.closures,
        }
    }
}

impl<T> Deref for CreatedNode<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.node
    }
}