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
use crate::dom;
use crate::dom::dom_node;
use crate::dom::dom_node::DomInner;
use crate::dom::DomAttr;
use crate::dom::DomAttrValue;
use crate::dom::DomNode;
use crate::dom::{Application, Program};
use crate::vdom::ComponentEventCallback;
use crate::vdom::EventCallback;
use crate::vdom::TreePath;
use crate::vdom::{Attribute, AttributeValue, Patch, PatchType};
use indexmap::IndexMap;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::JsValue;

/// a Patch where the virtual nodes are all created in the document.
/// This is necessary since the created Node  doesn't contain references
/// as opposed to Patch which contains reference to the vdom, which makes it hard
/// to be included in a struct
#[derive(Debug)]
pub struct DomPatch {
    /// The path to traverse to get to the target_element
    pub patch_path: TreePath,
    /// the target node
    pub target_element: DomNode,
    /// the parent element of the target node
    pub target_parent: DomNode,
    /// the patch variant
    pub patch_variant: PatchVariant,
}

/// patch variant
#[derive(Debug)]
pub enum PatchVariant {
    /// Insert nodes before the target node
    InsertBeforeNode {
        /// nodes to be inserted before the target node
        nodes: Vec<DomNode>,
    },
    /// Insert nodes after the target node
    InsertAfterNode {
        /// the nodes to be inserted after the target node
        nodes: Vec<DomNode>,
    },
    /// Append nodes into the target node
    AppendChildren {
        /// the children nodes to be appended into the target node
        children: Vec<DomNode>,
    },
    /// Add attributes to the target node
    AddAttributes {
        /// the attributes to be added to the target node
        attrs: Vec<DomAttr>,
    },
    /// Remove attributes from the target node
    RemoveAttributes {
        /// the attributes names to be removed
        attrs: Vec<DomAttr>,
    },
    /// Replace the target node with the replacement node
    ReplaceNode {
        /// the replacement node
        replacement: Vec<DomNode>,
    },
    /// Remove the target node
    RemoveNode,
    /// Clear the children of the target node
    ClearChildren,
    /// Move the target node before the node specified in the path location
    MoveBeforeNode {
        /// before the node at this location
        for_moving: Vec<DomNode>,
    },
    /// Move the target node after the node specified in the path location
    MoveAfterNode {
        /// after the node at this location
        for_moving: Vec<DomNode>,
    },
}

impl DomNode {
    pub(crate) fn find_node(&self, path: &mut TreePath) -> Option<DomNode> {
        match &self.inner {
            DomInner::StatefulComponent { .. } => {
                log::info!(
                    "This is a stateful component, should return the element
                inside relative to the child container at this path: {:?}",
                    path
                );
                // just return self and handle its own patches
                Some(self.clone())
            }
            _ => {
                if path.is_empty() {
                    Some(self.clone())
                } else {
                    let idx = path.remove_first();
                    if let Some(children) = self.children() {
                        if let Some(child) = children.get(idx) {
                            child.find_node(path)
                        } else {
                            log::warn!("There is no child at index: {idx}");
                            None
                        }
                    } else {
                        log::warn!("Traversing to a childless node..");
                        None
                    }
                }
            }
        }
    }

    pub(crate) fn find_all_nodes(
        &self,
        nodes_to_find: &[(&TreePath, Option<&&'static str>)],
    ) -> IndexMap<TreePath, (DomNode, DomNode)> {
        let mut nodes_to_patch = IndexMap::with_capacity(nodes_to_find.len());
        for (path, tag) in nodes_to_find {
            let mut traverse_path: TreePath = (*path).clone();
            if let Some(found) = self.find_node(&mut traverse_path) {
                let mut parent_path = path.backtrack();
                let target_parent = self
                    .find_node(&mut parent_path)
                    .expect("must find the parent");
                nodes_to_patch.insert((*path).clone(), (found, target_parent));
            } else {
                log::warn!(
                    "can not find: {:?} {:?} target_node: {:?}",
                    path,
                    tag,
                    &self
                );
                log::info!(
                    "real entire dom: {:#?}",
                    dom_node::render_real_dom_to_string(&self.as_node())
                );
                log::warn!("entire dom: {}", self.render_to_string());
            }
        }
        nodes_to_patch
    }
}

impl<APP> Program<APP>
where
    APP: Application + 'static,
{
    pub(crate) fn convert_attr(&self, attr: &Attribute<APP::MSG>) -> DomAttr {
        DomAttr {
            namespace: attr.namespace,
            name: attr.name,
            value: attr
                .value
                .iter()
                .filter_map(|v| self.convert_attr_value(v))
                .collect(),
        }
    }

    fn convert_attr_value(&self, attr_value: &AttributeValue<APP::MSG>) -> Option<DomAttrValue> {
        match attr_value {
            AttributeValue::Simple(v) => Some(DomAttrValue::Simple(v.clone())),
            AttributeValue::Style(v) => Some(DomAttrValue::Style(v.clone())),
            AttributeValue::EventListener(v) => {
                Some(DomAttrValue::EventListener(self.convert_event_listener(v)))
            }
            AttributeValue::ComponentEventListener(v) => Some(DomAttrValue::EventListener(
                self.convert_component_event_listener(v),
            )),
            AttributeValue::Empty => None,
        }
    }

    fn convert_event_listener(
        &self,
        event_listener: &EventCallback<APP::MSG>,
    ) -> Closure<dyn FnMut(web_sys::Event)> {
        let program = self.downgrade();
        let event_listener = event_listener.clone();
        let closure: Closure<dyn FnMut(web_sys::Event)> =
            Closure::new(move |event: web_sys::Event| {
                let msg = event_listener.emit(dom::Event::from(event));
                let mut program = program.upgrade().expect("must upgrade");
                program.dispatch(msg);
            });
        closure
    }

    fn convert_component_event_listener(
        &self,
        component_callback: &ComponentEventCallback,
    ) -> Closure<dyn FnMut(web_sys::Event)> {
        let component_callback = component_callback.clone();
        let closure: Closure<dyn FnMut(web_sys::Event)> =
            Closure::new(move |event: web_sys::Event| {
                component_callback.emit(dom::Event::from(event));
            });
        closure
    }
    /// get the real DOM target node and make a DomPatch object for each of the Patch
    pub(crate) fn convert_patches(
        &self,
        target_node: &DomNode,
        patches: &[Patch<APP::MSG>],
    ) -> Result<Vec<DomPatch>, JsValue> {
        let nodes_to_find: Vec<(&TreePath, Option<&&'static str>)> = patches
            .iter()
            .map(|patch| (patch.path(), patch.tag()))
            .chain(
                patches
                    .iter()
                    .flat_map(|patch| patch.node_paths())
                    .map(|path| (path, None)),
            )
            .collect();

        let nodes_lookup = target_node.find_all_nodes(&nodes_to_find);

        let dom_patches:Vec<DomPatch> = patches.iter().map(|patch|{
            let patch_path = patch.path();
            let patch_tag = patch.tag();
            if let Some((target_node, target_parent)) = nodes_lookup.get(patch_path) {
                let target_tag = target_node.tag();
                if let (Some(patch_tag), Some(target_tag)) = (patch_tag, target_tag) {
                    if **patch_tag != target_tag{
                        panic!(
                            "expecting a tag: {patch_tag:?}, but found: {target_tag:?}"
                        );
                    }
                }
                self.convert_patch(&nodes_lookup, target_node, target_parent, patch)
            } else {
                unreachable!("Getting here means we didn't find the element of next node that we are supposed to patch, patch_path: {:?}, with tag: {:?}", patch_path, patch_tag);
            }
        }).collect();

        Ok(dom_patches)
    }
    /// convert a virtual DOM Patch into a created DOM node Patch
    pub fn convert_patch(
        &self,
        nodes_lookup: &IndexMap<TreePath, (DomNode, DomNode)>,
        target_element: &DomNode,
        target_parent: &DomNode,
        patch: &Patch<APP::MSG>,
    ) -> DomPatch {
        let target_element = target_element.clone();
        let target_parent = target_parent.clone();
        let Patch {
            patch_path,
            patch_type,
            ..
        } = patch;

        let patch_path = patch_path.clone();

        match patch_type {
            PatchType::InsertBeforeNode { nodes } => {
                let nodes = nodes
                    .iter()
                    .map(|for_insert| self.create_dom_node(for_insert))
                    .collect();
                DomPatch {
                    patch_path,
                    target_element,
                    target_parent,
                    patch_variant: PatchVariant::InsertBeforeNode { nodes },
                }
            }
            PatchType::InsertAfterNode { nodes } => {
                let nodes = nodes
                    .iter()
                    .map(|for_insert| self.create_dom_node(for_insert))
                    .collect();
                DomPatch {
                    patch_path,
                    target_element,
                    target_parent,
                    patch_variant: PatchVariant::InsertAfterNode { nodes },
                }
            }

            PatchType::AddAttributes { attrs } => {
                // we merge the attributes here prior to conversion
                let attrs = Attribute::merge_attributes_of_same_name(attrs.iter().copied());
                DomPatch {
                    patch_path,
                    target_element,
                    target_parent,
                    patch_variant: PatchVariant::AddAttributes {
                        attrs: attrs.iter().map(|a| self.convert_attr(a)).collect(),
                    },
                }
            }
            PatchType::RemoveAttributes { attrs } => DomPatch {
                patch_path,
                target_element,
                target_parent,
                patch_variant: PatchVariant::RemoveAttributes {
                    attrs: attrs.iter().map(|a| self.convert_attr(a)).collect(),
                },
            },

            PatchType::ReplaceNode { replacement } => {
                let replacement = replacement
                    .iter()
                    .map(|node| self.create_dom_node(node))
                    .collect();
                DomPatch {
                    patch_path,
                    target_element,
                    target_parent,
                    patch_variant: PatchVariant::ReplaceNode { replacement },
                }
            }
            PatchType::RemoveNode => DomPatch {
                patch_path,
                target_element,
                target_parent,
                patch_variant: PatchVariant::RemoveNode,
            },
            PatchType::ClearChildren => DomPatch {
                patch_path,
                target_element,
                target_parent,
                patch_variant: PatchVariant::ClearChildren,
            },
            PatchType::MoveBeforeNode { nodes_path } => {
                let for_moving = nodes_path
                    .iter()
                    .map(|path| {
                        let (node, _) = nodes_lookup.get(path).expect("must have found the node");
                        node.clone()
                    })
                    .collect();
                DomPatch {
                    patch_path,
                    target_element,
                    target_parent,
                    patch_variant: PatchVariant::MoveBeforeNode { for_moving },
                }
            }
            PatchType::MoveAfterNode { nodes_path } => {
                let for_moving = nodes_path
                    .iter()
                    .map(|path| {
                        let (node, _) = nodes_lookup.get(path).expect("must have found the node");
                        node.clone()
                    })
                    .collect();
                DomPatch {
                    patch_path,
                    target_element,
                    target_parent,
                    patch_variant: PatchVariant::MoveAfterNode { for_moving },
                }
            }
            PatchType::AppendChildren { children } => {
                let children = children
                    .iter()
                    .map(|for_insert| self.create_dom_node(for_insert))
                    .collect();

                DomPatch {
                    patch_path,
                    target_element,
                    target_parent,
                    patch_variant: PatchVariant::AppendChildren { children },
                }
            }
        }
    }

    /// TODO: this should not have access to root_node, so it can generically
    /// apply patch to any dom node
    pub(crate) fn apply_dom_patches(
        &self,
        dom_patches: impl IntoIterator<Item = DomPatch>,
    ) -> Result<(), JsValue> {
        for dom_patch in dom_patches {
            self.apply_dom_patch(dom_patch)?;
        }
        Ok(())
    }

    /// apply a dom patch to this root node,
    /// return a new root_node if it would replace the original root_node
    /// TODO: this should have no access to root_node, so it can be used in general sense
    pub(crate) fn apply_dom_patch(&self, dom_patch: DomPatch) -> Result<(), JsValue> {
        let DomPatch {
            patch_path,
            target_element,
            target_parent,
            patch_variant,
        } = dom_patch;

        match patch_variant {
            PatchVariant::InsertBeforeNode { nodes } => {
                target_parent.insert_before(&target_element, nodes);
            }

            PatchVariant::InsertAfterNode { nodes } => {
                target_parent.insert_after(&target_element, nodes);
            }
            PatchVariant::AppendChildren { children } => {
                target_element.append_children(children);
            }

            PatchVariant::AddAttributes { attrs } => {
                target_element.set_dom_attrs(attrs).unwrap();
            }
            PatchVariant::RemoveAttributes { attrs } => {
                for attr in attrs.iter() {
                    for att_value in attr.value.iter() {
                        match att_value {
                            DomAttrValue::Simple(_) => {
                                target_element.remove_dom_attr(attr)?;
                            }
                            // it is an event listener
                            DomAttrValue::EventListener(_) => {
                                let DomInner::Element { listeners, .. } = &target_element.inner
                                else {
                                    unreachable!("must be an element");
                                };
                                if let Some(listener) = listeners.borrow_mut().as_mut() {
                                    listener.retain(|event, _| *event != attr.name)
                                }
                            }
                            DomAttrValue::Style(_) => {
                                target_element.remove_dom_attr(attr)?;
                            }
                            DomAttrValue::Empty => (),
                        }
                    }
                }
            }

            // 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
            // TODO: make root node a Vec
            PatchVariant::ReplaceNode { mut replacement } => {
                let first_node = replacement.remove(0);

                if target_element.is_fragment() {
                    assert!(
                        patch_path.is_empty(),
                        "this should only happen to root node"
                    );
                    let mut mount_node = self.mount_node.borrow_mut();
                    let mount_node = mount_node.as_mut().expect("must have a mount node");
                    mount_node.append_children(vec![first_node.clone()]);
                    mount_node.append_children(replacement);
                } else {
                    if patch_path.path.is_empty() {
                        let mut mount_node = self.mount_node.borrow_mut();
                        let mount_node = mount_node.as_mut().expect("must have a mount node");
                        mount_node.replace_child(&target_element, first_node.clone());
                    } else {
                        target_parent.replace_child(&target_element, first_node.clone());
                    }
                    //insert the rest
                    target_parent.insert_after(&first_node, replacement);
                }
                if patch_path.path.is_empty() {
                    *self.root_node.borrow_mut() = Some(first_node);
                }
            }
            PatchVariant::RemoveNode => {
                target_parent.remove_children(&[&target_element]);
            }
            PatchVariant::ClearChildren => {
                target_element.clear_children();
            }
            PatchVariant::MoveBeforeNode { for_moving } => {
                target_parent.remove_children(&for_moving.iter().collect::<Vec<_>>());
                target_parent.insert_before(&target_element, for_moving);
            }

            PatchVariant::MoveAfterNode { for_moving } => {
                target_parent.remove_children(&for_moving.iter().collect::<Vec<_>>());
                target_parent.insert_after(&target_element, for_moving);
            }
        }
        Ok(())
    }
}