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
use super::{Reform, VDiff, VNode};
use log::warn;
use std::cmp::PartialEq;
use std::fmt;
use stdweb::web::{document, Element, INode, Node, TextNode};
#[derive(Clone)]
pub struct VText {
pub text: String,
pub reference: Option<TextNode>,
}
impl VText {
pub fn new(text: String) -> Self {
VText {
text,
reference: None,
}
}
}
impl VDiff for VText {
fn detach(&mut self, parent: &Element) -> Option<Node> {
let node = self
.reference
.take()
.expect("tried to remove not rendered VText from DOM");
let next_sibling = node.next_sibling();
if parent.remove_child(&node).is_err() {
warn!("Node not found to remove VText");
}
next_sibling
}
fn apply(
&mut self,
parent: &Element,
previous_sibling: Option<&Node>,
ancestor: Option<VNode>,
) -> Option<Node> {
assert!(
self.reference.is_none(),
"reference is ignored so must not be set"
);
let reform = {
match ancestor {
Some(VNode::VText(mut vtext)) => {
self.reference = vtext.reference.take();
if self.text != vtext.text {
if let Some(ref element) = self.reference {
element.set_node_value(Some(&self.text));
}
}
Reform::Keep
}
Some(mut vnode) => Reform::Before(vnode.detach(parent)),
None => Reform::Before(None),
}
};
match reform {
Reform::Keep => {}
Reform::Before(next_sibling) => {
let element = document().create_text_node(&self.text);
if let Some(next_sibling) = next_sibling {
parent
.insert_before(&element, &next_sibling)
.expect("can't insert text before the next sibling");
} else if let Some(next_sibling) = previous_sibling.and_then(|p| p.next_sibling()) {
parent
.insert_before(&element, &next_sibling)
.expect("can't insert text before next_sibling");
} else {
parent.append_child(&element);
}
self.reference = Some(element);
}
}
self.reference.as_ref().map(|t| t.as_node().to_owned())
}
}
impl fmt::Debug for VText {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "VText {{ text: {} }}", self.text)
}
}
impl PartialEq for VText {
fn eq(&self, other: &VText) -> bool {
self.text == other.text
}
}