forked from alupuleasa/html-diff
-
Notifications
You must be signed in to change notification settings - Fork 1
/
viztree.go
63 lines (58 loc) · 1.32 KB
/
viztree.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
// Package vizhtml provides a way to display html node trees for debug purposes.
package vizhtml
import (
"strings"
"golang.org/x/net/html"
)
// Tree provides a text visualisation of the given html.Node tree, one node per line, stopping at the target.
// It is intended for debugging.
func Tree(n, target *html.Node) string {
r, _ := vizTree0(n, target, 0, "")
return r
}
// nodeLevel returns the prefix to show the depth of the node
func nodeLevel(l int) (s string) {
for i := 0; i < l; i++ {
s += "-"
}
s += ">"
return s
}
// vizTree0 is the recursive node tree walker.
func vizTree0(n, target *html.Node, l int, s string) (string, bool) {
if n == nil {
return s, true
}
s += nodeLevel(l)
switch n.Type {
case html.ErrorNode:
s += " Error: "
case html.TextNode:
s += " Text: "
case html.DocumentNode:
s += "Document: "
case html.ElementNode:
s += "Element: "
case html.CommentNode:
s += "Comment: "
case html.DoctypeNode:
s += "DocType: "
}
if len(n.Data) > 10 {
s += strings.Replace(n.Data[:10], "\n", "", -1)
} else {
s += strings.Replace(n.Data, "\n", "", -1)
}
if n == target {
return s + " (Target)\n", true
}
s += "\n"
for c := n.FirstChild; c != nil; c = c.NextSibling {
var found bool
s, found = vizTree0(c, target, l+1, s)
if found {
return s, true
}
}
return s, false
}