-
Notifications
You must be signed in to change notification settings - Fork 27
/
elem.go
273 lines (229 loc) · 7.02 KB
/
elem.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
package elem
import (
"fmt"
"sort"
"strings"
"github.com/chasefleming/elem-go/attrs"
)
// List of HTML5 void elements. Void elements, also known as self-closing or empty elements,
// are elements that don't have a closing tag because they can't contain any content.
// For example, the <img> tag cannot wrap text or other tags, it stands alone, so it doesn't have a closing tag.
var voidElements = map[string]struct{}{
"area": {},
"base": {},
"br": {},
"col": {},
"command": {},
"embed": {},
"hr": {},
"img": {},
"input": {},
"keygen": {},
"link": {},
"meta": {},
"param": {},
"source": {},
"track": {},
"wbr": {},
}
// List of boolean attributes. Boolean attributes can't have literal values. The presence of an boolean
// attribute represents the "true" value. To represent the "false" value, the attribute has to be omitted.
// See https://html.spec.whatwg.org/multipage/indices.html#attributes-3 for reference
var booleanAttrs = map[string]struct{}{
attrs.AllowFullscreen: {},
attrs.Async: {},
attrs.Autofocus: {},
attrs.Autoplay: {},
attrs.Checked: {},
attrs.Controls: {},
attrs.Defer: {},
attrs.Disabled: {},
attrs.Ismap: {},
attrs.Loop: {},
attrs.Multiple: {},
attrs.Muted: {},
attrs.Nomodule: {},
attrs.Novalidate: {},
attrs.Open: {},
attrs.Playsinline: {},
attrs.Readonly: {},
attrs.Required: {},
attrs.Selected: {},
}
type CSSGenerator interface {
GenerateCSS() string // TODO: Change to CSS()
}
type RenderOptions struct {
// DisableHtmlPreamble disables the doctype preamble for the HTML tag if it exists in the rendering tree
DisableHtmlPreamble bool
StyleManager CSSGenerator
}
type Node interface {
RenderTo(builder *strings.Builder, opts RenderOptions)
Render() string
RenderWithOptions(opts RenderOptions) string
}
// NoneNode represents a node that renders nothing.
type NoneNode struct{}
// RenderTo for NoneNode does nothing.
func (n NoneNode) RenderTo(builder *strings.Builder, opts RenderOptions) {
// Intentionally left blank to render nothing
}
// Render for NoneNode returns an empty string.
func (n NoneNode) Render() string {
return ""
}
// RenderWithOptions for NoneNode returns an empty string.
func (n NoneNode) RenderWithOptions(opts RenderOptions) string {
return ""
}
type TextNode string
func (t TextNode) RenderTo(builder *strings.Builder, opts RenderOptions) {
builder.WriteString(string(t))
}
func (t TextNode) Render() string {
return string(t)
}
func (t TextNode) RenderWithOptions(opts RenderOptions) string {
return string(t)
}
type RawNode string
func (r RawNode) RenderTo(builder *strings.Builder, opts RenderOptions) {
builder.WriteString(string(r))
}
func (r RawNode) Render() string {
return string(r)
}
func (t RawNode) RenderWithOptions(opts RenderOptions) string {
return string(t)
}
type CommentNode string
func (c CommentNode) RenderTo(builder *strings.Builder, opts RenderOptions) {
builder.WriteString("<!-- ")
builder.WriteString(string(c))
builder.WriteString(" -->")
}
func (c CommentNode) Render() string {
return c.RenderWithOptions(RenderOptions{})
}
func (c CommentNode) RenderWithOptions(opts RenderOptions) string {
var builder strings.Builder
c.RenderTo(&builder, opts)
return builder.String()
}
type Element struct {
Tag string
Attrs attrs.Props
Children []Node
}
func (e *Element) RenderTo(builder *strings.Builder, opts RenderOptions) {
// The HTML tag needs a doctype preamble in order to ensure
// browsers don't render in legacy/quirks mode
// https://developer.mozilla.org/en-US/docs/Glossary/Doctype
if !opts.DisableHtmlPreamble && e.Tag == "html" {
builder.WriteString("<!DOCTYPE html>")
}
isFragment := e.Tag == "fragment"
// Start with opening tag
if !isFragment {
builder.WriteString("<")
builder.WriteString(e.Tag)
}
// Sort the keys for consistent order
keys := make([]string, 0, len(e.Attrs))
for k := range e.Attrs {
keys = append(keys, k)
}
sort.Strings(keys)
// Append the attributes to the builder
for _, k := range keys {
e.renderAttrTo(k, builder)
}
// If it's a void element, close it and return
if _, exists := voidElements[e.Tag]; exists {
builder.WriteString(`>`)
return
}
if !isFragment {
// Close opening tag
builder.WriteString(`>`)
}
// Build the content
for _, child := range e.Children {
child.RenderTo(builder, opts)
}
if !isFragment {
// Append closing tag
builder.WriteString(`</`)
builder.WriteString(e.Tag)
builder.WriteString(`>`)
}
}
// return string representation of given attribute with its value
func (e *Element) renderAttrTo(attrName string, builder *strings.Builder) {
if _, exists := booleanAttrs[attrName]; exists {
// boolean attribute presents its name only if the value is "true"
if e.Attrs[attrName] == "true" {
builder.WriteString(` `)
builder.WriteString(attrName)
}
} else {
// regular attribute has a name and a value
attrVal := e.Attrs[attrName]
// A necessary check to to avoid adding extra quotes around values that are already single-quoted
// An example is '{"quantity": 5}'
isSingleQuoted := strings.HasPrefix(attrVal, "'") && strings.HasSuffix(attrVal, "'")
builder.WriteString(` `)
builder.WriteString(attrName)
builder.WriteString(`=`)
if !isSingleQuoted {
builder.WriteString(`"`)
}
builder.WriteString(attrVal)
if !isSingleQuoted {
builder.WriteString(`"`)
}
}
}
func (e *Element) Render() string {
return e.RenderWithOptions(RenderOptions{})
}
func (e *Element) RenderWithOptions(opts RenderOptions) string {
var builder strings.Builder
e.RenderTo(&builder, opts)
if opts.StyleManager != nil {
htmlContent := builder.String()
cssContent := opts.StyleManager.GenerateCSS()
// Define the <style> element with the generated CSS content
styleElement := fmt.Sprintf("<style>%s</style>", cssContent)
// Check if a <head> tag exists in the HTML content
headStartIndex := strings.Index(htmlContent, "<head>")
headEndIndex := strings.Index(htmlContent, "</head>")
if headStartIndex != -1 && headEndIndex != -1 {
// If <head> exists, inject the style content just before </head>
beforeHead := htmlContent[:headEndIndex]
afterHead := htmlContent[headEndIndex:]
modifiedHTML := beforeHead + styleElement + afterHead
return modifiedHTML
} else {
// If <head> does not exist, create it and inject the style content
// Assuming <html> tag exists and injecting <head> immediately after <html>
htmlTagEnd := strings.Index(htmlContent, ">") + 1
if htmlTagEnd > 0 {
beforeHTML := htmlContent[:htmlTagEnd]
afterHTML := htmlContent[htmlTagEnd:]
modifiedHTML := beforeHTML + "<head>" + styleElement + "</head>" + afterHTML
return modifiedHTML
}
}
}
// Return the original HTML content if no modifications were made
return builder.String()
}
func newElement(tag string, attrs attrs.Props, children ...Node) *Element {
return &Element{
Tag: tag,
Attrs: attrs,
Children: children,
}
}