Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -897,6 +897,28 @@ All bubbletea/lipgloss/bubbles code is behind `//go:build !js`. All `syscall/js`

---

## Testing views

A View is a pure function of the model, so both renderings can be tested in plain `go test`, with no terminal or browser:

```go
func TestEmptyState(t *testing.T) {
view := model{}.View()

tui := wui.RenderTUISized(view, 60, 10) // what the terminal shows
if !strings.Contains(tui, "Nothing to do") { t.Fatal(tui) }

html := wui.RenderHTML(view) // what the browser build puts in #wui-root
if !strings.Contains(html, `<input id="new-todo"`) { t.Fatal(html) }
}
```

`RenderHTML` produces the same semantic HTML the WASM renderer builds: tags, classes and inline styles, with current values reflected as attributes, and no event wiring. Attributes are sorted, so the output is stable enough for golden files. `RenderHTMLPage(title, el)` wraps it in a standalone document with the base stylesheet, for static exports such as an HTML report from a terminal tool.

The browser behaviour itself (events, focus, patching) is covered by the browser tests in `e2e/` (`make e2e`).

---

## Architecture

```
Expand Down Expand Up @@ -976,6 +998,14 @@ Exercises the framework features rather than a domain: declarative key bindings

A stopwatch: Cmd-driven self-rescheduling ticks, start/stop/reset, bordered display.

### Layout (`example/layout/`)

The layout helpers side by side, switchable at runtime: an `AppShell` frame with a collapsing `Sidebar`, a `Split` pair of panes, and a `Centered` login screen. Resize the terminal or browser window to watch the sidebar collapse.

### Gallery (`example/gallery/`)

Every built-in element with live state and the default styles, for comparing the terminal and browser renderings, or for checking a theme.

---

## Dependencies
Expand Down
123 changes: 123 additions & 0 deletions render_html.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package wui

import (
"html"
"sort"
"strings"
)

// RenderHTML renders an element tree to the HTML the browser build
// puts inside #wui-root, without a browser: the same semantic tags,
// classes and inline styles, with current values reflected as
// attributes and no event wiring. It works in every build.
//
// Use it for snapshot tests of the browser rendering (the counterpart
// of RenderTUI), or for static exports such as an HTML report from a
// terminal tool. Empty elements appear as <!----> placeholders, as they
// do in the live DOM. Attributes are written in sorted order, so the
// output is deterministic.
func RenderHTML(el Element) string {
var b strings.Builder
writeHTML(&b, describeTree(el))
return b.String()
}

// RenderHTMLPage renders a complete, standalone HTML document: the base
// stylesheet (dark theme) and el inside #wui-root. The page is static;
// it does not load the WASM build.
func RenderHTMLPage(title string, el Element) string {
var b strings.Builder
b.WriteString("<!DOCTYPE html>\n<html data-wui-theme=\"dark\">\n<head>\n<meta charset=\"utf-8\">\n")
b.WriteString("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>")
b.WriteString(html.EscapeString(title))
b.WriteString("</title>\n<style id=\"wui-base-css\">")
b.WriteString(baseCSS)
b.WriteString("</style>\n</head>\n<body>\n<div id=\"wui-root\">")
writeHTML(&b, describeTree(el))
b.WriteString("</div>\n</body>\n</html>\n")
return b.String()
}

// voidElements have no closing tag.
var voidElements = map[string]bool{"input": true, "hr": true, "br": true, "img": true}

// rawTextElements hold text that must not be entity-escaped.
var rawTextElements = map[string]bool{"style": true, "script": true}

func writeHTML(b *strings.Builder, v *vnode) {
if v.tag == commentTag {
b.WriteString("<!---->")
return
}

attrs := make(map[string]string, len(v.attrs)+1)
for k, val := range v.attrs {
attrs[k] = val
}
text, selected := v.text, ""
for _, p := range v.props {
switch {
case p.name == "value" && v.tag == "textarea":
text, _ = p.value.(string)
case p.name == "value" && v.tag == "select":
selected, _ = p.value.(string)
case p.name == "value":
if s, _ := p.value.(string); s != "" {
attrs["value"] = s
}
case p.name == "checked":
if on, _ := p.value.(bool); on {
attrs["checked"] = ""
}
}
}

b.WriteByte('<')
b.WriteString(v.tag)
names := make([]string, 0, len(attrs))
for k := range attrs {
names = append(names, k)
}
sort.Strings(names)
for _, k := range names {
b.WriteByte(' ')
b.WriteString(k)
if val := attrs[k]; val != "" {
b.WriteString(`="`)
b.WriteString(html.EscapeString(val))
b.WriteByte('"')
}
}
b.WriteByte('>')
if voidElements[v.tag] {
return
}

switch {
case len(v.kids) > 0:
for _, k := range v.kids {
if v.tag == "select" && k.tag == "option" && k.attrs["value"] == selected {
k = withAttr(k, "selected", "")
}
writeHTML(b, k)
}
case rawTextElements[v.tag]:
b.WriteString(strings.ReplaceAll(text, "</", `<\/`))
default:
b.WriteString(html.EscapeString(text))
}
b.WriteString("</")
b.WriteString(v.tag)
b.WriteByte('>')
}

// withAttr returns a shallow copy of v with one more attribute.
func withAttr(v *vnode, name, value string) *vnode {
c := *v
c.attrs = make(map[string]string, len(v.attrs)+1)
for k, val := range v.attrs {
c.attrs[k] = val
}
c.attrs[name] = value
return &c
}
76 changes: 76 additions & 0 deletions render_html_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package wui

import (
"strings"
"testing"
)

func TestRenderHTMLElements(t *testing.T) {
nop := func() Msg { return nil }
tests := []struct {
name string
el Element
want string
}{
{"text escaped", Text(`a < b & "c"`), `<span>a &lt; b &amp; &#34;c&#34;</span>`},
{"styled text", Text("hi", WithTextStyle(NewStyle().SetBold(true).Classed("x"))),
`<span class="x" style="font-weight:bold;">hi</span>`},
{"button", Button("Go", nop), `<button id="btn:Go" type="button">Go</button>`},
{"submit button", Button("Send", nil, Disabled()), `<button disabled id="btn:Send" type="submit">Send</button>`},
{"input value", Input("q", WithValue(`say "hi"`), WithPlaceholder("Search")),
`<input id="q" placeholder="Search" type="text" value="say &#34;hi&#34;">`},
{"empty input value omitted", Input("q"), `<input id="q" type="text">`},
{"textarea value as text", TextArea("t", WithAreaValue("a<b"), WithAreaRows(2)),
`<textarea id="t" rows="2">a&lt;b</textarea>`},
{"checkbox checked", Checkbox("c", "Done", true, nil),
`<label class="wui-checkbox"><input checked id="c" type="checkbox"><span class="wui-checkbox-mark"></span><span> Done</span></label>`},
{"select marks the selected option", Select("s", Options("a", "b"), "b", nil),
`<select id="s"><option value="a">a</option><option selected value="b">b</option></select>`},
{"empty placeholder", Box(Column, Empty()),
`<div style="display:flex;flex-direction:column;align-items:flex-start;"><!----></div>`},
{"divider", Divider(""), `<hr class="wui-divider">`},
{"link", Link("Docs", "https://x.test/?a=1&b=2"),
`<a href="https://x.test/?a=1&amp;b=2" id="link:https://x.test/?a=1&amp;b=2">Docs</a>`},
{"table", Table([]string{"A"}, [][]string{{"1"}}),
`<table><thead><tr><th>A</th></tr></thead><tbody><tr><td>1</td></tr></tbody></table>`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := RenderHTML(tt.el); got != tt.want {
t.Errorf("RenderHTML =\n%s\nwant\n%s", got, tt.want)
}
})
}
}

func TestRenderHTMLResponsiveStyleIsRaw(t *testing.T) {
got := RenderHTML(Responsive(At(0, Text("a")), At(40, Text("b"))))
if !strings.Contains(got, "<style>.wui-bp-0-0{display:none;}@container (not (width >= 40ch))") {
t.Errorf("container-query CSS must not be entity-escaped:\n%s", got)
}
}

func TestRenderHTMLDeterministic(t *testing.T) {
el := Text("x", WithTextStyle(NewStyle().Fg("1").Bg("2").W(10).Classed("a", "b")))
first := RenderHTML(el)
for i := 0; i < 20; i++ {
if got := RenderHTML(el); got != first {
t.Fatalf("output changed between calls:\n%s\n%s", first, got)
}
}
}

func TestRenderHTMLPage(t *testing.T) {
got := RenderHTMLPage("Report <1>", Text("body"))
for _, want := range []string{
"<!DOCTYPE html>",
`<html data-wui-theme="dark">`,
"<title>Report &lt;1&gt;</title>",
`<style id="wui-base-css">`,
`<div id="wui-root"><span>body</span></div>`,
} {
if !strings.Contains(got, want) {
t.Errorf("page missing %q", want)
}
}
}
Loading