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
//! provides functionalities related to patching the DOM in the browser.
use crate::{
    dom::{
        created_node,
        created_node::{ActiveClosure, CreatedNode},
    },
    html::attributes::AttributeValue,
    mt_dom::patch::{
        AddAttributes, AppendChildren, InsertNode, RemoveAttributes,
        RemoveNode, ReplaceNode,
    },
    Dispatch, Patch,
};
use js_sys::Function;
use std::collections::BTreeMap;
use std::collections::HashMap;
use wasm_bindgen::{JsCast, JsValue};
use web_sys::{Element, Node};

/// Apply all of the patches to our old root node in order to create the new root node
/// that we desire.
/// This is usually used after diffing two virtual nodes.
///
/// Note: If Program is None, it is a dumb patch, meaning
/// there is no event listener attached or changed
pub fn patch<DSP, MSG>(
    program: &DSP,
    root_node: &mut Node,
    old_closures: &mut ActiveClosure,
    focused_node: &mut Option<Node>,
    patches: Vec<Patch<MSG>>,
) -> Result<ActiveClosure, JsValue>
where
    MSG: 'static,
    DSP: Clone + Dispatch<MSG> + 'static,
{
    patch_by_traversal_path(
        program,
        root_node,
        old_closures,
        focused_node,
        patches,
    )
}

/// patch using the tree path traversal instead of node_idx
pub fn patch_by_traversal_path<DSP, MSG>(
    program: &DSP,
    root_node: &mut Node,
    old_closures: &mut ActiveClosure,
    focused_node: &mut Option<Node>,
    patches: Vec<Patch<MSG>>,
) -> Result<ActiveClosure, JsValue>
where
    MSG: 'static,
    DSP: Clone + Dispatch<MSG> + 'static,
{
    let nodes_to_find: Vec<(&[usize], Option<&&'static str>)> = patches
        .iter()
        .map(|patch| (patch.path(), patch.tag()))
        .collect();

    let mut paths = vec![];
    for patch in patches.iter() {
        paths.push(patch.path());
    }

    let mut active_closures = HashMap::new();
    let nodes_to_patch =
        find_all_nodes_by_path(root_node.clone(), &nodes_to_find);

    for patch in patches.iter() {
        let patch_path = patch.path();
        if let Some(element) = nodes_to_patch.get(patch_path) {
            let new_closures = apply_patch_to_node(
                program,
                root_node,
                element,
                old_closures,
                focused_node,
                patch,
            )?;
            active_closures.extend(new_closures);
        } else {
            unreachable!("Getting here means we didn't find the element of next node that we are supposed to patch, patch_path: {:?}", patch_path);
        }
    }

    Ok(active_closures)
}

fn find_node_by_path_recursive(
    node: Node,
    path: &mut Vec<usize>,
) -> Option<Node> {
    if path.is_empty() {
        Some(node)
    } else {
        let idx = path.remove(0);
        let children = node.child_nodes();
        if let Some(child) = children.item(idx as u32) {
            find_node_by_path_recursive(child, path)
        } else {
            None
        }
    }
}

fn find_all_nodes_by_path(
    node: Node,
    nodes_to_find: &[(&[usize], Option<&&'static str>)],
) -> BTreeMap<Vec<usize>, Node> {
    let mut nodes_to_patch: BTreeMap<Vec<usize>, Node> = BTreeMap::new();

    for (path, tag) in nodes_to_find {
        let mut traverse_path = path.to_vec();
        let root_idx = traverse_path.remove(0);
        assert_eq!(0, root_idx, "path should start at 0");
        if let Some(found) =
            find_node_by_path_recursive(node.clone(), &mut traverse_path)
        {
            nodes_to_patch.insert(path.to_vec(), found);
        } else {
            log::warn!("can not find: {:?} {:?}", path, tag);
        }
    }
    nodes_to_patch
}

/// Get the "data-sauron-vdom-id" of all the desendent of this node including itself
/// This is needed to free-up the closure that was attached ActiveClosure manually
fn get_node_descendant_data_vdom_id(root_element: &Element) -> Vec<usize> {
    let mut data_vdom_id = vec![];

    // TODO: there should be a better way to get the node-id back
    // without having to read from the actual dom node element
    if let Some(vdom_id_str) =
        root_element.get_attribute(created_node::DATA_VDOM_ID)
    {
        let vdom_id = vdom_id_str
            .parse::<usize>()
            .expect("unable to parse sauron_vdom-id");
        data_vdom_id.push(vdom_id);
    }

    let children = root_element.child_nodes();
    let child_node_count = children.length();
    for i in 0..child_node_count {
        let child_node = children.item(i).expect("Expecting a child node");
        if child_node.node_type() == Node::ELEMENT_NODE {
            let child_element = child_node.unchecked_ref::<Element>();
            let child_data_vdom_id =
                get_node_descendant_data_vdom_id(child_element);
            data_vdom_id.extend(child_data_vdom_id);
        }
    }
    data_vdom_id
}

/// remove all the event listeners for this node
fn remove_event_listeners(
    node: &Element,
    old_closures: &mut ActiveClosure,
) -> Result<(), JsValue> {
    let all_descendant_vdom_id = get_node_descendant_data_vdom_id(node);
    for vdom_id in all_descendant_vdom_id {
        if let Some(old_closure) = old_closures.get(&vdom_id) {
            for (event, oc) in old_closure.iter() {
                let func: &Function = oc.as_ref().unchecked_ref();
                node.remove_event_listener_with_callback(event, func)?;
            }

            // remove closure active_closure in dom_updater to free up memory
            old_closures
                .remove(&vdom_id)
                .expect("Unable to remove old closure");
        } else {
            log::warn!(
                "There is no closure marked with that vdom_id: {}",
                vdom_id
            );
        }
    }
    Ok(())
}

/// remove the event listener which matches the given event name
fn remove_event_listener_with_name(
    event_name: &'static str,
    node: &Element,
    old_closures: &mut ActiveClosure,
) -> Result<(), JsValue> {
    let all_descendant_vdom_id = get_node_descendant_data_vdom_id(node);
    for vdom_id in all_descendant_vdom_id {
        if let Some(old_closure) = old_closures.get_mut(&vdom_id) {
            for (event, oc) in old_closure.iter() {
                if *event == event_name {
                    let func: &Function = oc.as_ref().unchecked_ref();
                    node.remove_event_listener_with_callback(event, func)?;
                }
            }

            old_closure.retain(|(event, _oc)| *event != event_name);

            // remove closure active_closure in dom_updater to free up memory
            if old_closure.is_empty() {
                old_closures
                    .remove(&vdom_id)
                    .expect("Unable to remove old closure");
            }
        } else {
            log::warn!(
                "There is no closure marked with that vdom_id: {}",
                vdom_id
            );
        }
    }
    Ok(())
}

/// apply a the patch to this element node.
/// and return the ActiveClosure that may be attached to that element
///
/// Note: a mutable root_node is passed here
/// for the sole purpose of setting it when the a patch ReplaceNode at 0 is encountered.
#[track_caller]
fn apply_patch_to_node<DSP, MSG>(
    program: &DSP,
    root_node: &mut Node,
    node: &Node,
    old_closures: &mut ActiveClosure,
    focused_node: &mut Option<Node>,
    patch: &Patch<MSG>,
) -> Result<ActiveClosure, JsValue>
where
    MSG: 'static,
    DSP: Clone + Dispatch<MSG> + 'static,
{
    let mut active_closures = ActiveClosure::new();

    match patch {
        Patch::InsertNode(InsertNode {
            tag,
            patch_path,
            node: for_insert,
        }) => {
            // we inser the node before this target element
            let target_element: &Element = node.unchecked_ref();
            let created_node = CreatedNode::create_dom_node::<DSP, MSG>(
                program,
                for_insert,
                focused_node,
            );
            if let Some(parent_node) = target_element.parent_node() {
                let parent_element: &Element = parent_node.unchecked_ref();
                if let Some(tag) = tag {
                    let parent_tag = parent_element.tag_name().to_lowercase();
                    if parent_tag != **tag {
                        panic!(
                            "expecting a tag: {:?}, but found: {:?}",
                            tag, parent_tag
                        );
                    }
                }
                parent_node
                    .insert_before(&created_node.node, Some(target_element))
                    .expect("must remove target node");
            } else {
                panic!("unable to get parent node of the target element: {:?} thas has a tag: {:?} in path: {:?}, for patching: {:#?}", target_element, tag, patch_path, for_insert);
            }

            Ok(active_closures)
        }
        Patch::AddAttributes(AddAttributes { attrs, .. }) => {
            let element: &Element = node.unchecked_ref();
            CreatedNode::set_element_attributes(
                program,
                &mut active_closures,
                element,
                attrs,
            );

            Ok(active_closures)
        }
        Patch::RemoveAttributes(RemoveAttributes { attrs, .. }) => {
            let element: &Element = node.unchecked_ref();
            for attr in attrs.iter() {
                for att_value in attr.value() {
                    match att_value {
                        AttributeValue::Simple(_) => {
                            CreatedNode::remove_element_attribute(
                                element, attr,
                            )?;
                        }
                        // it is an event listener
                        AttributeValue::EventListener(_) => {
                            remove_event_listener_with_name(
                                attr.name(),
                                element,
                                old_closures,
                            )?;
                        }
                        AttributeValue::FunctionCall(_)
                        | AttributeValue::Style(_)
                        | AttributeValue::Empty => (),
                    }
                }
            }
            Ok(active_closures)
        }

        // This also removes the associated closures and event listeners to the node being replaced
        // including the associated closures of the descendant of replaced node
        // before it is actully replaced in the DOM
        //
        Patch::ReplaceNode(ReplaceNode {
            tag,
            patch_path,
            replacement,
        }) => {
            let element: &Element = node.unchecked_ref();
            // FIXME: performance bottleneck here
            // Each element and it's descendant is created. Each call to dom to create the element
            // has a cost of ~1ms due to bindings in wasm-bindgen, multiple call of 1000 elements can accumulate to 1s time.
            //
            // Possible fix: stringify and process the patch in plain javascript code.
            // That way, all the code is done at once.
            let created_node = CreatedNode::create_dom_node::<DSP, MSG>(
                program,
                replacement,
                focused_node,
            );
            if let Some(tag) = tag {
                let target_tag = element.tag_name().to_lowercase();
                if target_tag != **tag {
                    panic!(
                        "expecting a tag: {:?}, but found: {:?}",
                        tag, target_tag
                    );
                }
            }

            if element.node_type() == Node::ELEMENT_NODE {
                remove_event_listeners(element, old_closures)?;
            }
            element
                .replace_with_with_node_1(&created_node.node)
                .expect("must replace node");

            // if what we are replacing is a root node:
            // we replace the root node here, so that's reference is updated
            // to the newly created node
            if patch_path.path == [0] {
                *root_node = created_node.node;
            }
            Ok(created_node.closures)
        }
        Patch::RemoveNode(RemoveNode { .. }) => {
            let element: &Element = node.unchecked_ref();
            let parent_node =
                element.parent_node().expect("must have a parent node");
            parent_node
                .remove_child(element)
                .expect("must remove target node");
            if element.node_type() == Node::ELEMENT_NODE {
                let element: &Element = node.unchecked_ref();
                remove_event_listeners(element, old_closures)?;
            }
            Ok(active_closures)
        }
        Patch::AppendChildren(AppendChildren {
            tag: _,
            patch_path: _,
            children: new_nodes,
        }) => {
            let element: &Element = node.unchecked_ref();
            let mut active_closures = HashMap::new();
            for new_node in new_nodes.iter() {
                let created_node = CreatedNode::create_dom_node::<DSP, MSG>(
                    program,
                    new_node,
                    focused_node,
                );
                element.append_child(&created_node.node)?;
                active_closures.extend(created_node.closures);
            }
            Ok(active_closures)
        }
        Patch::ChangeText(ct) => {
            node.set_node_value(Some(&ct.new.text));
            Ok(active_closures)
        }
        Patch::ChangeComment(cm) => {
            node.set_node_value(Some(&cm.new));
            Ok(active_closures)
        }
    }
}