-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.go
More file actions
124 lines (105 loc) · 2.33 KB
/
node.go
File metadata and controls
124 lines (105 loc) · 2.33 KB
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
package whtml
import (
"bufio"
"fmt"
"io"
)
type NodeType uint32
const (
ErrorNode NodeType = iota
TextNode
ElementNode
MustacheNode
)
type Node struct {
Type NodeType
Data string
Attrs []Attribute
Parent *Node
FirstChild, LastChild *Node
PrevSibling, NextSibling *Node
Namespace string
Pos Pos
}
func (node *Node) Render(writer io.Writer) {
buf := bufio.NewWriter(writer)
node.render(buf, 0)
buf.Flush()
}
func (node *Node) render(w *bufio.Writer, depth int) {
for i := 0; i < depth; i++ {
w.WriteString(" ")
}
switch node.Type {
case ElementNode:
w.WriteRune('<')
w.WriteString(node.Data)
if len(node.Attrs) > 0 {
for _, attr := range node.Attrs {
w.WriteRune(' ')
switch attr.Type {
case StringAttribute:
w.WriteString(sfmt("%v=\"%v\"", attr.Key, attr.Val))
case MustacheAttribute:
w.WriteString(sfmt("%v={{%v}}", attr.Key, attr.Val))
case BoolAttribute:
w.WriteString(attr.Key)
case VariadicAttribute:
w.WriteString(sfmt("...{{%v}}", attr.Val))
}
}
}
if node.FirstChild == nil {
w.WriteString("/>")
return
}
w.WriteRune('>')
for c := node.FirstChild; c != nil; c = c.NextSibling {
w.WriteRune('\n')
c.render(w, depth+1)
}
w.WriteRune('\n')
for i := 0; i < depth; i++ {
w.WriteString(" ")
}
w.WriteString(sfmt("</%v>", node.Data))
case TextNode:
w.WriteString(fmt.Sprintf("%q", node.Data))
}
}
// AppendChild adds a node c as a child of n.
//
// It will panic if c already has a parent or siblings.
func (n *Node) AppendChild(c *Node) {
if c.Parent != nil || c.PrevSibling != nil || c.NextSibling != nil {
panic("html: AppendChild called for an attached child Node")
}
last := n.LastChild
if last != nil {
last.NextSibling = c
} else {
n.FirstChild = c
}
n.LastChild = c
c.Parent = n
c.PrevSibling = last
}
// nodeStack is a stack of nodes.
type nodeStack []*Node
func (s *nodeStack) push(node *Node) {
*s = append(*s, node)
}
// pop pops the stack. It will panic if s is empty.
func (s *nodeStack) pop() *Node {
i := len(*s)
n := (*s)[i-1]
*s = (*s)[:i-1]
return n
}
// top returns the most recently pushed node, or nil if s is empty.
func (s *nodeStack) top() *Node {
if i := len(*s); i > 0 {
return (*s)[i-1]
}
return nil
}