-
Notifications
You must be signed in to change notification settings - Fork 0
/
dom_representation.go
64 lines (53 loc) · 1.22 KB
/
dom_representation.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
package dom
import (
"bytes"
"fmt"
"strings"
"golang.org/x/net/html"
)
func writePipeChar(buf *bytes.Buffer, index int) {
if index == 0 {
return
}
buf.WriteString(strings.Repeat("│ ", index-1))
buf.WriteString("├─")
}
func writeNode(buf *bytes.Buffer, node *html.Node) {
name := NodeName(node)
buf.WriteString(name)
if len(node.Attr) != 0 {
buf.WriteString(" (")
}
for i, attr := range node.Attr {
buf.WriteString(fmt.Sprintf("%s=%q", attr.Key, attr.Val))
if i < len(node.Attr)-1 {
buf.WriteString(" ")
}
}
if len(node.Attr) != 0 {
buf.WriteString(")")
}
if name == "#text" {
buf.WriteString(fmt.Sprintf(" %q", node.Data))
}
}
// RenderRepresentation is useful for debugging.
// It renders out the *structure* of the dom.
func RenderRepresentation(startNode *html.Node) string {
var buf bytes.Buffer
var finder func(*html.Node, int)
finder = func(node *html.Node, index int) {
writePipeChar(&buf, index)
writeNode(&buf, node)
buf.WriteRune('\n')
for child := node.FirstChild; child != nil; child = child.NextSibling {
finder(child, index+1)
}
}
if startNode.Parent == nil {
finder(startNode, 0)
} else {
finder(startNode, 1)
}
return strings.TrimSpace(buf.String())
}