-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender_wasm.go
More file actions
986 lines (922 loc) · 28 KB
/
Copy pathrender_wasm.go
File metadata and controls
986 lines (922 loc) · 28 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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
//go:build js
package wui
import (
"fmt"
"strconv"
"strings"
"syscall/js"
)
// ansiPalette maps ANSI color indices 0-15 to hex colors for use in
// CSS, since ANSI indices are meaningless to the browser.
var ansiPalette = [16]string{
"#000000", "#800000", "#008000", "#808000",
"#000080", "#800080", "#008080", "#c0c0c0",
"#808080", "#ff0000", "#00ff00", "#ffff00",
"#0000ff", "#ff00ff", "#00ffff", "#ffffff",
}
// wasmRenderer performs a full-replace render of an Element tree into
// a root DOM node. v1 does no VDOM diffing: each render clears and
// rebuilds the subtree, preserving focus and in-progress input values
// across the replace.
//
// Elements carry their own callbacks (ButtonEl.OnClick, etc.); the
// renderer wires each DOM event directly to the matching callback and
// forwards the resulting Msg to dispatch.
type wasmRenderer struct {
root js.Value
dispatch func(Msg)
funcs []js.Func
// prevValues snapshots live <input> values at the start of each
// render; lastSpec records the spec Value each input was last
// rendered with. Together they let renderTextInput distinguish
// programmatic value changes (respect the new spec) from
// in-progress typing (preserve the live value) — mirroring the
// TUI renderer's ensureInput.
prevValues map[string]string
lastSpec map[string]string
// bpSeq numbers Responsive elements within a render so each gets
// unique breakpoint class names. Reset at the start of Render so
// the names stay stable frame to frame.
bpSeq int
}
func newWASMRenderer(root js.Value, dispatch func(Msg)) *wasmRenderer {
return &wasmRenderer{
root: root,
dispatch: dispatch,
lastSpec: make(map[string]string),
}
}
func (r *wasmRenderer) Render(el Element) {
doc := js.Global().Get("document")
activeID := ""
if active := doc.Get("activeElement"); !active.IsNull() && !active.IsUndefined() {
activeID = active.Get("id").String()
}
r.prevValues = r.collectInputValues(doc)
for _, f := range r.funcs {
f.Release()
}
r.funcs = r.funcs[:0]
r.bpSeq = 0
r.root.Set("innerHTML", "")
node := r.renderEl(el, doc)
r.root.Call("appendChild", node)
if activeID != "" {
if el := doc.Call("getElementById", activeID); !el.IsNull() {
el.Call("focus")
}
}
}
func (r *wasmRenderer) collectInputValues(doc js.Value) map[string]string {
values := make(map[string]string)
nodeList := r.root.Call("querySelectorAll", `input:not([type="checkbox"]), textarea`)
length := nodeList.Get("length").Int()
for i := 0; i < length; i++ {
n := nodeList.Call("item", i)
id := n.Get("id").String()
if id != "" {
values[id] = n.Get("value").String()
}
}
return values
}
func (r *wasmRenderer) addFunc(f js.Func) js.Func {
r.funcs = append(r.funcs, f)
return f
}
func (r *wasmRenderer) renderEl(el Element, doc js.Value) js.Value {
switch e := el.(type) {
case TextEl:
return r.renderText(e, doc)
case BoxEl:
return r.renderBox(e, doc)
case ButtonEl:
return r.renderButton(e, doc)
case TextInputEl:
return r.renderTextInput(e, doc)
case CheckboxEl:
return r.renderCheckbox(e, doc)
case CardEl:
return r.renderCard(e, doc)
case FormEl:
return r.renderForm(e, doc)
case ListEl:
return r.renderList(e, doc)
case ScrollAreaEl:
return r.renderScroll(e, doc)
case LinkEl:
return r.renderLink(e, doc)
case TableEl:
return r.renderTable(e, doc)
case EmptyEl:
// A zero-size, non-rendering placeholder keeps appendChild
// callers uniform without affecting layout.
return doc.Call("createDocumentFragment")
case ResponsiveEl:
return r.renderResponsive(e, doc)
case SpacerEl:
return r.renderSpacer(e, doc)
case DividerEl:
return r.renderDivider(e, doc)
case ProgressEl:
return r.renderProgress(e, doc)
case SpinnerEl:
return r.renderSpinner(e, doc)
case SelectEl:
return r.renderSelect(e, doc)
case TextAreaEl:
return r.renderTextArea(e, doc)
default:
return doc.Call("createElement", "span")
}
}
// renderSpacer emits fixed blank space, or a flex:1 stretch when Size is
// zero — the CSS analogue of the TUI's leftover-width distribution.
func (r *wasmRenderer) renderSpacer(e SpacerEl, doc js.Value) js.Value {
n := doc.Call("createElement", "span")
if e.Size <= 0 {
n.Set("style", "flex:1 1 auto;")
return n
}
// Size is cells: ch horizontally and lh vertically, matching how
// every other dimension crosses over. flex-basis covers whichever
// axis the parent Box runs along.
n.Set("style", fmt.Sprintf(
"flex:0 0 auto;width:%dch;height:%dem;height:%dlh;", e.Size, e.Size, e.Size))
return n
}
func (r *wasmRenderer) renderDivider(e DividerEl, doc js.Value) js.Value {
if e.Label == "" {
n := doc.Call("createElement", "hr")
n.Set("className", "wui-divider")
applyStyle(n, e.Style)
return n
}
n := doc.Call("createElement", "div")
n.Set("className", "wui-divider-labeled")
applyStyle(n, e.Style)
label := doc.Call("createElement", "span")
label.Set("textContent", e.Label)
n.Call("appendChild", label)
return n
}
// renderProgress uses <progress>, the semantic element, styled by the
// base CSS to read like the TUI's block bar.
func (r *wasmRenderer) renderProgress(e ProgressEl, doc js.Value) js.Value {
wrap := doc.Call("createElement", "span")
wrap.Set("className", "wui-progress")
bar := doc.Call("createElement", "progress")
v := clampUnit(e.Value)
bar.Set("max", 1)
bar.Set("value", v)
width := e.Width
if width <= 0 {
width = 20
}
bar.Set("style", fmt.Sprintf("width:%dch;", width))
applyStyle(bar, e.Style)
wrap.Call("appendChild", bar)
if e.ShowLabel {
label := doc.Call("createElement", "span")
label.Set("textContent", fmt.Sprintf(" %d%%", int(v*100+0.5)))
wrap.Call("appendChild", label)
}
return wrap
}
// renderSpinner draws the same glyph cycle as the TUI, so an app's frame
// counter animates identically on both platforms.
func (r *wasmRenderer) renderSpinner(e SpinnerEl, doc js.Value) js.Value {
n := doc.Call("createElement", "span")
text := spinnerGlyph(e.Frame)
if e.Label != "" {
text += " " + e.Label
}
n.Set("textContent", text)
applyStyle(n, e.Style)
return n
}
func (r *wasmRenderer) renderSelect(e SelectEl, doc js.Value) js.Value {
n := doc.Call("createElement", "select")
n.Set("id", e.ID)
if e.Disabled {
n.Set("disabled", true)
}
applyStyle(n, e.Style)
for _, o := range e.Options {
opt := doc.Call("createElement", "option")
opt.Set("value", o.Value)
label := o.Label
if label == "" {
label = o.Value
}
opt.Set("textContent", label)
if o.Value == e.Value {
opt.Set("selected", true)
}
n.Call("appendChild", opt)
}
spec := e
changeFn := js.FuncOf(func(this js.Value, args []js.Value) any {
val := args[0].Get("target").Get("value").String()
r.dispatch(selectChangeMsg(spec, val))
return nil
})
r.addFunc(changeFn)
n.Call("addEventListener", "change", changeFn)
return n
}
func (r *wasmRenderer) renderTextArea(e TextAreaEl, doc js.Value) js.Value {
n := doc.Call("createElement", "textarea")
n.Set("id", e.ID)
rows := e.Rows
if rows <= 0 {
rows = 4
}
n.Set("rows", rows)
n.Set("placeholder", e.Placeholder)
if e.Disabled {
n.Set("disabled", true)
}
// Same rule as single-line inputs: keep in-progress typing across
// the full-tree replace unless the app changed the spec value.
val := e.Value
if prev, ok := r.prevValues[e.ID]; ok && r.lastSpec[e.ID] == e.Value {
val = prev
}
r.lastSpec[e.ID] = e.Value
n.Set("value", val)
applyStyle(n, e.Style)
if e.OnChange != nil {
onChange := e.OnChange
inputFn := js.FuncOf(func(this js.Value, args []js.Value) any {
r.dispatch(onChange(args[0].Get("target").Get("value").String()))
return nil
})
r.addFunc(inputFn)
n.Call("addEventListener", "input", inputFn)
}
return n
}
func (r *wasmRenderer) renderText(e TextEl, doc js.Value) js.Value {
n := doc.Call("createElement", "span")
n.Set("textContent", e.Content)
applyStyle(n, e.Style)
return n
}
func (r *wasmRenderer) renderBox(e BoxEl, doc js.Value) js.Value {
n := doc.Call("createElement", "div")
dir := "row"
if e.Direction == Column {
dir = "column"
}
css := "display:flex;flex-direction:" + dir + ";"
if e.Wrap {
css += "flex-wrap:wrap;"
}
if e.Gap > 0 {
// Gap is terminal cells in the TUI; ch/lh (with an em
// fallback) are the closest CSS analogues.
css += fmt.Sprintf("column-gap:%dch;row-gap:%dem;row-gap:%dlh;", e.Gap, e.Gap, e.Gap)
}
if a := alignItemsCSS(e.Align); a != "" {
css += "align-items:" + a + ";"
}
if j := justifyContentCSS(e.Justify); j != "" {
css += "justify-content:" + j + ";"
}
n.Set("style", css+styleToCSS(e.Style))
for _, c := range e.Children {
n.Call("appendChild", r.renderEl(c, doc))
}
return n
}
func (r *wasmRenderer) renderButton(e ButtonEl, doc js.Value) js.Value {
n := doc.Call("createElement", "button")
n.Set("textContent", e.Label)
// The focus key doubles as the DOM id so keyboard focus survives
// the full-tree replace, mirroring the TUI focus ring.
n.Set("id", buttonFocusKey(e))
if e.Disabled {
n.Set("disabled", true)
}
applyStyle(n, e.Style)
if e.OnClick != nil {
onClick := e.OnClick
f := js.FuncOf(func(this js.Value, args []js.Value) any {
r.dispatch(onClick())
return nil
})
r.addFunc(f)
n.Call("addEventListener", "click", f)
}
return n
}
func (r *wasmRenderer) renderTextInput(e TextInputEl, doc js.Value) js.Value {
n := doc.Call("createElement", "input")
n.Set("id", e.ID)
if e.Password {
n.Set("type", "password")
} else {
n.Set("type", "text")
}
// Keep in-progress typing across the full-tree replace unless the
// app changed the spec value programmatically since last render.
val := e.Value
if prev, ok := r.prevValues[e.ID]; ok && r.lastSpec[e.ID] == e.Value {
val = prev
}
r.lastSpec[e.ID] = e.Value
n.Set("value", val)
n.Set("placeholder", e.Placeholder)
if e.Disabled {
n.Set("disabled", true)
}
applyStyle(n, e.Style)
if e.OnChange != nil {
onChange := e.OnChange
inputFn := js.FuncOf(func(this js.Value, args []js.Value) any {
val := args[0].Get("target").Get("value").String()
r.dispatch(onChange(val))
return nil
})
r.addFunc(inputFn)
n.Call("addEventListener", "input", inputFn)
}
if e.OnSubmit != nil {
onSubmit := e.OnSubmit
keydownFn := js.FuncOf(func(this js.Value, args []js.Value) any {
if args[0].Get("key").String() == "Enter" {
// Stop the enclosing form (if any) from also
// submitting — the input's own handler wins,
// matching TUI dispatch order.
args[0].Call("preventDefault")
val := args[0].Get("target").Get("value").String()
r.dispatch(onSubmit(val))
}
return nil
})
r.addFunc(keydownFn)
n.Call("addEventListener", "keydown", keydownFn)
}
return n
}
// renderCheckbox renders <label><input type="checkbox"><span/></label>.
// The native checkbox is visually hidden (browsers cannot restyle it as
// text) and a sibling span draws the TUI-style "[ ]"/"[x]" mark via the
// base CSS; the input still provides focus, keyboard toggling, and the
// change event.
func (r *wasmRenderer) renderCheckbox(e CheckboxEl, doc js.Value) js.Value {
label := doc.Call("createElement", "label")
label.Set("className", "wui-checkbox")
applyStyle(label, e.Style)
input := doc.Call("createElement", "input")
input.Set("type", "checkbox")
input.Set("id", e.ID)
input.Set("checked", e.Checked)
if e.Disabled {
input.Set("disabled", true)
}
spec := e
changeFn := js.FuncOf(func(this js.Value, args []js.Value) any {
checked := args[0].Get("target").Get("checked").Bool()
r.dispatch(checkboxToggleMsg(spec, checked))
return nil
})
r.addFunc(changeFn)
input.Call("addEventListener", "change", changeFn)
label.Call("appendChild", input)
mark := doc.Call("createElement", "span")
mark.Set("className", "wui-checkbox-mark")
label.Call("appendChild", mark)
if e.Label != "" {
text := doc.Call("createElement", "span")
text.Set("textContent", " "+e.Label)
label.Call("appendChild", text)
}
return label
}
// renderCard renders <fieldset><legend>Title</legend>…</fieldset> — the
// semantic HTML for a titled, bordered panel; the base CSS styles it to
// match the TUI's title-in-border card.
func (r *wasmRenderer) renderCard(e CardEl, doc js.Value) js.Value {
n := doc.Call("createElement", "fieldset")
applyStyle(n, e.Style)
if e.Title != "" {
legend := doc.Call("createElement", "legend")
legend.Set("textContent", e.Title)
n.Call("appendChild", legend)
}
n.Call("appendChild", r.renderEl(e.Child, doc))
return n
}
func (r *wasmRenderer) renderForm(e FormEl, doc js.Value) js.Value {
n := doc.Call("createElement", "form")
applyStyle(n, e.Style)
for _, c := range e.Children {
n.Call("appendChild", r.renderEl(c, doc))
}
if e.OnSubmit != nil {
formNode := n
onSubmit := e.OnSubmit
submitFn := js.FuncOf(func(this js.Value, args []js.Value) any {
args[0].Call("preventDefault")
values := collectFormValues(formNode)
r.dispatch(onSubmit(values))
return nil
})
r.addFunc(submitFn)
n.Call("addEventListener", "submit", submitFn)
}
return n
}
// collectFormValues gathers text-input values by id. Checkboxes are
// excluded — the TUI's formValues only walks text inputs, and checkbox
// state flows through OnToggle/ToggleMsg instead.
func collectFormValues(formNode js.Value) map[string]string {
values := make(map[string]string)
nodeList := formNode.Call("querySelectorAll", `input:not([type="checkbox"]), textarea, select`)
length := nodeList.Get("length").Int()
for i := 0; i < length; i++ {
input := nodeList.Call("item", i)
id := input.Get("id").String()
if id != "" {
values[id] = input.Get("value").String()
}
}
return values
}
func (r *wasmRenderer) renderList(e ListEl, doc js.Value) js.Value {
tag := "ul"
if e.Ordered {
tag = "ol"
}
n := doc.Call("createElement", tag)
applyStyle(n, e.Style)
for _, item := range e.Items {
li := doc.Call("createElement", "li")
li.Call("appendChild", r.renderEl(item, doc))
n.Call("appendChild", li)
}
return n
}
func (r *wasmRenderer) renderScroll(e ScrollAreaEl, doc js.Value) js.Value {
n := doc.Call("createElement", "div")
css := "overflow:auto;"
if e.MaxHeight > 0 {
// MaxHeight is terminal rows, like every other vertical unit:
// lh is the CSS analogue, with an em fallback.
css += fmt.Sprintf("max-height:%dem;max-height:%dlh;", e.MaxHeight, e.MaxHeight)
}
n.Set("style", css+styleToCSS(e.Style))
n.Call("appendChild", r.renderEl(e.Child, doc))
return n
}
func (r *wasmRenderer) renderLink(e LinkEl, doc js.Value) js.Value {
n := doc.Call("createElement", "a")
n.Set("textContent", e.Label)
n.Set("href", e.Href)
// Same id scheme as the TUI focus ring; keeps focus across renders.
n.Set("id", "link:"+e.Href)
applyStyle(n, e.Style)
return n
}
func (r *wasmRenderer) renderTable(e TableEl, doc js.Value) js.Value {
table := doc.Call("createElement", "table")
applyStyle(table, e.Style)
thead := doc.Call("createElement", "thead")
headRow := doc.Call("createElement", "tr")
for _, col := range e.Columns {
th := doc.Call("createElement", "th")
th.Set("textContent", col)
headRow.Call("appendChild", th)
}
thead.Call("appendChild", headRow)
table.Call("appendChild", thead)
tbody := doc.Call("createElement", "tbody")
for _, row := range e.Rows {
tr := doc.Call("createElement", "tr")
for _, cell := range row {
td := doc.Call("createElement", "td")
td.Set("textContent", cell)
tr.Call("appendChild", td)
}
tbody.Call("appendChild", tr)
}
table.Call("appendChild", tbody)
return table
}
func applyStyle(n js.Value, s Style) {
css := styleToCSS(s)
if css != "" {
existing := n.Get("style").Get("cssText").String()
n.Set("style", existing+css)
}
}
func styleToCSS(s Style) string {
var parts []string
if s.FG != "" {
parts = append(parts, "color:"+resolveCSSColor(s.FG))
}
if s.BG != "" {
parts = append(parts, "background-color:"+resolveCSSColor(s.BG))
}
if s.Bold {
parts = append(parts, "font-weight:bold")
}
if s.Italic {
parts = append(parts, "font-style:italic")
}
if s.Underline {
parts = append(parts, "text-decoration:underline")
}
// Sizing units mirror terminal cells: ch horizontally, lh (line
// height) vertically with an em fallback for older browsers.
if s.Width > 0 {
parts = append(parts, fmt.Sprintf("width:%dch", s.Width))
} else if s.Width == Fill {
parts = append(parts, "width:100%;box-sizing:border-box;align-self:stretch")
}
if s.Height > 0 {
parts = append(parts, fmt.Sprintf("height:%dem;height:%dlh", s.Height, s.Height))
} else if s.Height == Fill {
// #wui-root is a flex column, so growing is how a top-level
// element takes the whole viewport; min-height:0 lets nested
// scroll areas shrink inside it.
parts = append(parts, "flex:1 1 auto;min-height:0")
}
if s.Grow > 0 {
parts = append(parts, fmt.Sprintf("flex-grow:%d;min-width:0", s.Grow))
}
if s.MinWidth > 0 {
parts = append(parts, fmt.Sprintf("min-width:%dch", s.MinWidth))
}
if s.MaxWidth > 0 {
parts = append(parts, fmt.Sprintf("max-width:%dch;box-sizing:border-box", s.MaxWidth))
}
if s.MaxHeight > 0 {
parts = append(parts, fmt.Sprintf("max-height:%dem;max-height:%dlh", s.MaxHeight, s.MaxHeight))
}
if s.Padding != [4]int{} {
parts = append(parts, fmt.Sprintf("padding:%dem %dch %dem %dch",
s.Padding[0], s.Padding[1], s.Padding[2], s.Padding[3]))
parts = append(parts, fmt.Sprintf("padding:%dlh %dch %dlh %dch",
s.Padding[0], s.Padding[1], s.Padding[2], s.Padding[3]))
}
if s.Margin != [4]int{} {
parts = append(parts, fmt.Sprintf("margin:%dem %dch %dem %dch",
s.Margin[0], s.Margin[1], s.Margin[2], s.Margin[3]))
parts = append(parts, fmt.Sprintf("margin:%dlh %dch %dlh %dch",
s.Margin[0], s.Margin[1], s.Margin[2], s.Margin[3]))
}
// Auto margins place a capped block in the space it did not use.
// They come after the margin shorthand so an explicit Margin sets
// the vertical gaps without overriding the horizontal placement.
if s.MaxWidth > 0 {
switch s.PlaceX {
case AlignCenter:
parts = append(parts, "margin-left:auto;margin-right:auto")
case AlignEnd:
parts = append(parts, "margin-left:auto;margin-right:0")
}
}
if s.Border {
col := "currentColor"
if s.BorderColor != "" {
col = resolveCSSColor(s.BorderColor)
}
parts = append(parts, "border:1px solid "+col)
}
if len(parts) == 0 {
return ""
}
return strings.Join(parts, ";") + ";"
}
func resolveCSSColor(c Color) string {
if idx, err := strconv.Atoi(string(c)); err == nil && idx >= 0 && idx < 16 {
return ansiPalette[idx]
}
return string(c)
}
// alignItemsCSS maps Align to a CSS align-items value. AlignStart must
// be emitted explicitly: the CSS default is stretch, but the TUI joins
// children at their natural size, so flex-start is the parity default.
func alignItemsCSS(a Align) string {
switch a {
case AlignCenter:
return "center"
case AlignEnd:
return "flex-end"
case AlignStretch:
return "stretch"
default:
return "flex-start"
}
}
// justifyContentCSS maps a Box's Justify to justify-content. The
// zero value emits nothing — flex-start is already the CSS default.
func justifyContentCSS(a Align) string {
switch a {
case AlignCenter:
return "center"
case AlignEnd:
return "flex-end"
default:
return ""
}
}
// baseCSS is the default stylesheet injected by WASM builds (disable
// with WithoutBaseCSS). It styles the semantic HTML output to visually
// match the TUI renderer: monospace type on a dark background, buttons
// drawn as "[ Label ]" that reverse-video on focus, unordered lists
// with "- " markers, and bordered tables.
const baseCSS = `
:root { color-scheme: dark; }
html, body { height: 100%; }
body {
margin: 0;
background: #14151a;
color: #e6e6e6;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
font-size: 14px;
line-height: 1.4;
}
/* pre-wrap: runs of spaces are significant in a terminal (column
alignment via %-Ns etc.) and must survive in HTML too.
The root is a full-viewport flex column so a top-level element with
Height: Fill (Fullscreen, AppShell, Centered) can grow to take the
whole screen; align-items keeps children at their natural width,
matching the TUI. */
#wui-root {
padding: 1em 1ch;
white-space: pre-wrap;
box-sizing: border-box;
min-height: 100vh;
min-height: 100dvh;
display: flex;
flex-direction: column;
align-items: flex-start;
}
#wui-root button {
font: inherit;
color: inherit;
background: none;
border: none;
padding: 0;
cursor: pointer;
width: fit-content;
}
#wui-root button::before { content: "[ "; }
#wui-root button::after { content: " ]"; }
#wui-root button:hover:not(:disabled),
#wui-root button:focus-visible {
background: #e6e6e6;
color: #14151a;
outline: none;
}
#wui-root button:disabled { opacity: 0.45; cursor: default; }
#wui-root input:not([type="checkbox"]) {
font: inherit;
color: inherit;
background: #1f2128;
border: 1px solid #3a3d46;
border-radius: 3px;
padding: 0 1ch;
}
#wui-root input:focus { outline: none; border-color: #7aa2f7; }
#wui-root label.wui-checkbox { cursor: pointer; width: fit-content; }
#wui-root label.wui-checkbox input {
position: absolute;
opacity: 0;
width: 1px;
height: 1px;
margin: 0;
}
#wui-root .wui-checkbox-mark::before { content: "[ ]"; }
#wui-root input:checked + .wui-checkbox-mark::before { content: "[x]"; }
#wui-root input:focus-visible + .wui-checkbox-mark {
background: #e6e6e6;
color: #14151a;
}
#wui-root input:disabled + .wui-checkbox-mark { opacity: 0.45; }
#wui-root input:disabled ~ span { opacity: 0.45; }
#wui-root fieldset {
border: 1px solid #3a3d46;
border-radius: 6px;
margin: 0;
padding: 0.25lh 1ch;
min-width: 0;
width: fit-content;
}
#wui-root legend { font-weight: bold; padding: 0 1ch; }
#wui-root a { color: inherit; }
#wui-root a:focus-visible {
background: #e6e6e6;
color: #14151a;
outline: none;
}
#wui-root ul { list-style: none; margin: 0; padding: 0; }
#wui-root ul > li::before { content: "- "; }
#wui-root ol { margin: 0; padding: 0; list-style-position: inside; }
#wui-root table { border-collapse: collapse; }
#wui-root th, #wui-root td {
border: 1px solid #3a3d46;
padding: 0 1ch;
text-align: left;
}
/* No border by default, matching the TUI: a TextArea inside a Card
must not draw a second frame inside the card's. Opt in with
Style.Border. */
#wui-root textarea {
font: inherit;
color: inherit;
background: #1f2128;
border: none;
border-radius: 3px;
padding: 0 1ch;
resize: vertical;
width: 100%;
box-sizing: border-box;
}
#wui-root textarea:focus { outline: 1px solid #7aa2f7; }
#wui-root select {
font: inherit;
color: inherit;
background: #1f2128;
border: 1px solid #3a3d46;
border-radius: 3px;
padding: 0 1ch;
}
#wui-root select:focus { outline: none; border-color: #7aa2f7; }
#wui-root hr.wui-divider {
border: none;
border-top: 1px solid #3a3d46;
margin: 0.5lh 0;
width: 100%;
}
/* A labelled divider is the label with a rule running off each side,
matching the TUI's "── Label ──────". */
#wui-root .wui-divider-labeled {
display: flex;
align-items: center;
gap: 1ch;
width: 100%;
}
#wui-root .wui-divider-labeled::before,
#wui-root .wui-divider-labeled::after {
content: "";
border-top: 1px solid #3a3d46;
flex: 1 1 auto;
}
#wui-root .wui-divider-labeled::before { flex-grow: 0; width: 2ch; }
#wui-root .wui-progress { display: inline-flex; align-items: center; }
#wui-root progress {
-webkit-appearance: none;
appearance: none;
height: 1lh;
vertical-align: middle;
}
#wui-root progress::-webkit-progress-bar { background: #1f2128; }
#wui-root progress::-webkit-progress-value { background: #7aa2f7; }
#wui-root progress::-moz-progress-bar { background: #7aa2f7; }
/* Status bar: a fixed strip across the bottom of the viewport,
mirroring the TUI's reverse-video bottom row. */
body.wui-has-status #wui-root { padding-bottom: 3lh; }
#wui-status {
position: fixed;
left: 0;
right: 0;
bottom: 0;
display: flex;
justify-content: space-between;
gap: 2ch;
padding: 0 1ch;
background: #e6e6e6;
color: #14151a;
font-family: inherit;
font-size: inherit;
line-height: 1.6;
white-space: pre;
overflow: hidden;
}
#wui-status .wui-status-side { display: flex; gap: 0; min-width: 0; }
#wui-status .wui-status-sep { opacity: 0.5; }
#wui-status .wui-status-right { justify-content: flex-end; }
`
// renderStatus draws (or removes) the fixed bottom status strip. It
// lives outside #wui-root so the full-tree replace never touches it.
func renderStatus(doc js.Value, s Status) {
body := doc.Get("body")
existing := doc.Call("getElementById", "wui-status")
if s.Hidden || s.Empty() {
if !existing.IsNull() {
existing.Call("remove")
}
body.Get("classList").Call("remove", "wui-has-status")
return
}
bar := existing
if bar.IsNull() {
bar = doc.Call("createElement", "div")
bar.Set("id", "wui-status")
body.Call("appendChild", bar)
}
bar.Set("innerHTML", "")
if css := styleToCSS(s.Style); css != "" {
bar.Set("style", css)
}
body.Get("classList").Call("add", "wui-has-status")
left, right := s.sides()
bar.Call("appendChild", statusSide(doc, left, s.separator(), false))
bar.Call("appendChild", statusSide(doc, right, s.separator(), true))
}
// statusSide builds one aligned group of status segments, separators
// included.
func statusSide(doc js.Value, items []StatusItem, sep string, right bool) js.Value {
n := doc.Call("createElement", "div")
class := "wui-status-side"
if right {
class += " wui-status-right"
}
n.Set("className", class)
first := true
for _, it := range items {
if it.Text == "" {
continue
}
if !first {
s := doc.Call("createElement", "span")
s.Set("className", "wui-status-sep")
s.Set("textContent", sep)
n.Call("appendChild", s)
}
first = false
seg := doc.Call("createElement", "span")
seg.Set("textContent", it.Text)
applyStyle(seg, it.Style)
n.Call("appendChild", seg)
}
return n
}
// renderResponsive emits every variant and lets CSS container queries
// decide which one is visible. Doing the switching in CSS rather than
// in Go means resizing the window reflows immediately, without a round
// trip through the model — the browser counterpart of the TUI reading
// its available width at render time.
//
// The wrapper establishes an inline-size container, so the queries
// measure the space the element actually occupies, matching the TUI's
// container-relative behaviour rather than the viewport.
func (r *wasmRenderer) renderResponsive(e ResponsiveEl, doc js.Value) js.Value {
n := doc.Call("createElement", "div")
n.Set("style", "container-type:inline-size;display:contents;")
if len(e.Variants) == 0 {
return n
}
// Variants are sorted ascending; each is visible from its own
// MinWidth up to the next one, and the last stays visible above.
// Widths are in ch so they mean the same thing as TUI cells.
var css strings.Builder
cls := make([]string, len(e.Variants))
for i, v := range e.Variants {
cls[i] = fmt.Sprintf("wui-bp-%d-%d", r.bpSeq, i)
upper := 0
if i+1 < len(e.Variants) {
upper = e.Variants[i+1].MinWidth
}
// Hidden by default, revealed only inside its own band, so
// exactly one variant shows at any width.
fmt.Fprintf(&css, ".%s{display:none;}", cls[i])
switch {
case v.MinWidth <= 0 && upper > 0:
fmt.Fprintf(&css, "@container (max-width:%dch){.%s{display:revert;}}", upper-1, cls[i])
case upper > 0:
fmt.Fprintf(&css, "@container (min-width:%dch) and (max-width:%dch){.%s{display:revert;}}",
v.MinWidth, upper-1, cls[i])
case v.MinWidth <= 0:
fmt.Fprintf(&css, ".%s{display:revert;}", cls[i])
default:
fmt.Fprintf(&css, "@container (min-width:%dch){.%s{display:revert;}}", v.MinWidth, cls[i])
}
}
r.bpSeq++
style := doc.Call("createElement", "style")
style.Set("textContent", css.String())
n.Call("appendChild", style)
for i, v := range e.Variants {
wrap := doc.Call("createElement", "div")
wrap.Set("className", cls[i])
wrap.Call("appendChild", r.renderEl(v.Content, doc))
n.Call("appendChild", wrap)
}
return n
}
// injectBaseCSS appends the default stylesheet to <head>, once.
func injectBaseCSS(doc js.Value) {
if existing := doc.Call("getElementById", "wui-base-css"); !existing.IsNull() {
return
}
style := doc.Call("createElement", "style")
style.Set("id", "wui-base-css")
style.Set("textContent", baseCSS)
doc.Get("head").Call("appendChild", style)
}