Repository navigation
Expand file tree
/
Copy pathnode.go
More file actions
710 lines (616 loc) · 24.4 KB
/
Copy pathnode.go
File metadata and controls
710 lines (616 loc) · 24.4 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
package preveltekit
import (
"reflect"
"strings"
)
// Node represents a node in the declarative UI tree.
// Nodes are constructed at build-time and walked to generate:
// 1. HTML with markers (for SSR)
// 2. WASM wiring code (for hydration)
type Node interface {
isNode() // only the framework's node types implement Node
}
// NodeAttr represents an attribute that can be applied to an element.
type NodeAttr interface {
isAttr() // only the framework's attribute types implement NodeAttr
}
// =============================================================================
// Text Node (auto-escaped text content)
// =============================================================================
// TextNode represents plain text content that is HTML-escaped on render.
// Used by typed element functions (Div, Span, etc.) to safely handle string children.
type TextNode struct {
Text string
}
func (t *TextNode) isNode() {}
// =============================================================================
// HTML Node
// =============================================================================
// HtmlNode represents a typed HTML element.
// Supports chainable AttrIf, On, and Bind methods.
type HtmlNode struct {
Tag string // e.g. "div", "span"
Attrs []string // Pre-formatted static attrs: `class="foo"`, `type="text"`
DynAttrs []*DynAttrAttr // Dynamic attributes needing render-time IDs
Children []any // Child content: Node, *Store[Component], AnyGetter, etc.
IsVoid bool // true for br, hr, img, input, etc.
// Chainable bindings
AttrConds []*AttrCond // conditional attributes applied to first tag
Events []*HtmlEvent // event bindings applied to first tag
BoundStore any // two-way binding store (*Store[string], *Store[int], *Store[bool])
}
// AttrCond represents a conditional attribute binding.
// Used by HtmlNode.AttrIf() to conditionally set attribute values.
type AttrCond struct {
Name string // attribute name (e.g., "class", "href", "disabled")
Cond func() bool // condition; re-evaluated when a store it reads changes
TrueValue any // value when true: string or *Store[T]
FalseValue any // value when false: string or *Store[T] (optional)
}
// HtmlEvent represents an event binding for HtmlNode.
// Used by HtmlNode.On() to attach event handlers.
type HtmlEvent struct {
ID string // unique handler ID for registry lookup
Event string // event name (e.g., "click", "submit")
}
func (h *HtmlNode) isNode() {}
// elementID returns the id attribute needed to find the element during
// hydration: the first event's handler ID, a new class ID for conditional
// attributes, or "" if the element needs none.
func (h *HtmlNode) elementID(c *IDCounter) string {
if len(h.Events) > 0 {
return h.Events[0].ID
}
if len(h.AttrConds) > 0 {
return c.NextClassID()
}
return ""
}
// value returns the attribute value for the current condition.
func (ac *AttrCond) value() string {
if ac.Cond() {
return evalAttrValue(ac.TrueValue)
}
return evalAttrValue(ac.FalseValue)
}
// =============================================================================
// RawHTML Node (unescaped inline HTML text)
// =============================================================================
// RawHTMLNode represents unescaped HTML text content.
// Unlike TextNode (which escapes), this renders the string as-is.
// Used for HTML entities (⚡) and inline markup (<code>foo</code>).
type RawHTMLNode struct {
HTML string
}
func (r *RawHTMLNode) isNode() {}
// RawHTML creates an unescaped HTML text node.
// Example: RawHTML("⚡"), RawHTML("<code>foo</code>")
func RawHTML(html string) *RawHTMLNode {
return &RawHTMLNode{HTML: html}
}
// =============================================================================
// Fragment Node (groups multiple children without a parent element)
// =============================================================================
// FragmentNode groups multiple child nodes without adding a parent element.
// Used where a single Node return is needed but multiple siblings are desired.
type FragmentNode struct {
Children []Node
}
func (f *FragmentNode) isNode() {}
// Fragment creates a node that groups children without a wrapping element.
// Example: Fragment(Section(...), Section(...), Footer(...))
func Fragment(children ...Node) *FragmentNode {
return &FragmentNode{Children: children}
}
// =============================================================================
// Typed Element Functions
// =============================================================================
// isVoidElement returns true for HTML5 void elements (self-closing, no children).
func isVoidElement(tag string) bool {
switch tag {
case "area", "base", "br", "col", "embed", "hr", "img", "input",
"link", "meta", "source", "track", "wbr":
return true
}
return false
}
// element is the internal helper for typed element functions.
// It populates structured fields (Tag, Attrs, DynAttrs, Children)
// instead of pre-serializing HTML into Parts.
func element(tag string, parts ...any) *HtmlNode {
h := &HtmlNode{Tag: tag, IsVoid: isVoidElement(tag)}
for _, part := range parts {
switch v := part.(type) {
case *StaticAttr:
h.Attrs = append(h.Attrs, v.Name+`="`+escapeHTML(v.Value)+`"`)
case *DynAttrAttr:
h.DynAttrs = append(h.DynAttrs, v)
case string:
h.Children = append(h.Children, &TextNode{Text: v})
default:
h.Children = append(h.Children, part)
}
}
return h
}
// El creates a typed element node for an arbitrary HTML tag.
// String children are auto-escaped. NodeAttr values become attributes.
// Example: El("custom-element", Attr("class", "foo"), "content")
func El(tag string, parts ...any) *HtmlNode {
return element(tag, parts...)
}
// --- Sectioning / Structural ---
func Div(parts ...any) *HtmlNode { return element("div", parts...) }
func Main(parts ...any) *HtmlNode { return element("main", parts...) }
func Header(parts ...any) *HtmlNode { return element("header", parts...) }
func Footer(parts ...any) *HtmlNode { return element("footer", parts...) }
func Nav(parts ...any) *HtmlNode { return element("nav", parts...) }
func Section(parts ...any) *HtmlNode { return element("section", parts...) }
func Article(parts ...any) *HtmlNode { return element("article", parts...) }
func Aside(parts ...any) *HtmlNode { return element("aside", parts...) }
// --- Headings ---
func H1(parts ...any) *HtmlNode { return element("h1", parts...) }
func H2(parts ...any) *HtmlNode { return element("h2", parts...) }
func H3(parts ...any) *HtmlNode { return element("h3", parts...) }
func H4(parts ...any) *HtmlNode { return element("h4", parts...) }
func H5(parts ...any) *HtmlNode { return element("h5", parts...) }
func H6(parts ...any) *HtmlNode { return element("h6", parts...) }
// --- Text ---
func P(parts ...any) *HtmlNode { return element("p", parts...) }
func Span(parts ...any) *HtmlNode { return element("span", parts...) }
func Strong(parts ...any) *HtmlNode { return element("strong", parts...) }
func Em(parts ...any) *HtmlNode { return element("em", parts...) }
func B(parts ...any) *HtmlNode { return element("b", parts...) }
func I(parts ...any) *HtmlNode { return element("i", parts...) }
func U(parts ...any) *HtmlNode { return element("u", parts...) }
func S(parts ...any) *HtmlNode { return element("s", parts...) }
func Small(parts ...any) *HtmlNode { return element("small", parts...) }
func Mark(parts ...any) *HtmlNode { return element("mark", parts...) }
func Sub(parts ...any) *HtmlNode { return element("sub", parts...) }
func Sup(parts ...any) *HtmlNode { return element("sup", parts...) }
func Abbr(parts ...any) *HtmlNode { return element("abbr", parts...) }
func Cite(parts ...any) *HtmlNode { return element("cite", parts...) }
func Q(parts ...any) *HtmlNode { return element("q", parts...) }
func Blockquote(parts ...any) *HtmlNode { return element("blockquote", parts...) }
func Code(parts ...any) *HtmlNode { return element("code", parts...) }
func Pre(parts ...any) *HtmlNode { return element("pre", parts...) }
func Kbd(parts ...any) *HtmlNode { return element("kbd", parts...) }
func Samp(parts ...any) *HtmlNode { return element("samp", parts...) }
func Var(parts ...any) *HtmlNode { return element("var", parts...) }
// --- Lists ---
func Ul(parts ...any) *HtmlNode { return element("ul", parts...) }
func Ol(parts ...any) *HtmlNode { return element("ol", parts...) }
func Li(parts ...any) *HtmlNode { return element("li", parts...) }
func Dl(parts ...any) *HtmlNode { return element("dl", parts...) }
func Dt(parts ...any) *HtmlNode { return element("dt", parts...) }
func Dd(parts ...any) *HtmlNode { return element("dd", parts...) }
// --- Links / Media ---
func A(parts ...any) *HtmlNode { return element("a", parts...) }
func Img(parts ...any) *HtmlNode { return element("img", parts...) }
func Audio(parts ...any) *HtmlNode { return element("audio", parts...) }
func Video(parts ...any) *HtmlNode { return element("video", parts...) }
func Source(parts ...any) *HtmlNode { return element("source", parts...) }
func Picture(parts ...any) *HtmlNode { return element("picture", parts...) }
func Figure(parts ...any) *HtmlNode { return element("figure", parts...) }
func Figcaption(parts ...any) *HtmlNode { return element("figcaption", parts...) }
func Canvas(parts ...any) *HtmlNode { return element("canvas", parts...) }
func Svg(parts ...any) *HtmlNode { return element("svg", parts...) }
// --- Tables ---
func Table(parts ...any) *HtmlNode { return element("table", parts...) }
func Thead(parts ...any) *HtmlNode { return element("thead", parts...) }
func Tbody(parts ...any) *HtmlNode { return element("tbody", parts...) }
func Tfoot(parts ...any) *HtmlNode { return element("tfoot", parts...) }
func Tr(parts ...any) *HtmlNode { return element("tr", parts...) }
func Th(parts ...any) *HtmlNode { return element("th", parts...) }
func Td(parts ...any) *HtmlNode { return element("td", parts...) }
func Caption(parts ...any) *HtmlNode { return element("caption", parts...) }
func Colgroup(parts ...any) *HtmlNode { return element("colgroup", parts...) }
func Col(parts ...any) *HtmlNode { return element("col", parts...) }
// --- Forms ---
func Form(parts ...any) *HtmlNode { return element("form", parts...) }
func Input(parts ...any) *HtmlNode { return element("input", parts...) }
func Textarea(parts ...any) *HtmlNode { return element("textarea", parts...) }
func Select(parts ...any) *HtmlNode { return element("select", parts...) }
func Option(parts ...any) *HtmlNode { return element("option", parts...) }
func Optgroup(parts ...any) *HtmlNode { return element("optgroup", parts...) }
func Button(parts ...any) *HtmlNode { return element("button", parts...) }
func Label(parts ...any) *HtmlNode { return element("label", parts...) }
func Fieldset(parts ...any) *HtmlNode { return element("fieldset", parts...) }
func Legend(parts ...any) *HtmlNode { return element("legend", parts...) }
func Datalist(parts ...any) *HtmlNode { return element("datalist", parts...) }
func Output(parts ...any) *HtmlNode { return element("output", parts...) }
func Progress(parts ...any) *HtmlNode { return element("progress", parts...) }
func Meter(parts ...any) *HtmlNode { return element("meter", parts...) }
// --- Semantic ---
func Details(parts ...any) *HtmlNode { return element("details", parts...) }
func Summary(parts ...any) *HtmlNode { return element("summary", parts...) }
func Dialog(parts ...any) *HtmlNode { return element("dialog", parts...) }
func Time(parts ...any) *HtmlNode { return element("time", parts...) }
func Data(parts ...any) *HtmlNode { return element("data", parts...) }
func Address(parts ...any) *HtmlNode { return element("address", parts...) }
func Ruby(parts ...any) *HtmlNode { return element("ruby", parts...) }
func Rt(parts ...any) *HtmlNode { return element("rt", parts...) }
func Rp(parts ...any) *HtmlNode { return element("rp", parts...) }
// --- Embedded ---
func Iframe(parts ...any) *HtmlNode { return element("iframe", parts...) }
func Embed(parts ...any) *HtmlNode { return element("embed", parts...) }
func Object(parts ...any) *HtmlNode { return element("object", parts...) }
// --- Misc ---
func Br(parts ...any) *HtmlNode { return element("br", parts...) }
func Hr(parts ...any) *HtmlNode { return element("hr", parts...) }
func Wbr(parts ...any) *HtmlNode { return element("wbr", parts...) }
func Area(parts ...any) *HtmlNode { return element("area", parts...) }
func Base(parts ...any) *HtmlNode { return element("base", parts...) }
func Link(parts ...any) *HtmlNode { return element("link", parts...) }
func Meta(parts ...any) *HtmlNode { return element("meta", parts...) }
func Script(parts ...any) *HtmlNode { return element("script", parts...) }
func Noscript(parts ...any) *HtmlNode { return element("noscript", parts...) }
func Template(parts ...any) *HtmlNode { return element("template", parts...) }
func Map(parts ...any) *HtmlNode { return element("map", parts...) }
func Del(parts ...any) *HtmlNode { return element("del", parts...) }
func Ins(parts ...any) *HtmlNode { return element("ins", parts...) }
// AttrIf adds a conditional attribute to the first HTML tag. cond is
// re-evaluated whenever a store it reads (with Get) changes.
// Values can be string literals or *Store[T] for reactive values.
// Multiple AttrIf calls for the same attribute name merge additively.
//
// Examples:
//
// Button("Save").AttrIf("class", dirty.Get, "active") // adds "active" when true
// Button("Save").AttrIf("class", dirty.Get, "active", "inactive") // "active" when true, "inactive" when false
// A("Link").AttrIf("href", loggedIn.Get, urlStore, "/fallback") // reactive value with fallback
func (h *HtmlNode) AttrIf(name string, cond func() bool, values ...any) *HtmlNode {
ac := &AttrCond{Name: name, Cond: cond}
if len(values) >= 1 {
ac.TrueValue = values[0]
}
if len(values) >= 2 {
ac.FalseValue = values[1]
}
h.AttrConds = append(h.AttrConds, ac)
return h
}
// On attaches an event handler to the first HTML tag.
// The handler ID is auto-generated for registry lookup during hydration.
// Returns the HtmlNode for chaining.
//
// Example:
//
// Button("Click").On("click", handler)
// Form(...).On("submit", handler).PreventDefault()
func (h *HtmlNode) On(event string, handler func()) *HtmlNode {
// Register handler in global registry for WASM hydration
id := RegisterHandler(handler)
h.Events = append(h.Events, &HtmlEvent{
ID: id,
Event: event,
})
return h
}
// PreventDefault adds the preventDefault modifier to the last event.
// Must be called after On. The modifier is stored in the handler registry
// so WASM can apply event.preventDefault() without needing it in bindings.
func (h *HtmlNode) PreventDefault() *HtmlNode {
if len(h.Events) > 0 {
last := h.Events[len(h.Events)-1]
handlerModifiers[last.ID] = append(handlerModifiers[last.ID], "preventDefault")
}
return h
}
// StopPropagation adds the stopPropagation modifier to the last event.
// Must be called after On. The modifier is stored in the handler registry
// so WASM can apply event.stopPropagation() without needing it in bindings.
func (h *HtmlNode) StopPropagation() *HtmlNode {
if len(h.Events) > 0 {
last := h.Events[len(h.Events)-1]
handlerModifiers[last.ID] = append(handlerModifiers[last.ID], "stopPropagation")
}
return h
}
// Bind attaches a two-way binding to the first HTML element.
// The store type determines the binding behavior:
// - *Store[string], *Store[int]: binds to input value
// - *Store[bool]: binds to checkbox checked state
//
// Example:
//
// Input(Attr("type", "text")).Bind(nameStore)
// Input(Attr("type", "checkbox")).Bind(darkModeStore)
func (h *HtmlNode) Bind(store any) *HtmlNode {
h.BoundStore = store
return h
}
// =============================================================================
// Bind Node (reactive text binding)
// =============================================================================
// BindNode represents a reactive binding to a store value.
type BindNode struct {
StoreRef any // The actual store reference (for evaluation)
IsHTML bool // true for raw HTML binding
}
func (b *BindNode) isNode() {}
// Bind creates a reactive text binding to a store.
func Bind[T any](store *Store[T]) *BindNode {
return &BindNode{
StoreRef: store,
IsHTML: false,
}
}
// BindAsHTML creates a reactive HTML binding (renders as innerHTML).
func BindAsHTML[T any](store *Store[T]) *BindNode {
return &BindNode{
StoreRef: store,
IsHTML: true,
}
}
// =============================================================================
// If Node (conditional rendering)
// =============================================================================
// IfNode represents conditional rendering with optional else-if and else branches.
type IfNode struct {
Branches []IfBranch
ElseNode []Node
}
func (i *IfNode) isNode() {}
// IfBranch represents a single if/else-if branch.
type IfBranch struct {
Cond func() bool
Children []Node
}
// If creates a conditional rendering node. cond is re-evaluated whenever a
// store it reads (with Get) changes:
//
// p.If(func() bool { return count.Get() > 0 }, p.P("positive"))
// p.If(loading.Get, p.P("Loading...")) // a *Store[bool]'s Get is a func() bool
func If(cond func() bool, children ...Node) *IfNode {
return &IfNode{
Branches: []IfBranch{{Cond: cond, Children: children}},
}
}
// ElseIf adds an else-if branch to the conditional.
func (i *IfNode) ElseIf(cond func() bool, children ...Node) *IfNode {
i.Branches = append(i.Branches, IfBranch{Cond: cond, Children: children})
return i
}
// Else adds an else branch to the conditional.
func (i *IfNode) Else(children ...Node) *IfNode {
i.ElseNode = children
return i
}
// =============================================================================
// Each Node (list rendering)
// =============================================================================
// EachNode represents list iteration with optional else for empty list.
type EachNode struct {
Body func(item any, index int) Node // Template function for each item
ElseNode []Node // Content for empty list
// Type-erased access to the List[T], set by Each
items func() []any // current items
onChange func(func()) (unsub func()) // subscribe to list changes
}
func (e *EachNode) isNode() {}
// Each creates a list rendering node.
// The body function receives each item and its index.
func Each[T comparable](list *List[T], body func(item T, index int) Node) *EachNode {
return &EachNode{
Body: func(item any, index int) Node {
return body(item.(T), index)
},
items: func() []any {
items := make([]any, len(list.items))
for i, item := range list.items {
items[i] = item
}
return items
},
onChange: list.subscribeAny,
}
}
// Else adds content to show when the list is empty.
func (e *EachNode) Else(children ...Node) *EachNode {
e.ElseNode = children
return e
}
// =============================================================================
// Component Node (nested component)
// =============================================================================
// ComponentNode represents a nested component.
type ComponentNode struct {
Name string // Component type name (derived from instance)
Instance any // The actual component instance
Children []Node // Slot content
renderCache Node // cached Render() result (used by WASM to avoid double Render)
}
func (c *ComponentNode) isNode() {}
// Comp creates a nested component node from a component instance.
// The component name is derived from the type via reflection.
// Example: Comp(&Badge{Label: p.New("New")})
func Comp(instance any, content ...any) *ComponentNode {
c := &ComponentNode{
Name: typeName(instance),
Instance: instance,
}
for _, item := range content {
if v, ok := item.(Node); ok {
c.Children = append(c.Children, v)
}
}
return c
}
// =============================================================================
// Slot Node (for child component content)
// =============================================================================
// SlotNode represents where child content should be inserted.
type SlotNode struct{}
func (s *SlotNode) isNode() {}
// Slot creates a slot placeholder for child content.
func Slot() *SlotNode {
return &SlotNode{}
}
// typeName returns the name of v's type, dereferencing pointers.
func typeName(v any) string {
t := reflect.TypeOf(v)
if t.Kind() == reflect.Pointer {
t = t.Elem()
}
return t.Name()
}
// componentName returns the type name of a component with a lowercase first letter.
func componentName(c Component) string {
if c == nil {
return ""
}
return lowerFirst(typeName(c))
}
// lowerFirst returns s with an ASCII uppercase first letter lowercased.
func lowerFirst(s string) string {
if s == "" || s[0] < 'A' || s[0] > 'Z' {
return s
}
return string(s[0]+'a'-'A') + s[1:]
}
// =============================================================================
// Attributes
// =============================================================================
// StaticAttr represents a static attribute (no reactive binding).
type StaticAttr struct {
Name string
Value string
}
func (s *StaticAttr) isAttr() {}
// DynAttrAttr represents a dynamic attribute with mixed string/store parts.
type DynAttrAttr struct {
Name string
Parts []any // mix of string and *Store[T]
}
func (d *DynAttrAttr) isAttr() {}
// value returns the current attribute value: the string parts and the
// current store values concatenated.
func (d *DynAttrAttr) value() string {
var sb strings.Builder
for _, part := range d.Parts {
switch v := part.(type) {
case string:
sb.WriteString(v)
case AnyGetter:
sb.WriteString(anyToString(v.GetAny()))
}
}
return sb.String()
}
// Attr creates an attribute. Parts can be strings and stores.
// With only string parts, it's static (no reactive binding).
// With any store parts, it becomes a dynamic attribute that updates reactively.
func Attr(name string, parts ...any) NodeAttr {
var sb strings.Builder
for _, p := range parts {
s, ok := p.(string)
if !ok {
return &DynAttrAttr{Name: name, Parts: parts}
}
sb.WriteString(s)
}
return &StaticAttr{Name: name, Value: sb.String()}
}
// =============================================================================
// Value Helpers
// =============================================================================
// anyToString converts any value to string without fmt.
func anyToString(v any) string {
switch val := v.(type) {
case string:
return val
case int:
return itoa(val)
case bool:
if val {
return "true"
}
return "false"
case float64:
return ftoa(val)
default:
return ""
}
}
// Itoa converts an int to a string without importing strconv.
func Itoa(n int) string { return itoa(n) }
func itoa(n int) string {
if n == 0 {
return "0"
}
neg := n < 0
if neg {
n = -n
}
var buf [20]byte
i := len(buf)
for n > 0 {
i--
buf[i] = byte('0' + n%10)
n /= 10
}
if neg {
i--
buf[i] = '-'
}
return string(buf[i:])
}
func ftoa(f float64) string {
if f == 0 {
return "0"
}
neg := f < 0
if neg {
f = -f
}
intPart := int(f)
fracPart := f - float64(intPart)
result := []byte(itoa(intPart))
if fracPart > 0.0000001 {
result = append(result, '.')
for i := 0; i < 6 && fracPart > 0.0000001; i++ {
fracPart *= 10
digit := int(fracPart)
result = append(result, byte('0'+digit))
fracPart -= float64(digit)
}
}
if neg {
return "-" + string(result)
}
return string(result)
}
// escapeHTML escapes HTML special characters, in text and attribute values.
func escapeHTML(s string) string {
var result []byte
for i := 0; i < len(s); i++ {
switch s[i] {
case '&':
result = append(result, []byte("&")...)
case '<':
result = append(result, []byte("<")...)
case '>':
result = append(result, []byte(">")...)
case '"':
result = append(result, []byte(""")...)
default:
result = append(result, s[i])
}
}
return string(result)
}
// evalAttrValue extracts the current string value from an attribute value.
// Handles plain strings and typed stores.
func evalAttrValue(v any) string {
if v == nil {
return ""
}
switch val := v.(type) {
case string:
return val
case AnyGetter:
return anyToString(val.GetAny())
}
return ""
}