Repository navigation
Expand file tree
/
Copy pathserialize.go
More file actions
267 lines (249 loc) · 7.88 KB
/
Copy pathserialize.go
File metadata and controls
267 lines (249 loc) · 7.88 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
package dom
import (
"webtyp.com/escape"
"webtyp.com/fmt"
)
type childRenderer func(Component) string
type elementObserver func(*Element)
// errChildrenBesideBinding is the panic text when an element has both BindChildren and
// static Child(...) content: its signal owns the children.
const errChildrenBesideBinding = "dom: this element uses BindChildren and also has Child(...) content — the signal owns the children: put the first nodes in the signal (NewNodes(...) or Set(...) before rendering) instead of Child(...)"
// serializeElement renders an Element tree into an HTML string.
// renderChild resolves Component children to HTML (SSR vs WASM lifecycle tracking).
// observer is an optional callback invoked for each Element in the tree (used by WASM to collect pending events).
func serializeElement(el *Element, renderChild childRenderer, observer ...elementObserver) string {
if el == nil {
return ""
}
beginPass()
defer endPass()
var obs elementObserver
if len(observer) > 0 {
obs = observer[0]
}
// One fmt.Builder for the whole tree, not one string per node glued
// together with +=: string is immutable, so s += x reallocates and
// recopies everything s already holds, every time — for a tree with N
// bytes of total output that is O(N²) copying, not O(N), because every
// parent re-copies the already-serialized text of all its children each
// time it appends the next one. fmt.Builder (this package's answer to
// strings.Builder — dom/AGENTS.md bans the stdlib one) grows one buffer
// amortized and pays for the copy once.
b := fmt.Convert()
writeElement(b, el, renderChild, obs)
return b.String()
}
type resolvedElement struct {
classes []string
attrs []fmt.KeyValue
styles []fmt.KeyValue
textContent string
hasTextContent bool
boundChildren []*Element
hasBoundChildren bool
}
// evalBindings resolves el's static attributes/classes together with the initial values of its bindings.
func evalBindings(el *Element, stampChildIDs bool) resolvedElement {
res := resolvedElement{
classes: append([]string(nil), el.classes...),
attrs: append([]fmt.KeyValue(nil), el.attrs...),
styles: append([]fmt.KeyValue(nil), el.styles...),
}
for _, bind := range el.bindings {
switch bind.kind {
case "text":
if bind.signal != nil {
if sig, ok := bind.signal.(*SignalString); ok {
res.textContent = sig.Get()
}
} else if bind.fnString != nil {
res.textContent = bind.fnString()
}
res.hasTextContent = true
case "attr":
val := ""
if bind.signal != nil {
if sig, ok := bind.signal.(*SignalString); ok {
val = sig.Get()
}
} else if bind.fnString != nil {
val = bind.fnString()
}
found := false
for i, attr := range res.attrs {
if attr.Key == bind.name {
res.attrs[i].Value = val
found = true
break
}
}
if !found {
res.attrs = append(res.attrs, fmt.KeyValue{Key: bind.name, Value: val})
}
case "styleprop":
val := ""
if bind.signal != nil {
if sig, ok := bind.signal.(*SignalString); ok {
val = sig.Get()
}
} else if bind.fnString != nil {
val = bind.fnString()
}
found := false
for i, st := range res.styles {
if st.Key == bind.name {
res.styles[i].Value = val
found = true
break
}
}
if !found {
res.styles = append(res.styles, fmt.KeyValue{Key: bind.name, Value: val})
}
case "class":
on := false
if bind.signal != nil {
if sig, ok := bind.signal.(*SignalBool); ok {
on = sig.Get()
}
} else if bind.fnBool != nil {
on = bind.fnBool()
}
if on {
res.classes = append(res.classes, bind.name)
}
case "attrbool":
on := false
if bind.signal != nil {
if sig, ok := bind.signal.(*SignalBool); ok {
on = sig.Get()
}
} else if bind.fnBool != nil {
on = bind.fnBool()
}
if on {
res.attrs = append(res.attrs, fmt.KeyValue{Key: bind.name, Value: ""})
}
case "state":
on := false
if bind.signal != nil {
if sig, ok := bind.signal.(*SignalBool); ok {
on = sig.Get()
}
} else if bind.fnBool != nil {
on = bind.fnBool()
}
if on {
res.attrs = append(res.attrs, fmt.KeyValue{Key: bind.state.Key(), Value: bind.state.Value()})
}
case "value":
val := ""
if bind.signal != nil {
if sig, ok := bind.signal.(*SignalString); ok {
val = sig.Get()
}
}
res.attrs = append(res.attrs, fmt.KeyValue{Key: "value", Value: val})
case "children":
// The signal owns the element's children, on the server and in the
// browser alike: both render exactly sig.Get().
if sig, ok := bind.signal.(*SignalNodes); ok {
rows := sig.Get()
if stampChildIDs {
// In the browser every row gets an identity, as
// reconcileChildren gives the rows it inserts: a row drawn
// here without one carries no reconcile mark, so the next
// update could never remove it.
for _, n := range rows {
if n.key == "" && n.id == "" {
n.id = generateID()
}
}
}
res.boundChildren = append(res.boundChildren, rows...)
}
res.hasBoundChildren = true
}
}
if res.hasBoundChildren && len(el.children) > 0 {
panic(errChildrenBesideBinding)
}
return res
}
// writeElement appends el's HTML to b. obs is nil on the SSR path and
// non-nil on WASM (see serializeElement) — hasObserver below is exactly the
// old "was an observer passed" check, just derived from a plain nil check
// now that obs is no longer a variadic slice at this layer.
func writeElement(b *fmt.Builder, el *Element, renderChild childRenderer, obs elementObserver) {
if el == nil {
return
}
hasObserver := obs != nil
// Auto-generating an id for a bound/eventful element only matters where
// something will later look that id up in a live DOM to patch or wire it
// — the WASM path, signaled by the presence of an observer (it collects
// pending events for exactly that purpose). SSR has no live DOM: gating
// this on hasObserver keeps it out of that path, where it used to leak
// into elementToHTML/(*Element).String() after unifying the two
// serializers, minting a fresh id on every render of the same tree and
// making SSR output for any bound element non-deterministic.
//
// A KEYED element joins that list for the same reason: Key is the author's
// identity contract, and (*Element).Ref resolves the live node through the
// id dom put on it here. Without an id a keyed element is unreachable and
// Ref would answer a silent false. Still inside the hasObserver gate — SSR
// emits no id for a key, so (*Element).String stays byte-identical across
// renders.
if hasObserver {
if (len(el.events) > 0 || len(el.bindings) > 0 || el.autofocus || el.key != "") && el.id == "" {
el.id = generateID()
}
obs(el)
}
b.WriteString("<").WriteString(el.tag)
if el.id != "" {
claimID(el.id, el.tag)
b.WriteString(" id='").WriteString(escape.HTML(el.id)).WriteString("'")
}
res := evalBindings(el, hasObserver)
if len(res.classes) > 0 {
b.WriteString(" class='")
for i, c := range res.classes {
if i > 0 {
b.WriteString(" ")
}
b.WriteString(escape.HTML(c))
}
b.WriteString("'")
}
for _, attr := range res.attrs {
b.WriteString(" ").WriteString(escape.HTML(attr.Key)).
WriteString("='").WriteString(escape.HTML(attr.Value)).WriteString("'")
}
b.WriteString(">")
if el.void {
return
}
if res.hasTextContent {
b.WriteString(escape.HTML(res.textContent))
} else {
for _, node := range res.boundChildren {
writeElement(b, node, renderChild, obs)
}
for _, child := range el.children {
switch v := child.(type) {
case *Element:
writeElement(b, v, renderChild, obs)
case TrustedHTML:
b.WriteString(string(v))
case string:
b.WriteString(escape.HTML(v))
case Component:
b.WriteString(renderChild(v))
default:
b.WriteString(escape.HTML(fmt.Sprint(v)))
}
}
}
b.WriteString("</").WriteString(el.tag).WriteString(">")
}