-
Notifications
You must be signed in to change notification settings - Fork 27
/
diff.go
330 lines (290 loc) · 7.03 KB
/
diff.go
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package live
import (
"bytes"
"fmt"
"log"
"strings"
"github.com/google/go-cmp/cmp"
"golang.org/x/net/html"
)
const _debug = false
// PatchAction available actions to take by a patch.
type PatchAction uint32
// Actions available.
const (
Noop PatchAction = iota
Insert
Replace
Append
Prepend
)
// Patch a location in the frontend dom.
type Patch struct {
Path []int
Action PatchAction
HTML string
}
func (p Patch) String() string {
action := ""
switch p.Action {
case Noop:
action = "NO"
case Insert:
action = "IN"
case Replace:
action = "RE"
case Append:
action = "AP"
case Prepend:
action = "PR"
}
return fmt.Sprintf("%v %s %s", p.Path, action, p.HTML)
}
// Diff compare two node states and return patches.
func Diff(current, proposed *html.Node) ([]Patch, error) {
patches := diffTrees(current, proposed)
output := make([]Patch, len(patches))
for idx, p := range patches {
var buf bytes.Buffer
if p.Node != nil {
if err := html.Render(&buf, p.Node); err != nil {
return nil, fmt.Errorf("failed to render patch: %w", err)
}
} else {
if _, err := buf.WriteString(""); err != nil {
return nil, fmt.Errorf("failed to render blank patch: %w", err)
}
}
output[idx] = Patch{
Path: p.Path[2:],
Action: p.Action,
HTML: buf.String(),
}
}
return output, nil
}
// patch describes how to modify a dom.
type patch struct {
Path []int
Action PatchAction
Node *html.Node
}
// differ handles state for recursive diffing.
type differ struct {
// `live-update` handler.
updateNode *html.Node
updateModifier PatchAction
updatePath []int
}
// diffTrees compares two html Nodes and outputs patches.
func diffTrees(current, proposed *html.Node) []patch {
d := &differ{}
pruneTree(current)
pruneTree(proposed)
return d.compareNodes(current, proposed, []int{0})
}
func pruneTree(root *html.Node) {
// Check this node.
if root.NextSibling != nil {
pruneTree(root.NextSibling)
}
if root.FirstChild != nil {
pruneTree(root.FirstChild)
}
debugNodeLog("checking", root)
if !nodeRelevant(root) {
if root.Parent != nil {
debugNodeLog("removingNode", root)
root.Parent.RemoveChild(root)
}
}
}
func (d *differ) compareNodes(oldNode, newNode *html.Node, followedPath []int) []patch {
debugNodeLog("compareNodes oldNode", oldNode)
debugNodeLog("compareNodes newNode", newNode)
patches := []patch{}
// Same so no patch.
if oldNode == nil && newNode == nil {
return patches
}
// If oldNode is nothing we need to append the new node.
if oldNode == nil {
if !nodeRelevant(newNode) {
return []patch{}
}
return append(
patches,
d.generatePatch(newNode, followedPath[:len(followedPath)-1], Append),
)
}
// If newNode does not exist, we need to patch a removal.
if newNode == nil {
if !nodeRelevant(oldNode) {
return []patch{}
}
return append(patches, d.generatePatch(newNode, followedPath, Replace))
}
// Check for `live-update` modifiers.
d.liveUpdateCheck(newNode, followedPath)
// If nodes at this position are not equal patch a replacement.
if nodeEqual(oldNode, newNode) == false {
return append(patches, d.generatePatch(newNode, followedPath, Replace))
}
newChildren := generateNodeList(newNode.FirstChild)
oldChildren := generateNodeList(oldNode.FirstChild)
for i := 0; i < len(newChildren) || i < len(oldChildren); i++ {
// Have to copy the followed path here, otherwise the patches
// paths get updated.
nextPath := make([]int, len(followedPath))
copy(nextPath, followedPath)
nextPath = append(nextPath, i)
if i >= len(newChildren) {
patches = append(patches, d.compareNodes(oldChildren[i], nil, nextPath)...)
} else if i >= len(oldChildren) {
patches = append(patches, d.compareNodes(nil, newChildren[i], nextPath)...)
} else {
patches = append(patches, d.compareNodes(oldChildren[i], newChildren[i], nextPath)...)
}
}
return patches
}
func (d *differ) generatePatch(node *html.Node, followedPath []int, action PatchAction) patch {
if node == nil {
return patch{
Path: d.patchPath(followedPath),
Action: d.patchAction(action),
Node: nil,
}
}
debugNodeLog("generatePatch", node)
switch node.Type {
case html.TextNode:
return patch{
Path: d.patchPath(followedPath[:len(followedPath)-1]),
Action: d.patchAction(action),
Node: node.Parent,
}
default:
return patch{
Path: d.patchPath(followedPath),
Action: d.patchAction(action),
Node: node,
}
}
}
// liveUpdateCheck check for an update modifier for this node.
func (d *differ) liveUpdateCheck(node *html.Node, followedPath []int) {
for _, attr := range node.Attr {
if attr.Key != "live-update" {
continue
}
d.updateNode = node
nextPath := make([]int, len(followedPath))
copy(nextPath, followedPath)
d.updatePath = nextPath
switch attr.Val {
case "replace":
d.updateModifier = Replace
d.updatePath = append(d.updatePath, 0)
case "ignore":
d.updateModifier = Noop
case "append":
d.updateModifier = Append
case "prepend":
d.updateModifier = Prepend
}
break
}
}
// patchAction in the current state of the differ get the patch
// action.
func (d *differ) patchAction(action PatchAction) PatchAction {
if d.updateNode != nil {
return d.updateModifier
}
return action
}
// patchPath in the current state of the differ get the patch
// path.
func (d *differ) patchPath(path []int) []int {
if d.updateNode != nil {
return d.updatePath
}
return path
}
// nodeRelevant check if this node is relevant.
func nodeRelevant(node *html.Node) bool {
if node.Type == html.TextNode {
debugNodeLog("textNode", node)
}
if node.Type == html.TextNode && len(strings.TrimSpace(node.Data)) == 0 {
return false
}
return true
}
// nodeEqual check if one node is equal to another.
func nodeEqual(oldNode *html.Node, newNode *html.Node) bool {
// Type check
if oldNode.Type != newNode.Type {
return false
}
if len(oldNode.Attr) != len(newNode.Attr) {
return false
}
// Deep attr check
for _, c := range newNode.Attr {
found := false
for _, l := range oldNode.Attr {
if cmp.Equal(c, l) {
found = true
break
}
}
if found {
continue
}
return false
}
// Data check
if strings.TrimSpace(oldNode.Data) != strings.TrimSpace(newNode.Data) {
return false
}
return true
}
// generateNodeList create a list of sibling nodes.
func generateNodeList(node *html.Node) []*html.Node {
list := []*html.Node{}
if node == nil {
return list
}
current := getFirstSibling(node)
for {
list = append(list, current)
if current.NextSibling == nil {
break
} else {
current = current.NextSibling
}
}
return list
}
// getFirstSibling takes a node and finds the "first" node in the sibling
// list.
func getFirstSibling(node *html.Node) *html.Node {
if node.PrevSibling == nil {
return node
}
return getFirstSibling(node.PrevSibling)
}
func debugNodeLog(msg string, node *html.Node) {
if !_debug {
return
}
if node == nil {
log.Println(msg, nil, nil, `""`)
return
}
var d bytes.Buffer
html.Render(&d, node)
log.Println(msg, node.Type, `s"`+node.Data+`"e`, `s"`+d.String()+`"e`)
}