-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
105 lines (87 loc) · 2.19 KB
/
index.js
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
const dummy = document.createElement('div');
export function morph(dst, src) {
if (typeof src === 'string') {
dummy.innerHTML = src;
src = document.createDocumentFragment();
let el;
while (el = dummy.firstChild) {
src.appendChild(el)
}
}
return patch(dst, src);
}
function patch(dst, src) {
let newChild = src.firstChild;
let oldChild = dst.firstChild;
let newNext;
let oldNext;
let changed = false;
while (oldChild != null && newChild != null) {
newNext = newChild.nextSibling;
oldNext = oldChild.nextSibling;
if (
oldChild.nodeType !== newChild.nodeType
|| oldChild.nodeName !== newChild.nodeName
) {
changed = true;
dst.replaceChild(newChild, oldChild);
} else if (oldChild.nodeType === oldChild.TEXT_NODE) {
if (oldChild.nodeValue !== newChild.nodeValue) {
changed = true;
oldChild.nodeValue = newChild.nodeValue;
}
} else {
changed = patchAttributes(oldChild, newChild) || changed;
changed = patch(oldChild, newChild) || changed;
}
newChild = newNext;
oldChild = oldNext;
}
if (newChild) {
do {
changed = true;
newNext = newChild.nextSibling
dst.appendChild(newChild);
} while (newChild = newNext);
}
if (oldChild) {
do {
changed = true;
oldNext = oldChild.nextSibling;
dst.removeChild(oldChild);
} while (oldChild = oldNext);
}
return changed;
}
function patchAttributes(oldNode, newNode) {
const exists = {};
let changed = false;
let i = oldNode.attributes.length;
while (i--) {
const oldAttr = oldNode.attributes[i];
const newAttr = newNode.attributes[oldAttr.name];
exists[oldAttr.name] = 1;
if (newAttr == null) {
changed = true;
oldNode.removeAttribute(oldAttr.name);
} else if (oldAttr.nodeValue !== newAttr.nodeValue) {
changed = true;
oldAttr.nodeValue = newAttr.nodeValue;
}
}
i = newNode.attributes.length;
while (i--) {
const {name, nodeValue} = newNode.attributes[i];
if (!exists.hasOwnProperty(name)) {
const oldAttr = oldNode.attributes[name];
if (oldAttr == null) {
changed = true;
oldNode.setAttribute(name, nodeValue);
} else if (oldAttr.nodeValue !== nodeValue) {
changed = true;
oldAttr.nodeValue = nodeValue;
}
}
}
return changed;
}