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
//! patch module

use crate::{Attribute, Node};
use alloc::vec::Vec;
use core::fmt::Debug;

pub use tree_path::TreePath;

mod tree_path;

/// A Patch encodes an operation that modifies a real DOM element or native UI element
///
/// To update the real DOM that a user sees you'll want to first diff your
/// old virtual dom and new virtual dom.
///
/// This diff operation will generate `Vec<Patch>` with zero or more patches that, when
/// applied to your real DOM, will make your real DOM look like your new virtual dom.
///
/// Each of the Patch contains `TreePath` which contains an array of indexes for each node
/// that we need to traverse to get the target element.
///
/// Consider the following html:
///
/// ```html
/// <body>
///     <main>
///         <input type="text"/>
///         <img src="pic.jpg"/>
///     </main>
///     <footer>
///         <a>Link</a>
///         <nav/>
///     </footer>
/// </body>
/// ```
/// The corresponding DOM tree would be
/// ```bob
///              .─.
///             ( 0 )  <body>
///              `-'
///             /   \
///            /     \
///           /       \
///          ▼         ▼
///  <main> .─.         .─. <footer>
///        ( 0 )       ( 1 )
///         `-'         `-'
///        /  \          | \ '.
///       /    \         |  \  '.
///      ▼      ▼        |   \   '.
///    .─.      .─.      ▼    ▼     ▼
///   ( 0 )    ( 1 )    .─.   .─.   .─.
///    `─'      `─'    ( 0 ) ( 1 ) ( 2 )
///  <input> <img>      `─'   `─'   `─'
///                    <a>  <Text>   <nav>
/// ```
/// To traverse to the `<nav>` element we follow the TreePath([0,1,2]).
/// 0 - is the root element which is always zero.
/// 1 - is the `footer` element since it is the 2nd element of the body.
/// 2 - is the `nav` element since it is the 3rd node in the `footer` element.
#[derive(Clone, Debug, PartialEq)]
pub struct Patch<'a, Ns, Tag, Leaf, Att, Val>
where
    Ns: PartialEq + Clone + Debug,
    Tag: PartialEq + Debug,
    Leaf: PartialEq + Clone + Debug,
    Att: PartialEq + Clone + Debug,
    Val: PartialEq + Clone + Debug,
{
    /// the tag of the node at patch_path
    pub tag: Option<&'a Tag>,
    /// the path to traverse to get to the target element
    pub patch_path: TreePath,
    /// the type of patch we are going to apply
    pub patch_type: PatchType<'a, Ns, Tag, Leaf, Att, Val>,
}

/// the patch variant
#[derive(Clone, Debug, PartialEq)]
pub enum PatchType<'a, Ns, Tag, Leaf, Att, Val>
where
    Ns: PartialEq + Clone + Debug,
    Tag: PartialEq + Debug,
    Leaf: PartialEq + Clone + Debug,
    Att: PartialEq + Clone + Debug,
    Val: PartialEq + Clone + Debug,
{
    /// insert the nodes before the node at patch_path
    InsertBeforeNode {
        /// the nodes to be inserted before patch_path
        nodes: Vec<&'a Node<Ns, Tag, Leaf, Att, Val>>,
    },

    /// insert the nodes after the node at patch_path
    InsertAfterNode {
        /// the nodes to be inserted after the patch_path
        nodes: Vec<&'a Node<Ns, Tag, Leaf, Att, Val>>,
    },

    /// Append a vector of child nodes to a parent node id at patch_path
    AppendChildren {
        /// children nodes to be appended and their corresponding new_node_idx
        children: Vec<&'a Node<Ns, Tag, Leaf, Att, Val>>,
    },
    /// remove the target node
    RemoveNode,
    /// remove the nodes pointed at these `nodes_path`
    /// and move them before `target_element` pointed at `patch_path`
    MoveBeforeNode {
        /// before this target location
        nodes_path: Vec<TreePath>,
    },
    /// remove the the nodes pointed at these nodes_path
    /// and move them after the `target_element` pointed at `patch_path`
    MoveAfterNode {
        /// after this target location
        nodes_path: Vec<TreePath>,
    },

    /// ReplaceNode a node with another node. This typically happens when a node's tag changes.
    /// ex: <div> becomes <span>
    ReplaceNode {
        /// the node that will replace the target node
        replacement: Vec<&'a Node<Ns, Tag, Leaf, Att, Val>>,
    },
    /// Add attributes that the new node has that the old node does not
    /// Note: the attributes is not a reference since attributes of same
    /// name are merged to produce a new unify attribute
    AddAttributes {
        /// the attributes to be patched into the target node
        attrs: Vec<&'a Attribute<Ns, Att, Val>>,
    },
    /// Remove attributes that the old node had that the new node doesn't
    RemoveAttributes {
        /// attributes that are to be removed from this target node
        attrs: Vec<&'a Attribute<Ns, Att, Val>>,
    },
}

impl<'a, Ns, Tag, Leaf, Att, Val> Patch<'a, Ns, Tag, Leaf, Att, Val>
where
    Ns: PartialEq + Clone + Debug,
    Tag: PartialEq + Debug,
    Leaf: PartialEq + Clone + Debug,
    Att: PartialEq + Clone + Debug,
    Val: PartialEq + Clone + Debug,
{
    /// return the path to traverse for this patch to get to the target Node
    pub fn path(&self) -> &TreePath {
        &self.patch_path
    }

    /// return the node paths involve such as those in moving nodes
    pub fn node_paths(&self) -> &[TreePath] {
        match &self.patch_type {
            PatchType::MoveBeforeNode { nodes_path } => nodes_path,
            PatchType::MoveAfterNode { nodes_path } => nodes_path,
            _ => &[],
        }
    }

    /// return the tag of this patch
    pub fn tag(&self) -> Option<&Tag> {
        self.tag
    }

    /// create an InsertBeforeNode patch
    pub fn insert_before_node(
        tag: Option<&'a Tag>,
        patch_path: TreePath,
        nodes: impl IntoIterator<Item = &'a Node<Ns, Tag, Leaf, Att, Val>>,
    ) -> Patch<'a, Ns, Tag, Leaf, Att, Val> {
        Patch {
            tag,
            patch_path,
            patch_type: PatchType::InsertBeforeNode {
                nodes: nodes.into_iter().collect(),
            },
        }
    }

    /// create an InsertAfterNode patch
    pub fn insert_after_node(
        tag: Option<&'a Tag>,
        patch_path: TreePath,
        nodes: Vec<&'a Node<Ns, Tag, Leaf, Att, Val>>,
    ) -> Patch<'a, Ns, Tag, Leaf, Att, Val> {
        Patch {
            tag,
            patch_path,
            patch_type: PatchType::InsertAfterNode { nodes },
        }
    }

    /// create a patch where we add children to the target node
    pub fn append_children(
        tag: Option<&'a Tag>,
        patch_path: TreePath,
        children: Vec<&'a Node<Ns, Tag, Leaf, Att, Val>>,
    ) -> Patch<'a, Ns, Tag, Leaf, Att, Val> {
        Patch {
            tag,
            patch_path,
            patch_type: PatchType::AppendChildren { children },
        }
    }

    /// create a patch where the target element that can be traverse
    /// using the patch path will be remove
    pub fn remove_node(
        tag: Option<&'a Tag>,
        patch_path: TreePath,
    ) -> Patch<'a, Ns, Tag, Leaf, Att, Val> {
        Patch {
            tag,
            patch_path,
            patch_type: PatchType::RemoveNode,
        }
    }

    /// remove the nodes pointed at the `nodes_path` and insert them before the target element
    /// pointed at patch_path
    pub fn move_before_node(
        tag: Option<&'a Tag>,
        patch_path: TreePath,
        nodes_path: impl IntoIterator<Item = TreePath>,
    ) -> Patch<'a, Ns, Tag, Leaf, Att, Val> {
        Patch {
            tag,
            patch_path,
            patch_type: PatchType::MoveBeforeNode {
                nodes_path: nodes_path.into_iter().collect(),
            },
        }
    }

    /// remove the nodes pointed at the `nodes_path` and insert them after the target element
    /// pointed at patch_path
    pub fn move_after_node(
        tag: Option<&'a Tag>,
        patch_path: TreePath,
        nodes_path: impl IntoIterator<Item = TreePath>,
    ) -> Patch<'a, Ns, Tag, Leaf, Att, Val> {
        Patch {
            tag,
            patch_path,
            patch_type: PatchType::MoveAfterNode {
                nodes_path: nodes_path.into_iter().collect(),
            },
        }
    }

    /// create a patch where a node is replaced by the `replacement` node.
    /// The target node to be replace is traverse using the `patch_path`
    pub fn replace_node(
        tag: Option<&'a Tag>,
        patch_path: TreePath,
        replacement: impl IntoIterator<Item = &'a Node<Ns, Tag, Leaf, Att, Val>>,
    ) -> Patch<'a, Ns, Tag, Leaf, Att, Val> {
        Patch {
            tag,
            patch_path,
            patch_type: PatchType::ReplaceNode {
                replacement: replacement.into_iter().collect(),
            },
        }
    }

    /// create a patch where a new attribute is added to the target element
    pub fn add_attributes(
        tag: &'a Tag,
        patch_path: TreePath,
        attrs: impl IntoIterator<Item = &'a Attribute<Ns, Att, Val>>,
    ) -> Patch<'a, Ns, Tag, Leaf, Att, Val> {
        Patch {
            tag: Some(tag),
            patch_path,
            patch_type: PatchType::AddAttributes {
                attrs: attrs.into_iter().collect(),
            },
        }
    }

    /// create patch where it remove attributes of the target element that can be traversed by the
    /// patch_path.
    pub fn remove_attributes(
        tag: &'a Tag,
        patch_path: TreePath,
        attrs: Vec<&'a Attribute<Ns, Att, Val>>,
    ) -> Patch<'a, Ns, Tag, Leaf, Att, Val> {
        Patch {
            tag: Some(tag),
            patch_path,
            patch_type: PatchType::RemoveAttributes { attrs },
        }
    }
}