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
use super::{VDiff, VNode, VText};
use html::{Component, Scope};
use stdweb::web::Node;
pub struct VList<COMP: Component> {
pub childs: Vec<VNode<COMP>>,
}
impl<COMP: Component> VList<COMP> {
pub fn new() -> Self {
VList { childs: Vec::new() }
}
pub fn add_child(&mut self, child: VNode<COMP>) {
self.childs.push(child);
}
}
impl<COMP: Component> VDiff for VList<COMP> {
type Component = COMP;
fn detach(&mut self, parent: &Node) -> Option<Node> {
let mut last_sibling = None;
for mut child in self.childs.drain(..) {
last_sibling = child.detach(parent);
}
last_sibling
}
fn apply(
&mut self,
parent: &Node,
precursor: Option<&Node>,
ancestor: Option<VNode<Self::Component>>,
env: &Scope<Self::Component>,
) -> Option<Node> {
let mut precursor = precursor.map(|node| node.to_owned());
let mut rights = {
match ancestor {
Some(VNode::VList(mut vlist)) => {
vlist.childs.drain(..).map(Some).collect::<Vec<_>>()
}
Some(mut vnode) => {
vec![Some(vnode)]
}
None => Vec::new(),
}
};
if self.childs.is_empty() {
let placeholder = VText::new("".into());
self.childs.push(placeholder.into());
}
let mut lefts = self.childs.iter_mut().map(Some).collect::<Vec<_>>();
let diff = lefts.len() as i32 - rights.len() as i32;
if diff > 0 {
for _ in 0..diff {
rights.push(None);
}
} else if diff < 0 {
for _ in 0..-diff {
lefts.push(None);
}
}
for pair in lefts.into_iter().zip(rights) {
match pair {
(Some(left), right) => {
precursor = left.apply(parent, precursor.as_ref(), right, &env);
}
(None, Some(mut right)) => {
right.detach(parent);
}
(None, None) => {
panic!("redundant iterations during diff");
}
}
}
precursor
}
}