update heatmap, add wasm charts

This commit is contained in:
2026-07-16 14:55:16 -04:00
parent 2477c2d6a2
commit 093bad311e
13 changed files with 1949 additions and 352 deletions

View File

@@ -1,119 +1,39 @@
package app
import (
"bytes"
"io"
"math/rand"
chart "github.com/wcharczuk/go-chart/v2"
. "kjol/vdom"
"kjol/wasmruntime"
ui "kjol/webui"
)
var chartLabels = []string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}
var chartPageDays = []string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}
// fixed initial data so the server SSR and the client's first render match.
func fixedChartData() []int { return []int{42, 17, 63, 28, 55, 9, 71} }
func randomValues() []int {
v := make([]int, len(chartLabels))
for i := range v {
v[i] = rand.Intn(95) + 5
// chartDemoData is a week of values; a non-zero seed reshuffles them deterministically, so
// "Shuffle" changes the chart without a data source and without a random that would differ
// between the server's render and the client's first one.
func chartDemoData(seed int) []float64 {
base := []float64{42, 17, 63, 28, 55, 9, 71}
if seed == 0 {
return base
}
return v
}
func renderSVG(c interface {
Render(chart.RendererProvider, io.Writer) error
}) string {
var buf bytes.Buffer
if c.Render(chart.SVG, &buf) != nil {
return "<p class=\"text-danger m-0\">chart error</p>"
}
return buf.String()
}
func barSVG(values []int) string {
bars := make([]chart.Value, len(values))
for i, v := range values {
bars[i] = chart.Value{Value: float64(v), Label: chartLabels[i%len(chartLabels)]}
}
return renderSVG(&chart.BarChart{
Title: "Weekly values (bar)",
TitleStyle: chart.Style{FontSize: 15},
Background: chart.Style{Padding: chart.Box{Top: 48, Left: 16, Right: 16, Bottom: 16}},
Height: 320, BarWidth: 48, Bars: bars,
})
}
func pieSVG(values []int) string {
vs := make([]chart.Value, len(values))
for i, v := range values {
vs[i] = chart.Value{Value: float64(v), Label: chartLabels[i%len(chartLabels)]}
}
return renderSVG(&chart.PieChart{
Title: "Share by day (pie)",
TitleStyle: chart.Style{FontSize: 15},
Background: chart.Style{Padding: chart.Box{Top: 48}},
Width: 320, Height: 320, Values: vs,
})
}
// chartSkeleton is what the SERVER puts where a chart is going to be: a box of the right
// height, so nothing jumps when the real one arrives.
func chartSkeleton(height string) *VNode {
return Div(Attr("class", "flex animate-pulse items-center justify-center rounded-default bg-surface-muted "+height),
Span(Attr("class", "text-xs text-ink-faint"), Text("drawing…")),
)
}
// newChartDrawing returns a signal that is FALSE on the server and on the client's first
// render, and true from the moment the WebAssembly has committed that first render.
//
// It is what keeps the charts CLIENT-DRAWN. go-chart is ordinary Go and would run just as
// happily on the server — it used to, and this page's markup carried two finished SVGs.
// Two reasons not to:
//
// - It is work the server does on every single request for a picture that only matters
// once the page is alive. Drawing it in the browser costs the server nothing and the
// reader nothing they can see.
// - It is the more honest demonstration. A Go charting library, compiled to WebAssembly,
// drawing an SVG in the browser is the thing this layer claims it can do. Shipping a
// server-rendered picture of one proves the opposite point.
//
// The false-on-first-render part is not optional: hydration walks the server's DOM
// alongside the client's first tree, so that tree has to be the SAME tree. Draw the charts
// on the client's first pass and the two disagree, and the reconciler has to rebuild what
// it should have adopted.
func newChartDrawing() *Signal[bool] {
drawn := NewSignal(false)
wasmruntime.AfterRender(func() {
if !drawn.Get() {
drawn.Set(true) // a write re-renders; the second pass draws for real
out := make([]float64, len(base))
for i, b := range base {
m := (int(b)*7 + seed*13) % 80
if m < 4 {
m = 4
}
})
return drawn
}
// chartBox renders one chart, or the placeholder standing in for it. draw is a closure so
// that on the server go-chart is never called at all — not called and discarded, but never
// entered.
func chartBox(class, height string, drawn bool, draw func() string) *VNode {
if !drawn {
return Div(Attr("class", class), chartSkeleton(height))
out[i] = float64(m)
}
return Div(Attr("class", class), Raw(draw()))
return out
}
//gowasm:page /wasm/chart static layout=app
func ChartPage(d Deps) func() *VNode {
data := NewSignal(fixedChartData())
drawn := newChartDrawing()
seed := NewSignal(0)
barChart := ui.NewChart()
areaChart := ui.NewChart()
return func() *VNode {
values := data.Get()
values := chartDemoData(seed.Get())
return docPage("Rendering", "SSR & hydration",
"A static route is rendered to HTML by the server, so the page is complete before any "+
@@ -132,34 +52,27 @@ func ChartPage(d Deps) func() *VNode {
"class onto the page forever."),
),
docSection("charts", "A worked example: charts",
prose("These charts are SVG produced by go-chart — a plain Go library that knows nothing "+
"about the browser. They are drawn by the WEBASSEMBLY, in your browser, and never by the "+
"server: what the server sends is the two placeholders you may have seen for a moment, "+
"and the WebAssembly replaces them on its first commit."),
prose("That is the demonstration. A Go charting library, compiled to wasm, drawing an SVG in "+
"the browser is exactly what this layer claims it can do — and a server-rendered picture "+
"of a chart would prove the opposite point while looking identical. Shuffle redraws them, "+
"and no request is made."),
prose("The rest of the page IS server-rendered — the headings, the prose, the code you are "+
"reading. Static and client-drawn are not opposites: a route can be pre-rendered and still "+
"leave the expensive, browser-only parts of itself for the client."),
docSection("charts", "A worked example: a chart",
prose("The two charts below are webui.Chart. Their SVG — axes, rounded columns, the smoothed "+
"area — is drawn on the SERVER and shipped in the page's HTML: view source and the marks "+
"are already there, complete before any WebAssembly runs. That is what static buys."),
prose("What the server cannot send is the interaction. The hover tooltip and the resize-to-fit "+
"come alive when the WebAssembly hydrates the page — it adopts the SVG already on screen and "+
"wires the pointer handlers to it, redrawing nothing. Server-rendered picture, client-side "+
"behaviour, one component. Shuffle re-renders it in the browser, and no request is made."),
Div(Attr("class", "mt-4"),
ui.Button(ui.ButtonProps{Color: ui.ButtonPrimary, Icon: "chart-column", Text: "Shuffle data",
OnClick: func() { data.Set(randomValues()) }}),
OnClick: func() { seed.Set(seed.Get() + 1) }}),
),
Div(Attr("class", "mt-4 grid gap-4 lg:grid-cols-12"),
chartBox("lg:col-span-7 rounded-default border border-line bg-surface p-3 shadow-xs overflow-auto",
"h-[260px]", drawn.Get(), func() string { return barSVG(values) }),
chartBox("lg:col-span-5 rounded-default border border-line bg-surface p-3 shadow-xs overflow-auto",
"h-[320px]", drawn.Get(), func() string { return pieSVG(values) }),
Div(Attr("class", "mt-4 grid gap-4 lg:grid-cols-2"),
Div(Attr("class", "rounded-default border border-line bg-surface p-3 shadow-xs"),
barChart.Render(ui.ChartProps{Kind: ui.ChartBar, Labels: chartPageDays,
Series: []ui.ChartSeries{{Name: "Requests", Data: values}}, Height: 240})),
Div(Attr("class", "rounded-default border border-line bg-surface p-3 shadow-xs"),
areaChart.Render(ui.ChartProps{Kind: ui.ChartArea, Smooth: true, Labels: chartPageDays,
Series: []ui.ChartSeries{{Name: "Requests", Data: values}}, Height: 240})),
),
note("go-chart lives in the EXAMPLE, not in kjol",
"The engine is standard-library-only. This example is its own Go module precisely so a "+
"charting dependency it happens to want does not become a dependency of everyone who "+
"uses the framework."),
),
docSection("api", "Reference",
@@ -167,7 +80,7 @@ func ChartPage(d Deps) func() *VNode {
apiRow{"//gowasm:page /path static", "Pre-render this route on the server, then hydrate it."},
apiRow{"vdom.RenderHTML", "Render a tree to an HTML string. This is what the server calls."},
apiRow{"wasmruntime.Hydrate", "Adopt server-rendered DOM instead of building it. The client's entry point for a static route."},
apiRow{"vdom.Raw", "Insert markup verbatim — how the SVG the WebAssembly drew gets in. The reconciler clears it correctly when the element is reused."},
apiRow{"vdom.Raw", "Insert markup verbatim — how webui.Chart's SVG string enters the tree. The reconciler clears it correctly when the element is reused."},
),
),
)
@@ -176,42 +89,22 @@ func ChartPage(d Deps) func() *VNode {
const chartSnippet = `//gowasm:page /wasm/chart static layout=app
func ChartPage(d Deps) func() *VNode {
data := NewSignal(fixedChartData())
drawn := NewSignal(false) // false on the server AND on the first client render
// AfterRender is the post-commit hook. It fires once the WebAssembly has put its
// first tree on the page — the earliest moment at which drawing is a client act.
wasmruntime.AfterRender(func() {
if !drawn.Get() {
drawn.Set(true) // a write re-renders; the second pass draws
}
})
seed := NewSignal(0)
chart := ui.NewChart() // a controller: holds hover + refs across renders
return func() *VNode {
return Div(
ui.Button(ui.ButtonProps{
Text: "Shuffle data",
OnClick: func() { data.Set(randomValues()) },
return docPage("Rendering", "SSR & hydration",
// The chart's SVG is rendered on the SERVER and shipped in the HTML.
// On hydration the client adopts those nodes and wires the pointer
// handlers — the hover tooltip comes alive without redrawing anything.
chart.Render(ui.ChartProps{
Kind: ui.ChartBar,
Labels: []string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"},
Series: []ui.ChartSeries{{Name: "Requests", Data: chartDemoData(seed.Get())}},
}),
// The server never enters barSVG: chartBox takes a CLOSURE, and calls it only
// once drawn is true. It renders the placeholder instead, and the WebAssembly
// swaps in the real chart on its first commit.
//
// drawn must be FALSE on the client's first render too. Hydration walks the
// server's DOM alongside the client's first tree, so the two have to BE the
// same tree; draw on that first pass and the reconciler rebuilds what it
// should have adopted.
chartBox("", "h-[260px]", drawn.Get(),
func() string { return barSVG(data.Get()) }),
ui.Button(ui.ButtonProps{Text: "Shuffle", OnClick: func() {
seed.Set(seed.Get() + 1) // a signal write re-renders, in the browser
}}),
)
}
}
// chartBox is the whole trick, and it is four lines.
func chartBox(class, height string, drawn bool, draw func() string) *VNode {
if !drawn {
return Div(Attr("class", class), chartSkeleton(height))
}
return Div(Attr("class", class), Raw(draw()))
}`

View File

@@ -1157,43 +1157,99 @@ func searchSection() func() *VNode {
// ---- charts --------------------------------------------------------------
var chartDaysWasm = []string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}
var pieLabelsWasm = []string{"Direct", "Search", "Social", "Email", "Referral"}
var regionsWasm = []string{"East", "Central", "Mountain", "Pacific"}
// A made-up per-state metric for the choropleth, and a few cities (lat/lng) — Anchorage
// and Honolulu land on albersUsa's Alaska and Hawaii insets.
var usSignups = map[string]float64{
"CA": 4820, "TX": 3910, "NY": 3120, "FL": 2870, "IL": 1740, "PA": 1610, "OH": 1490, "GA": 1450,
"NC": 1360, "MI": 1280, "WA": 1230, "AZ": 1180, "MA": 1120, "VA": 1090, "CO": 980, "TN": 940,
"NJ": 910, "OR": 720, "MN": 690, "WI": 610, "MO": 560, "MD": 540, "IN": 520, "NV": 480,
"UT": 430, "AL": 390, "SC": 360, "KY": 310, "LA": 300, "OK": 280, "CT": 260, "IA": 210,
"KS": 180, "AK": 140, "HI": 160, "ME": 120, "MT": 90, "WY": 60, "ND": 70, "SD": 80,
}
var usCities = []ui.USHeatmapPoint{
{Label: "Seattle", Lat: 47.6062, Lng: -122.3321, Value: 1230},
{Label: "San Francisco", Lat: 37.7749, Lng: -122.4194, Value: 2110},
{Label: "Denver", Lat: 39.7392, Lng: -104.9903, Value: 980},
{Label: "Chicago", Lat: 41.8781, Lng: -87.6298, Value: 1740},
{Label: "New York", Lat: 40.7128, Lng: -74.006, Value: 3120},
{Label: "Miami", Lat: 25.7617, Lng: -80.1918, Value: 1460},
{Label: "Anchorage", Lat: 61.2181, Lng: -149.9003, Value: 140},
{Label: "Honolulu", Lat: 21.3069, Lng: -157.8583, Value: 160},
}
func chartsSection() func() *VNode {
values := NewSignal(fixedChartData())
drawn := newChartDrawing()
seed := NewSignal(0)
threeD := NewSignal(false)
barC, donutC, areaC, lineC := ui.NewChart(), ui.NewChart(), ui.NewChart(), ui.NewChart()
horizC, stackC := ui.NewChart(), ui.NewChart()
heat := ui.NewUSHeatmap()
return func() *VNode {
v := values.Get()
sh := seed.Get()
shuffle := func(base []float64) []float64 {
out := make([]float64, len(base))
for i, b := range base {
if sh == 0 {
out[i] = b
continue
}
m := (int(b)*7 + sh*13) % 80
if m < 4 {
m = 4
}
out[i] = float64(m)
}
return out
}
requests := ui.ChartSeries{Name: "Requests", Data: shuffle([]float64{42, 17, 63, 28, 55, 9, 71})}
errs := ui.ChartSeries{Name: "Errors", Data: shuffle([]float64{8, 3, 12, 6, 9, 2, 14})}
pie := ui.ChartSeries{Name: "Traffic", Data: shuffle([]float64{40, 25, 20, 15, 8})}
threeDLabel := "3D"
if threeD.Get() {
threeDLabel = "Flat"
}
return docSection("charts", "Charts",
prose("These are SVG, produced by go-chart — a plain Go library that knows nothing about "+
"browsers. They are drawn by the WEBASSEMBLY, in your browser. The server never enters "+
"the drawing code at all; it renders a placeholder, and the wasm replaces it on its first "+
"commit."),
prose("A Go charting library, compiled to wasm, drawing an SVG in the browser is the thing "+
"this layer claims it can do. Server-rendering a picture of a chart would look identical "+
"and prove the opposite point."),
prose("webui.Chart draws its own SVG — nice-scale axes, rounded columns, arc slices, a "+
"pointer crosshair — with no charting library. The geometry is pure Go, so the same shapes "+
"the Solid kit draws on /js run here in the WebAssembly, against the same theme tokens. Change "+
"the data and only the marks that moved re-render."),
demo("Drawn in the browser, by Go",
row("grid gap-4 lg:grid-cols-12",
chartBox("lg:col-span-7 rounded-default border border-line bg-surface p-3 shadow-xs overflow-auto",
"h-[260px]", drawn.Get(), func() string { return barSVG(v) }),
chartBox("lg:col-span-5 rounded-default border border-line bg-surface p-3 shadow-xs overflow-auto",
"h-[320px]", drawn.Get(), func() string { return pieSVG(v) }),
demo("Bar, donut, smooth area, two lines — one data set, and a 3D toggle",
row("grid gap-6 lg:grid-cols-12",
Div(Attr("class", "lg:col-span-7"), barC.Render(ui.ChartProps{Kind: ui.ChartBar, Labels: chartDaysWasm, Series: []ui.ChartSeries{requests, errs}, Height: 260, ThreeD: threeD.Get()})),
Div(Attr("class", "lg:col-span-5"), donutC.Render(ui.ChartProps{Kind: ui.ChartDonut, Labels: pieLabelsWasm, Series: []ui.ChartSeries{pie}, Height: 260, ThreeD: threeD.Get()})),
Div(Attr("class", "lg:col-span-7"), areaC.Render(ui.ChartProps{Kind: ui.ChartArea, Smooth: true, Labels: chartDaysWasm, Series: []ui.ChartSeries{requests}, Height: 220})),
Div(Attr("class", "lg:col-span-5"), lineC.Render(ui.ChartProps{Kind: ui.ChartLine, Labels: chartDaysWasm, Series: []ui.ChartSeries{requests, errs}, Height: 220})),
),
row("mt-4 flex items-center gap-2",
ui.Button(ui.ButtonProps{Color: ui.ButtonPrimary, Small: true, Text: "New data",
OnClick: func() { values.Set(randomValues()) }}),
Span(Attr("class", "text-xs text-ink-muted"),
Text("Re-drawn in Go, in the browser. No request is made.")),
row("mt-4 flex items-center gap-3",
ui.Button(ui.ButtonProps{Color: ui.ButtonPrimary, Small: true, Text: "New data", OnClick: func() { seed.Set(seed.Get() + 1) }}),
ui.Button(ui.ButtonProps{Color: ui.ButtonNeutral, Small: true, Text: threeDLabel, OnClick: func() { threeD.Set(!threeD.Get()) }}),
Span(Attr("class", "text-xs text-ink-muted"), Text("Hover any chart. 3D extrudes the bars and tilts the donut.")),
),
),
note("webui.Chart is a stub, and says so",
"The Solid kit's Chart draws its own SVG — nice-scale axes, rounded columns, arc slices, "+
"a pointer-driven crosshair — with no charting library at all. That geometry has not "+
"been ported to the neutral Go runtime yet, so the Go port keeps the props shape for "+
"parity and renders only its box. This example draws with go-chart "+
"instead, as above. Pretending the port drew charts would be the one thing this site refuses to do."),
demo("Horizontal bars, and stacked",
row("grid gap-6 lg:grid-cols-2",
horizC.Render(ui.ChartProps{Kind: ui.ChartBar, Horizontal: true, Labels: chartDaysWasm, Series: []ui.ChartSeries{requests, errs}, Height: 260}),
stackC.Render(ui.ChartProps{Kind: ui.ChartBar, Stacked: true, Labels: regionsWasm, Series: []ui.ChartSeries{
{Name: "Requests", Data: shuffle([]float64{42, 55, 28, 63})},
{Name: "Errors", Data: shuffle([]float64{8, 9, 6, 12})},
{Name: "Retries", Data: shuffle([]float64{5, 7, 3, 9})},
}, Height: 260}),
),
),
demo("US heatmap — a value per state, with proportional lat/lng points on top",
heat.Render(ui.USHeatmapProps{Data: usSignups, Points: usCities, Proportional: true}),
Span(Attr("class", "mt-3 block text-xs text-ink-muted"),
Text("webui.USHeatmap shades each state on the choropleth ramp and projects lat/lng points "+
"with a Go albersUsa port — Anchorage and Honolulu land on the insets. Hover a state or a point.")),
),
)
}
}
@@ -1337,7 +1393,6 @@ func languageOptions() []ui.FormSelectOption {
}
}
const kitSnippet = `// A component is a function taking a props struct.
ui.Button(ui.ButtonProps{
Color: ui.ButtonPrimary,

View File

@@ -3,12 +3,9 @@
package app
import (
"bytes"
"strconv"
"time"
chart "github.com/wcharczuk/go-chart/v2"
. "kjol/vdom"
ui "kjol/webui"
)
@@ -17,7 +14,7 @@ import (
// component (same builders, signals, On handlers). The //gowasm:server directive
// makes the build generate a client stub so calling ServerCounter() on the
// frontend is identical to calling any component; the state and this render run
// on the server (its chart is computed there with go-chart), and clicks
// on the server (its chart SVG is drawn there by webui.ChartSVG), and clicks
// round-trip over /rsc.
//
// The chart plots the counter value against the wall-clock time of each click
@@ -60,61 +57,24 @@ type clickPoint struct {
V int // counter value after the click
}
// clickChartSVG plots counter value vs. time-of-click (ms since the first
// click) as a line graph. Explicit axis ranges keep it valid for the tricky
// cases (a single click, or several clicks within the same millisecond).
// clickChartSVG plots the counter value at each click as a line, drawn on the server by
// webui.ChartSVG — the same chart geometry the client kit uses, rendered to a static SVG
// string (no controller, no hover) because a server component's output is HTML.
func clickChartSVG(points []clickPoint) string {
if len(points) == 0 {
return `<span class="text-muted">Click + / to plot the counter over time (ms since the first click).</span>`
return `<span class="text-ink-muted">Click + / to plot the counter over each click.</span>`
}
t0 := points[0].T
xs := make([]float64, len(points))
ys := make([]float64, len(points))
minY, maxY := 0.0, 0.0 // keep the zero baseline in view for context
vals := make([]float64, len(points))
labels := make([]string, len(points))
for i, p := range points {
xs[i] = float64(p.T - t0)
ys[i] = float64(p.V)
if ys[i] < minY {
minY = ys[i]
}
if ys[i] > maxY {
maxY = ys[i]
}
vals[i] = float64(p.V)
labels[i] = strconv.Itoa(i + 1)
}
maxX := xs[len(xs)-1]
if maxX <= 0 {
maxX = 1 // rapid or single clicks: avoid a zero-width x-range
}
if minY == maxY {
maxY++ // avoid a zero-height y-range
}
graph := chart.Chart{
Title: "Counter over time (computed on the server)",
TitleStyle: chart.Style{FontSize: 14},
Background: chart.Style{Padding: chart.Box{Top: 48, Left: 20, Right: 20, Bottom: 40}},
Height: 260,
XAxis: chart.XAxis{
Name: "ms since first click",
Range: &chart.ContinuousRange{Min: 0, Max: maxX},
},
YAxis: chart.YAxis{
Name: "counter",
Range: &chart.ContinuousRange{Min: minY, Max: maxY},
},
Series: []chart.Series{
chart.ContinuousSeries{
XValues: xs,
YValues: ys,
Style: chart.Style{
StrokeColor: chart.ColorGreen, StrokeWidth: 2,
DotColor: chart.ColorGreen, DotWidth: 4, // a dot at each click
},
},
},
}
var buf bytes.Buffer
if graph.Render(chart.SVG, &buf) != nil {
return `<span class="text-danger">chart error</span>`
}
return buf.String()
return ui.ChartSVG(ui.ChartProps{
Kind: ui.ChartLine,
Labels: labels,
Series: []ui.ChartSeries{{Name: "Counter", Data: vals, Color: "var(--color-chart-4)"}},
Height: 240,
NoTooltip: true,
})
}