-
Notifications
You must be signed in to change notification settings - Fork 84
/
patch.rs
269 lines (235 loc) · 9.54 KB
/
patch.rs
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
use crate::VirtualNode;
use std::collections::HashMap;
use std::collections::HashSet;
use std::cmp::min;
use wasm_bindgen::JsCast;
use web_sys;
use web_sys::{Element, Node};
/// A Patch encodes an operation that modifies a real DOM 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 Patch has a u32 node index that helps us identify the real DOM node that it applies to.
///
/// Our old virtual dom's nodes are indexed depth first, as shown in this illustration
/// (0 being the root node, 1 being it's first child, 2 being it's first child's first child).
///
/// ```ignore
/// .─.
/// ( 0 )
/// `┬'
/// ┌────┴──────┐
/// │ │
/// ▼ ▼
/// .─. .─.
/// ( 1 ) ( 4 )
/// `┬' `─'
/// ┌────┴───┐ │
/// │ │ ├─────┬─────┐
/// ▼ ▼ │ │ │
/// .─. .─. ▼ ▼ ▼
/// ( 2 ) ( 3 ) .─. .─. .─.
/// `─' `─' ( 5 ) ( 6 ) ( 7 )
/// `─' `─' `─'
/// ```
///
/// We'll revisit our indexing in the future when we optimize our diff/patch process.
#[derive(Debug, PartialEq)]
pub enum Patch<'a> {
/// Append a vector of child nodes to a parent node id.
AppendChildren(NodeIdx, Vec<&'a VirtualNode>),
/// For a `node_i32`, remove all children besides the first `len`
TruncateChildren(NodeIdx, usize),
/// Replace a node with another node. This typically happens when a node's tag changes.
/// ex: <div> becomes <span>
Replace(NodeIdx, &'a VirtualNode),
/// Add attributes that the new node has that the old node does not
AddAttributes(NodeIdx, HashMap<&'a str, &'a str>),
/// Remove attributes that the old node had that the new node doesn't
RemoveAttributes(NodeIdx, Vec<&'a str>),
/// Change the text of a Text node.
ChangeText(NodeIdx, &'a VirtualNode),
}
impl<'a> Patch<'a> {
/// Every Patch is meant to be applied to a specific node within the DOM. Get the
/// index of the DOM node that this patch should apply to. DOM nodes are indexed
/// depth first with the root node in the tree having index 0.
pub fn node_idx(&self) -> usize {
match self {
Patch::AppendChildren(node_idx, _) => *node_idx,
Patch::TruncateChildren(node_idx, _) => *node_idx,
Patch::Replace(node_idx, _) => *node_idx,
Patch::AddAttributes(node_idx, _) => *node_idx,
Patch::RemoveAttributes(node_idx, _) => *node_idx,
Patch::ChangeText(node_idx, _) => *node_idx,
}
}
}
type NodeIdx = usize;
/// 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.
pub fn patch(root_node: Element, patches: &Vec<Patch>) {
let mut cur_node_idx = 0;
let mut nodes_to_find = HashSet::new();
for patch in patches {
nodes_to_find.insert(patch.node_idx());
}
let mut elements_to_patch = HashMap::new();
let mut text_nodes_to_patch = HashMap::new();
find_nodes(
root_node,
&mut cur_node_idx,
&mut nodes_to_find,
&mut elements_to_patch,
&mut text_nodes_to_patch,
);
for patch in patches {
let patch_node_idx = patch.node_idx();
if let Some(element) = elements_to_patch.get(&patch_node_idx) {
apply_element_patch(&element, &patch);
continue;
}
if let Some(text_node) = text_nodes_to_patch.get(&patch_node_idx) {
apply_text_patch(&text_node, &patch);
continue;
}
unreachable!("Getting here means we didn't find the element or next node that we were supposed to patch.")
}
}
fn find_nodes(
root_node: Element,
cur_node_idx: &mut usize,
nodes_to_find: &mut HashSet<usize>,
nodes_to_patch: &mut HashMap<usize, Element>,
text_nodes_to_patch: &mut HashMap<usize, web_sys::Node>,
) {
if nodes_to_find.len() == 0 {
return;
}
// We use child_nodes() instead of children() because children() ignores text nodes
let children = root_node.child_nodes();
let child_node_count = children.length();
if nodes_to_find.get(&cur_node_idx).is_some() {
nodes_to_patch.insert(*cur_node_idx, root_node);
nodes_to_find.remove(&cur_node_idx);
}
*cur_node_idx += 1;
for i in 0..child_node_count {
let node = children.item(i).unwrap();
let element = node.dyn_into::<Element>();
if element.is_ok() {
find_nodes(
element.ok().unwrap(),
cur_node_idx,
nodes_to_find,
nodes_to_patch,
text_nodes_to_patch,
);
} else {
let text_or_comment_node = element.err().unwrap();
// At this time we do not support user entered comment nodes, so if we see a comment
// then it was a delimiter created by virtual-dom-rs in order to ensure that two
// neighboring text nodes did not get merged into one by the browser. So we skip
// over this virtual-dom-rs generated comment node.
if text_or_comment_node.node_type() == Node::COMMENT_NODE {
continue;
}
if nodes_to_find.get(&cur_node_idx).is_some() {
let text_node = text_or_comment_node;
text_nodes_to_patch.insert(*cur_node_idx, text_node);
}
*cur_node_idx += 1;
}
}
}
fn apply_element_patch(node: &Element, patch: &Patch) {
let document = web_sys::window().unwrap().document().unwrap();
match patch {
Patch::AddAttributes(_node_idx, attributes) => {
for (attrib_name, attrib_val) in attributes.iter() {
node.set_attribute(attrib_name, attrib_val)
.expect("Set attribute on element");
}
}
Patch::RemoveAttributes(_node_idx, attributes) => {
for attrib_name in attributes.iter() {
node.remove_attribute(attrib_name)
.expect("Remove attribute from element");
}
}
Patch::Replace(_node_idx, new_node) => {
if new_node.is_text_node() {
node.replace_with_with_node_1(&new_node.create_text_node())
.expect("Replaced with text node");
} else {
node.replace_with_with_node_1(&new_node.create_element())
.expect("Replaced with element");
}
}
Patch::TruncateChildren(_node_idx, num_children_remaining) => {
let children = node.child_nodes();
let mut child_count = children.length();
// We skip over any separators that we placed between two text nodes
// -> `<!--ptns-->`
// and trim all children that come after our new desired `num_children_remaining`
let mut non_separator_children_found = 0;
for index in 0 as u32..child_count {
let child = children
.get(min(index, child_count - 1))
.expect("Potential child to truncate");
// If this is a comment node then we know that it is a `<!--ptns-->`
// text node separator that was created in virtual_node/mod.rs.
if child.node_type() == Node::COMMENT_NODE {
continue;
}
non_separator_children_found += 1;
if non_separator_children_found <= *num_children_remaining as u32 {
continue;
}
node.remove_child(&child).expect("Truncated children");
child_count -= 1;
}
}
Patch::AppendChildren(_node_idx, new_nodes) => {
let parent = &node;
for new_node in new_nodes {
if new_node.is_text_node() {
parent
.append_child(
&document
.create_text_node(
new_node.text.as_ref().expect("Text node to append"),
)
.dyn_into::<web_sys::Node>()
.ok()
.expect("Appended text node"),
)
.expect("Append text node");
} else {
parent
.append_child(&new_node.create_element())
.expect("Appended child element");
}
}
}
Patch::ChangeText(_node_idx, _new_node) => unreachable!(
"Elements should not receive ChangeText patches. Those should go to Node's"
),
}
}
fn apply_text_patch(node: &Node, patch: &Patch) {
match patch {
Patch::ChangeText(_node_idx, new_node) => {
let text = new_node.text.as_ref().expect("New text to use");
node.set_node_value(Some(text.as_str()));
}
_ => unreachable!(
"Node's should only receive change text patches. All other patches go to Element's"
),
}
}