-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender.go
More file actions
398 lines (337 loc) · 9.19 KB
/
render.go
File metadata and controls
398 lines (337 loc) · 9.19 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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package rx
import (
"encoding/binary"
"fmt"
"strconv"
"strings"
"sync"
)
type Node struct {
Entity // simple reference
TagName string
Classes string
Text string
Focused bool
Children []*Node
Attrs []Attr // for arbitrary HTML elements
visited bool
old Entity // for reuse nodes
hdl intentHandler
}
func (n *Node) SetText(text string) *Node { n.Text = text; return n }
func (n *Node) AddChildren(cs ...*Node) *Node { n.Children = append(n.Children, cs...); return n }
// DEPRECATE: use [Keep] instead
func (n *Node) GiveKey(ctx Context) *Node { n.Entity = ctx.ng.cnt.Inc(); return n }
func (n *Node) AddAttr(kv ...string) *Node {
// TODO(rdo) static check for the right number of arguments
for i := 0; i < len(kv); i += 2 {
seen := false
for j := range n.Attrs {
if n.Attrs[j].Name == kv[i] {
n.Attrs[j].Value = kv[i+1]
seen = true
}
}
if !seen {
n.Attrs = append(n.Attrs, Attr{Name: kv[i], Value: kv[i+1]})
}
}
return n
}
// ForwardEvents links the current node's events to another node by adding a data attribute.
// This allows events triggered on this node to be handled by the target node's event handlers.
func (n *Node) ForwardEvents(ctx Context, to *Node) {
if n.Entity == 0 {
n.GiveKey(ctx)
}
n.AddAttr("data-linked-entity", to.ElementID(ctx))
}
// GetAttr returns the value set for the attribute.
// An empty string is returned if no value is set.
func (n *Node) GetAttr(attr string) string {
for _, a := range n.Attrs {
if a.Name == attr {
return a.Value
}
}
return ""
}
// OnIntent attaches the action to the intent.
//
// When the intent is fired on the node (browser-side),
// the action is executed on the current context, leading to a new context.
// The new view is then rendered based on the new context.
func (n *Node) OnIntent(evt IntentType, h Action) *Node {
if h == nil {
return n
}
n.hdl[evt] = h
return n
}
// React is a executes state mutators on an event
func (n *Node) React(evt IntentType, mutators ...any) *Node {
return n.OnIntent(evt, Mutate(mutators...))
}
// Focus calls the [focus] method on the final element
//
// [focus]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus
func (n *Node) Focus(ctx Context) *Node { n.Focused = true; return n.GiveKey(ctx) }
// Set ARIA role, using the "role" property
// Useful for reliable tests
func (n *Node) AddRole(role string) *Node {
// it's "role", not "aria-role"
return n.AddAttr("role", role)
}
// AddClasses to a node.
// If the classes already exists, they are not modified.
// Empty classes are simply ignored.
//
// Example:
//
// GetNode("td").SetClass("table-cell"); td().AddClass("bg-blue")
func (n *Node) AddClasses(cls ...string) *Node {
c := strings.Join(cls, " ")
if n.Classes == "" {
n.Classes = c
} else {
n.Classes = n.Classes + " " + c
}
return n
}
// Can be used for attributes such as checkbox "checked", button "disabled"
// Example:
// GetNode("button").AddBoolAttr("disabled", isDisabled)
func (n *Node) AddBoolAttr(key string, val bool) *Node {
if val {
n.Attrs = append(n.Attrs, Attr{Name: key, Value: ""})
}
return n
}
func (n *Node) IsNothing() bool {
return n.TagName == "nothing"
}
// ElementID returns the Element.id property.
// This can be used in referencing, e.g. "for" properties.
func (n *Node) ElementID(ctx Context) string {
if n.Entity == 0 {
n.GiveKey(ctx)
}
return strconv.FormatUint(uint64(n.Entity), 10)
}
func printEntityTreeRec(n *Node, strb *strings.Builder, level int) {
if n == nil {
return
}
tabs := strings.Repeat("\t", level) + "| "
if n.Entity != 0 {
ntag := fmt.Sprintf(tabs+n.PrintInline()+"\n", n.TagName, n.Entity, n.Classes, n.Attrs)
strb.WriteString(ntag)
} else {
strb.WriteString(tabs + "non-entity-node\n")
}
for _, c := range n.Children {
printEntityTreeRec(c, strb, level+1)
}
}
// PrintEntityTree for debugging
// Running on the root node should show all entities
func (n *Node) PrintEntityTree() string {
var strb strings.Builder
printEntityTreeRec(n, &strb, 0)
return strb.String()
}
func (n *Node) PrintInline() string {
return fmt.Sprintf("%s entity='%d' class='%s' attrs='%v'", n.TagName, n.Entity, n.Classes, n.Attrs)
}
// DEPRECATED: use [Reuse] instead
func ReuseFrom(ctx Context, nt Entity) *Node {
n := GetNode("reuse")
n.old = nt
return n.GiveKey(ctx)
}
// Nothing returns a node that does not appear in the DOM.
// This is useful in conditionals, making branches regular, e.g.:
//
// x := Nothing()
// if val > threshold {
// x = alert()
// }
//
// During the rendering phase, Nothing is optimized away; which means that:
//
// 1. Terminal nodes will simply not exist
// 2. Children of Nothing nodes will become children of the parent of the Nothing node.
func Nothing(ws ...*Node) *Node { return GetNode("nothing").AddChildren(ws...) }
type Attr struct{ Name, Value string }
type flist struct {
next *flist
nodes []Node
}
var npool = struct {
flist
free *flist
nmtx sync.Mutex
}{flist: flist{nodes: make([]Node, 0, 512)}}
// GetNode returns a node from the pool, minimizing allocations.
// The pool is re-initialized as a whole during each cycle.
func GetNode(tagname string) *Node {
npool.nmtx.Lock()
defer npool.nmtx.Unlock()
// invariant: pool next is nil iff len(nodes) < cap(nodes)
pool := &npool.flist
for pool.next != nil {
pool = pool.next
}
pool.nodes = pool.nodes[:len(pool.nodes)+1]
if len(pool.nodes) == cap(pool.nodes) {
if npool.free != nil {
pool.next = &flist{nodes: npool.free.nodes[:0]}
npool.free = npool.free.next
} else {
pool.next = &flist{nodes: make([]Node, 0, 512)}
}
}
last := &pool.nodes[len(pool.nodes)-1]
// reset all fields, preserve space already alloc for values
*last = Node{TagName: tagname, Attrs: last.Attrs[:0], Children: last.Children[:0]}
return last
}
// FreePool de-allocate all nodes at once.
func FreePool() {
npool.nmtx.Lock()
defer npool.nmtx.Unlock()
npool.free, npool.next = npool.next, nil
npool.nodes = npool.nodes[:0]
}
// serialize does a preorder visit of the node tree, keeping track of nodes in the entity tree
func serialize(n *Node, tree *etree, ctr *Counter, vm XAS) XAS {
if n.visited {
panic("cycle detected")
}
n.visited = true
switch n.TagName {
case "":
panic("empty tag name")
case "nothing":
for _, c := range n.Children {
assert(c != nil, "nil child in node: %v", n)
vm = serialize(c, tree, ctr, vm)
}
return vm
case "reuse":
// Reuse ports the old tree to the new one
// ReID is then updating the ID, so that the handlers fire on the correct element
vm = vm.AddInstr(OpReuse, strconv.FormatUint(uint64(n.old), 10))
tree.reuse(n.old, n.Entity, ctr, func(from, to Entity) {
vm = vm.AddInstr(OpReID,
strconv.FormatUint(uint64(from), 10),
strconv.FormatUint(uint64(to), 10))
})
return vm
}
vm = vm.AddInstr(OpCreateElement, n.TagName)
if len(n.Classes) > 0 {
vm = vm.AddInstr(OpSetClass, n.Classes)
}
if n.Entity == 0 && n.hdl.Some() {
// curtesy, create the entity for user
n.Entity = ctr.Inc()
}
var idx int
if n.Entity != 0 {
idx = tree.add(n.Entity)
if n.hdl.Some() {
tree.addHandler(n.hdl)
}
vm = vm.AddInstr(OpSetID, strconv.FormatUint(uint64(n.Entity), 10))
}
for _, a := range n.Attrs {
vm = vm.AddInstr(OpSetAttr, a.Name, a.Value)
}
if n.Text != "" {
vm = vm.AddInstr(OpAddText, n.Text)
}
for _, c := range n.Children {
vm = serialize(c, tree, ctr, vm)
}
if n.Entity != 0 {
tree.closeScope(idx)
}
return vm.AddInstr(OpNext)
}
// Build bottoms-out the rendering tree: a node is a widget that is self
func (n *Node) Build(_ Context) *Node { return n }
// ToHTML creates a textual representation of the node tree.
// This is useful for server-side rendering.
// As such, there is no way to attach a callback to an entity.
func (n *Node) ToHTML() string {
var buf strings.Builder
serializeHTML(n, &buf)
return buf.String()
}
func serializeHTML(n *Node, buf *strings.Builder) {
if n.visited {
panic("cycle detected")
}
n.visited = true
// skip nothing node
if n.IsNothing() {
for _, c := range n.Children {
assert(c != nil, "nil child in node: %v", n)
serializeHTML(c, buf)
}
return
}
fmt.Fprintf(buf, "<%s ", n.TagName)
if len(n.Classes) > 0 {
fmt.Fprintf(buf, "class=\"%s\" ", n.Classes)
}
for _, a := range n.Attrs {
fmt.Fprintf(buf, "%s=\"%s\"", a.Name, a.Value)
}
fmt.Fprint(buf, ">")
if n.Text != "" {
fmt.Fprint(buf, n.Text)
}
for _, c := range n.Children {
serializeHTML(c, buf)
}
fmt.Fprintf(buf, "</%s>", n.TagName)
}
// BuildWidgets creates a slice of nodes by rendering each widget.
// It takes care of ignoring nil values.
func BuildWidgets(ctx Context, ws []Widget) []*Node {
ns := make([]*Node, len(ws))
j := 0
for _, w := range ws {
if w == nil {
continue
}
ns[j] = w.Build(ctx)
j++
}
return ns[:j]
}
//go:generate go tool rxabi -type OpType
// using an alias let's us run go generate but do not alter existing code
type OpType = byte
const (
OpTerm OpType = iota
OpCreateElement
OpSetClass
OpSetID
OpSetAttr
OpAddText
OpReuse
OpReID
OpNext
)
type XAS []byte
func (vm XAS) AddInstr(code byte, val ...string) XAS {
vm = append(vm, code)
for i := range val {
vm = binary.BigEndian.AppendUint16(vm, uint16(len(val[i])))
vm = append(vm, val[i]...)
}
return vm
}