-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.js
53 lines (42 loc) · 1.17 KB
/
example.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
// @flow
import tracePath from './dist/index-es6.js'
var nodeA = document.querySelector('#node-1')
var nodeB = document.querySelector('#node-2')
var oldChildren = nodeA ? nodeA.childNodes : []
var newChildren = nodeB ? nodeB.childNodes : []
var diffPath = []
function applyDiff (parent, a, b, diff, update) {
var offsetA = 0
var offsetB = 0
for (var i = 0; i < diff.length; i++) {
if (diff[i] === 'DELETE') {
parent.removeChild(a[i + offsetA])
--offsetA
--offsetB
} else if (diff[i] === 'INSERT') {
parent.insertBefore(b[i + offsetB], a[i + offsetA])
--offsetB
} else {
update(a[i + offsetA], b[i + offsetB])
}
}
}
function canPatch (nodeA, nodeB) {
if (nodeA.nodeName === nodeB.nodeName) return true
return false
}
if(nodeA !== null) {
tracePath(oldChildren, newChildren, function (px, py, x, y) {
if (x === px) {
diffPath.unshift('INSERT')
} else if (y === py) {
diffPath.unshift('DELETE')
} else {
diffPath.unshift('UPDATE')
}
}, canPatch)
applyDiff(nodeA, oldChildren, newChildren, diffPath, function (a, b) {
a.textContent = b.textContent
})
}
window.tracePath = tracePath;