-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.go
67 lines (58 loc) · 1.63 KB
/
builder.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
package smetana
import (
"log"
"sort"
"strings"
)
// Struct for tracking internal state during HTML and CSS compilation.
// - `Buf` is the string buffer being written to.
// - By default, the order of HTML tag attributes is undefined and
// non-deterministic. It can be changed to be deterministic by
// setting `deterministicAttributes` to true. Note that this has
// a significant performance cost.
// - `logger` is used for reporting warnings and errors during
// compilation.
type Builder struct {
Buf strings.Builder
DeterministicAttributes bool
Logger *log.Logger
}
func (builder *Builder) writeAttr(key string, value string) {
builder.Buf.WriteByte(' ')
builder.Buf.WriteString(key)
builder.Buf.WriteString("=\"")
builder.Buf.WriteString(value)
builder.Buf.WriteByte('"')
}
func (builder *Builder) writeAttrs(attrs Attrs) {
if builder.DeterministicAttributes {
keys := make([]string, 0, len(attrs))
for k := range attrs {
keys = append(keys, k)
}
sort.Strings(keys)
for _, key := range keys {
builder.writeAttr(key, attrs[key])
}
} else {
for key, value := range attrs {
builder.writeAttr(key, value)
}
}
}
func (builder *Builder) writeOpeningTag(tag Tag, attrs Attrs) {
builder.Buf.WriteByte('<')
builder.Buf.WriteString(tag)
builder.writeAttrs(attrs)
builder.Buf.WriteByte('>')
}
func (builder *Builder) writeClosingTag(tag Tag) {
builder.Buf.WriteString("</")
builder.Buf.WriteString(tag)
builder.Buf.WriteByte('>')
}
func (builder *Builder) writeChildren(children Children) {
for _, child := range children {
child.ToHtml(builder)
}
}