add WASM blazor-like thing
This commit is contained in:
35
.vscode/launch.json
vendored
Normal file
35
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
// Debug configs for the gowasm example. cwd is the example dir because the
|
||||||
|
// dev server resolves ./wwwroot, ./app, ./wasm and the watched engine dir
|
||||||
|
// relative to it.
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "gowasm: dev server",
|
||||||
|
"type": "go",
|
||||||
|
"request": "launch",
|
||||||
|
"mode": "auto",
|
||||||
|
"program": "${workspaceFolder}/go/cmd/examples/go-wasm-web/server",
|
||||||
|
"cwd": "${workspaceFolder}/go/cmd/examples/go-wasm-web",
|
||||||
|
"args": ["-addr", ":8085"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "gowasm: dev server (no watch)",
|
||||||
|
"type": "go",
|
||||||
|
"request": "launch",
|
||||||
|
"mode": "auto",
|
||||||
|
"program": "${workspaceFolder}/go/cmd/examples/go-wasm-web/server",
|
||||||
|
"cwd": "${workspaceFolder}/go/cmd/examples/go-wasm-web",
|
||||||
|
"args": ["-watch=false"]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "gowasm: codegen (gowasmgen)",
|
||||||
|
"type": "go",
|
||||||
|
"request": "launch",
|
||||||
|
"mode": "auto",
|
||||||
|
"program": "${workspaceFolder}/go/cmd/gowasmgen",
|
||||||
|
"cwd": "${workspaceFolder}/go/cmd/examples/go-wasm-web",
|
||||||
|
"args": ["./app"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
73
.vscode/tasks.json
vendored
Normal file
73
.vscode/tasks.json
vendored
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
{
|
||||||
|
// Tasks for the kjol repo. The gowasm example is a nested module at
|
||||||
|
// go/cmd/examples/go-wasm-web, so its tasks set cwd there; the module-wide
|
||||||
|
// Go tasks run in go/.
|
||||||
|
"version": "2.0.0",
|
||||||
|
"tasks": [
|
||||||
|
{
|
||||||
|
"label": "gowasm: dev server (hot reload)",
|
||||||
|
"detail": "Run the go-wasm-web example: codegen + SSR + hot reload on :8085",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "go run ./server",
|
||||||
|
"options": { "cwd": "${workspaceFolder}/go/cmd/examples/go-wasm-web" },
|
||||||
|
"isBackground": true,
|
||||||
|
"problemMatcher": {
|
||||||
|
"owner": "go",
|
||||||
|
"pattern": {
|
||||||
|
"regexp": "^(.*):(\\d+):(\\d+):\\s+(.*)$",
|
||||||
|
"file": 1, "line": 2, "column": 3, "message": 4
|
||||||
|
},
|
||||||
|
"background": {
|
||||||
|
"activeOnStart": true,
|
||||||
|
"beginsPattern": "rebuilding",
|
||||||
|
"endsPattern": "serving|reloading clients"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"presentation": { "reveal": "always", "panel": "dedicated", "clear": true },
|
||||||
|
"group": { "kind": "build", "isDefault": true }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "gowasm: build (build.sh)",
|
||||||
|
"detail": "One-off build of the example: codegen + wasm + stage wasm_exec.js",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "./build.sh",
|
||||||
|
"options": { "cwd": "${workspaceFolder}/go/cmd/examples/go-wasm-web" },
|
||||||
|
"problemMatcher": ["$go"],
|
||||||
|
"group": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "gowasm: codegen",
|
||||||
|
"detail": "Regenerate app/*.gen.go from //gowasm: directives",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "go run kjol/cmd/gowasmgen ./app",
|
||||||
|
"options": { "cwd": "${workspaceFolder}/go/cmd/examples/go-wasm-web" },
|
||||||
|
"problemMatcher": ["$go"],
|
||||||
|
"group": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "kjol: build ./...",
|
||||||
|
"detail": "Build the whole kjol module (excludes the nested example)",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "go build ./...",
|
||||||
|
"options": { "cwd": "${workspaceFolder}/go" },
|
||||||
|
"problemMatcher": ["$go"],
|
||||||
|
"group": "build"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "kjol: vet ./...",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "go vet ./...",
|
||||||
|
"options": { "cwd": "${workspaceFolder}/go" },
|
||||||
|
"problemMatcher": ["$go"],
|
||||||
|
"group": "test"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "kjol: test ./...",
|
||||||
|
"type": "shell",
|
||||||
|
"command": "go test ./...",
|
||||||
|
"options": { "cwd": "${workspaceFolder}/go" },
|
||||||
|
"problemMatcher": ["$go"],
|
||||||
|
"group": { "kind": "test", "isDefault": true }
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -34,7 +34,11 @@ Language-first, **not** feature-first. Consequence: the **bundler is Go** and li
|
|||||||
### go/ — module `kjol`
|
### go/ — module `kjol`
|
||||||
|
|
||||||
Packages, imported as `kjol/<name>`: `appenv basic chrono config csv dbutil finance httputil
|
Packages, imported as `kjol/<name>`: `appenv basic chrono config csv dbutil finance httputil
|
||||||
l4g security snailmail validation bundler`, plus `cmd/{bundle,migrate,loc,passgen,typecheck}`.
|
l4g security snailmail validation bundler`, plus the **gowasm** web-UI engine (`vdom`
|
||||||
|
`wasmruntime` `rsc` `wasmdevserver` — author components in pure Go compiled to WebAssembly;
|
||||||
|
all stdlib-only), and `cmd/{bundle,migrate,loc,passgen,typecheck,gowasmgen}`. A runnable
|
||||||
|
example lives in `cmd/examples/go-wasm-web` (its own nested module so its go-chart dep stays
|
||||||
|
out of kjol).
|
||||||
|
|
||||||
Build / test (run from repo root):
|
Build / test (run from repo root):
|
||||||
```
|
```
|
||||||
|
|||||||
71
go/cmd/examples/go-wasm-web/README.md
Normal file
71
go/cmd/examples/go-wasm-web/README.md
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
# go-wasm-web — example app for the gowasm engine
|
||||||
|
|
||||||
|
A runnable example of kjol's **gowasm** engine: author UI **components in pure
|
||||||
|
Go**, compiled to **WebAssembly**, with **SSR + hydration**, **Next.js-style
|
||||||
|
server components**, layouts, and a **flash-free, state-preserving hot reload**.
|
||||||
|
No custom markup, no JSX — just Go. The engine lives in top-level kjol packages
|
||||||
|
(`kjol/go/{vdom,wasmruntime,rsc,wasmdevserver}`); this directory is only the app
|
||||||
|
that consumes them.
|
||||||
|
|
||||||
|
## Run it
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cd cmd/examples/go-wasm-web
|
||||||
|
go run ./server # codegen + SSR + hot reload at http://localhost:8085
|
||||||
|
```
|
||||||
|
|
||||||
|
Open http://localhost:8085. `/` and `/about` use the light **public** layout,
|
||||||
|
`/chart` and `/server` use the dark **app** layout. Edit any `.go` file and the
|
||||||
|
browser hot-swaps the new wasm **without a full reload or a flash**, preserving
|
||||||
|
page state; a build failure shows the Go compiler output as an overlay.
|
||||||
|
|
||||||
|
(`build.sh` does a one-off build instead of running the dev server.)
|
||||||
|
|
||||||
|
## This is a separate module
|
||||||
|
|
||||||
|
`go.mod` here declares its own module (`gowasmweb`) with `replace kjol => ../../..`,
|
||||||
|
so the app's `go-chart` dependency (and freetype / x/image) stays out of kjol —
|
||||||
|
the engine packages (`vdom`, `wasmruntime`, `rsc`, `wasmdevserver`) are
|
||||||
|
**stdlib-only**. `go build ./...` at the kjol root does not descend into this
|
||||||
|
nested module; build it from this directory.
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
```
|
||||||
|
app/ the application — neutral, standalone functions (no central struct)
|
||||||
|
pages.go Deps + Shell + App/Public layouts + nav + Counter + pages
|
||||||
|
chart.go Chart page (go-chart, renders on both sides)
|
||||||
|
server_counter.go //gowasm:server component (server-only; clicks-over-time chart)
|
||||||
|
*.gen.go GENERATED by kjol/cmd/gowasmgen (routes, layout dispatch, stubs)
|
||||||
|
wasm/ the js/wasm client entry point (main_native.go is a host stub)
|
||||||
|
server/ the dev-server main: injects Build/Render/Document into wasmdevserver
|
||||||
|
wwwroot/ bootstrap.js, bootstrap.min.css (+ generated wasm_exec.js, app.wasm)
|
||||||
|
```
|
||||||
|
|
||||||
|
## How it maps onto the engine (top-level `kjol` packages)
|
||||||
|
|
||||||
|
| Engine package | Role | This app's use |
|
||||||
|
|---|---|---|
|
||||||
|
| `kjol/vdom` | neutral virtual DOM (native + wasm): `VNode`, builders, `Signal`, `RenderHTML` | pages build `*VNode`; `server` SSRs with `vdom.RenderHTML` |
|
||||||
|
| `kjol/wasmruntime` | wasm client runtime: reconcile, `Run`/`Hydrate`, router, fetch, HMR state | `wasm/main.go` calls `Hydrate`/`Run` |
|
||||||
|
| `kjol/rsc` | stateless server components over HTTP (gob) | `//gowasm:server` + the generated client stub |
|
||||||
|
| `kjol/wasmdevserver` | reusable dev server: SSR, `/rsc`, hot reload, error overlay | `server/main.go` fills a `wasmdevserver.Config` |
|
||||||
|
| `kjol/cmd/gowasmgen` | directive codegen → `app/*.gen.go` | run by `buildWasm` and `//go:generate` |
|
||||||
|
|
||||||
|
The **golden rule** holds: `wasmdevserver` imports no app code. The app injects
|
||||||
|
`Build` (how to compile the wasm), `Render` (SSR a route → HTML), and `Document`
|
||||||
|
(wrap it in a page) via `wasmdevserver.Config` — the same coupling inversion kjol
|
||||||
|
uses elsewhere.
|
||||||
|
|
||||||
|
## Directives (expanded by `gowasmgen` at build time)
|
||||||
|
|
||||||
|
```go
|
||||||
|
//gowasm:page / static layout=public // a route; `static` SSRs it, `layout=` wraps it
|
||||||
|
func HomePage(d Deps) func() *VNode { ... }
|
||||||
|
|
||||||
|
//gowasm:layout public // chrome for pages that opt into layout=public
|
||||||
|
func PublicLayout(d Deps, content *VNode) *VNode { ... }
|
||||||
|
|
||||||
|
//gowasm:server // runs on the server; calling it looks identical
|
||||||
|
func ServerCounter() func() *VNode { count := NewSignal(0); ... }
|
||||||
|
```
|
||||||
81
go/cmd/examples/go-wasm-web/app/chart.go
Normal file
81
go/cmd/examples/go-wasm-web/app/chart.go
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"io"
|
||||||
|
"math/rand"
|
||||||
|
|
||||||
|
chart "github.com/wcharczuk/go-chart/v2"
|
||||||
|
|
||||||
|
. "kjol/vdom"
|
||||||
|
)
|
||||||
|
|
||||||
|
var chartLabels = []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
|
||||||
|
}
|
||||||
|
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,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
//gowasm:page /chart static layout=app
|
||||||
|
func ChartPage(d Deps) func() *VNode {
|
||||||
|
data := NewSignal(fixedChartData())
|
||||||
|
return func() *VNode {
|
||||||
|
values := data.Get()
|
||||||
|
return Div(
|
||||||
|
H2(Attr("class", "h4 mb-3"), Text("Charts — go-chart (SSR + hydrate)")),
|
||||||
|
P(Attr("class", "text-secondary"),
|
||||||
|
Text("Rendered to SVG on the server, hydrated on the client; Shuffle re-renders client-side.")),
|
||||||
|
Button(Attr("class", "btn btn-primary mb-3"),
|
||||||
|
On(EVENT_CLICK, func() { data.Set(randomValues()) }), Text("Shuffle Data")),
|
||||||
|
Div(Attr("class", "row"),
|
||||||
|
Div(Attr("class", "col-12 col-lg-7 mb-3"),
|
||||||
|
Div(Attr("class", "border rounded p-2 bg-white overflow-auto"), Raw(barSVG(values)))),
|
||||||
|
Div(Attr("class", "col-12 col-lg-5 mb-3"),
|
||||||
|
Div(Attr("class", "border rounded p-2 bg-white overflow-auto"), Raw(pieSVG(values)))),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
13
go/cmd/examples/go-wasm-web/app/client.gen.go
Normal file
13
go/cmd/examples/go-wasm-web/app/client.gen.go
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
// Code generated by gowasmgen. DO NOT EDIT.
|
||||||
|
|
||||||
|
//go:build js && wasm
|
||||||
|
|
||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"kjol/rsc"
|
||||||
|
"kjol/vdom"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ServerCounter is a generated client stub for the server component of the same name.
|
||||||
|
func ServerCounter() func() *vdom.VNode { return rsc.Mount("ServerCounter") }
|
||||||
193
go/cmd/examples/go-wasm-web/app/pages.go
Normal file
193
go/cmd/examples/go-wasm-web/app/pages.go
Normal file
@@ -0,0 +1,193 @@
|
|||||||
|
// Package app holds the application's pages and components as standalone
|
||||||
|
// functions (no central App struct). It is platform-neutral, so the SAME code
|
||||||
|
// renders on the server (SSR) and hydrates on the client.
|
||||||
|
//
|
||||||
|
// Directives (processed by cmd/gowasmgen at build time):
|
||||||
|
//
|
||||||
|
// //gowasm:page <path> [static] [layout=<name>]
|
||||||
|
// marks a page factory as a route. `static`
|
||||||
|
// pre-renders it on the server (SSR);
|
||||||
|
// `layout=<name>` wraps it in a //gowasm:layout.
|
||||||
|
// //gowasm:layout <name> marks a func(Deps, *VNode) *VNode as a named
|
||||||
|
// layout that wraps a page's content.
|
||||||
|
// //gowasm:server (see server_counter.go) marks a component
|
||||||
|
// that runs on the server; the generated
|
||||||
|
// client stub makes calling it identical to
|
||||||
|
// calling any other component.
|
||||||
|
//
|
||||||
|
// The Routes() map, StaticPaths set, and RouteLayout/LayoutFor dispatch are all
|
||||||
|
// generated from these directives.
|
||||||
|
package app
|
||||||
|
|
||||||
|
//go:generate go run kjol/cmd/gowasmgen .
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
. "kjol/vdom"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Deps are the client-only capabilities, injected so the pages stay neutral.
|
||||||
|
type Deps struct {
|
||||||
|
Path func() string
|
||||||
|
Navigate func(string)
|
||||||
|
}
|
||||||
|
|
||||||
|
func itoa(n int) string { return strconv.Itoa(n) }
|
||||||
|
|
||||||
|
// Layout wraps a page's rendered content with shared chrome (nav, footer, …).
|
||||||
|
// Layouts are declared with //gowasm:layout and selected per route via a page's
|
||||||
|
// `layout=` directive; the generated LayoutFor dispatches by name.
|
||||||
|
type Layout func(d Deps, content *VNode) *VNode
|
||||||
|
|
||||||
|
// Shell renders the current route's page inside its declared layout. `routes` is
|
||||||
|
// the generated route table; `d.Path()` selects both the page and its layout.
|
||||||
|
func Shell(d Deps, routes map[string]func() *VNode) *VNode {
|
||||||
|
path := d.Path()
|
||||||
|
var content *VNode
|
||||||
|
if page := routes[path]; page != nil {
|
||||||
|
content = page()
|
||||||
|
} else {
|
||||||
|
content = notFound(path)
|
||||||
|
}
|
||||||
|
return LayoutFor(d, path, content)
|
||||||
|
}
|
||||||
|
|
||||||
|
func notFound(path string) *VNode {
|
||||||
|
return Div(
|
||||||
|
H2(Attr("class", "h4 mb-3"), Text("Page not found")),
|
||||||
|
P(Attr("class", "text-secondary"), Text("No route matches "+path+".")),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- layouts (selected per route via `layout=` in //gowasm:page) ---------
|
||||||
|
|
||||||
|
// PublicLayout is the chrome for public/marketing pages: a light navbar with a
|
||||||
|
// call-to-action into the app, and a footer. The func(Deps, *VNode) *VNode shape
|
||||||
|
// is what //gowasm:layout expects.
|
||||||
|
//
|
||||||
|
//gowasm:layout public
|
||||||
|
func PublicLayout(d Deps, content *VNode) *VNode {
|
||||||
|
return Div(
|
||||||
|
Nav(Attr("class", "navbar navbar-expand bg-light border-bottom mb-4"),
|
||||||
|
Div(Attr("class", "container"),
|
||||||
|
A(Attr("class", "navbar-brand fw-bold"), Attr("href", "/"), navigate(d, "/"), Text("gowasm")),
|
||||||
|
Ul(Attr("class", "navbar-nav ms-auto align-items-center"),
|
||||||
|
navItem(d, "/", "Home"),
|
||||||
|
navItem(d, "/about", "About"),
|
||||||
|
Li(Attr("class", "nav-item ms-2"),
|
||||||
|
A(Attr("class", "btn btn-sm btn-primary"), Attr("href", "/chart"),
|
||||||
|
navigate(d, "/chart"), Text("Open app →"))),
|
||||||
|
))),
|
||||||
|
Main(Attr("class", "container"),
|
||||||
|
content,
|
||||||
|
Footer(Attr("class", "text-secondary small border-top mt-5 pt-3"),
|
||||||
|
Text("gowasm public site — a tiny Blazor-like engine in Go.")),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AppLayout is the chrome for the application itself: a dark app navbar listing
|
||||||
|
// the app's sections, plus a link back to the public site.
|
||||||
|
//
|
||||||
|
//gowasm:layout app
|
||||||
|
func AppLayout(d Deps, content *VNode) *VNode {
|
||||||
|
return Div(
|
||||||
|
Nav(Attr("class", "navbar navbar-expand navbar-dark bg-dark mb-4"),
|
||||||
|
Div(Attr("class", "container"),
|
||||||
|
A(Attr("class", "navbar-brand fw-bold"), Attr("href", "/chart"), navigate(d, "/chart"), Text("gowasm · app")),
|
||||||
|
Ul(Attr("class", "navbar-nav me-auto"),
|
||||||
|
navItem(d, "/chart", "Chart"),
|
||||||
|
navItem(d, "/server", "Server")),
|
||||||
|
Ul(Attr("class", "navbar-nav"),
|
||||||
|
navItem(d, "/", "Home")),
|
||||||
|
)),
|
||||||
|
Main(Attr("class", "container"), content),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// navItem is a nav link that carries an active state on the current route.
|
||||||
|
func navItem(d Deps, path, label string) *VNode {
|
||||||
|
cls := "nav-link"
|
||||||
|
if d.Path() == path {
|
||||||
|
cls += " active"
|
||||||
|
}
|
||||||
|
return Li(Attr("class", "nav-item"),
|
||||||
|
A(Attr("class", cls), Attr("href", path), navigate(d, path), Text(label)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// navigate intercepts a link click for client-side SPA navigation. On the server
|
||||||
|
// Navigate is nil, so the anchor falls back to a normal navigation.
|
||||||
|
func navigate(d Deps, path string) Mod {
|
||||||
|
return OnEvent(EVENT_CLICK, func(e Event) {
|
||||||
|
if d.Navigate != nil {
|
||||||
|
e.PreventDefault()
|
||||||
|
d.Navigate(path)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Counter is a presentational client component; state is owned by the caller.
|
||||||
|
func Counter(label string, count *Signal[int]) *VNode {
|
||||||
|
return Div(Attr("class", "counter card mb-2"),
|
||||||
|
Div(Attr("class", "card-body py-2 d-flex align-items-center"),
|
||||||
|
Span(Attr("class", "me-2 fw-semibold"), Text(label+": ")),
|
||||||
|
Strong(Attr("class", "badge text-bg-primary me-2"), Text(itoa(count.Get()))),
|
||||||
|
Div(Attr("class", "btn-group btn-group-sm ms-auto"),
|
||||||
|
Button(Attr("class", "btn btn-outline-secondary"),
|
||||||
|
On(EVENT_CLICK, func() { count.Update(func(v int) int { return v - 1 }) }), Text("−")),
|
||||||
|
Button(Attr("class", "btn btn-outline-primary"),
|
||||||
|
On(EVENT_CLICK, func() { count.Update(func(v int) int { return v + 1 }) }), Text("+")),
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
//gowasm:page / static layout=public
|
||||||
|
func HomePage(d Deps) func() *VNode {
|
||||||
|
a := NewSignal(0)
|
||||||
|
b := NewSignal(0)
|
||||||
|
return func() *VNode {
|
||||||
|
return Div(
|
||||||
|
H2(Attr("class", "h4 mb-3"), Text("Home — component composition")),
|
||||||
|
P(Attr("class", "text-secondary"), Text("Two counters; the total is derived across them. Server-rendered, then hydrated.")),
|
||||||
|
Counter("Apples", a),
|
||||||
|
Counter("Bananas", b),
|
||||||
|
Div(Attr("class", "alert alert-info d-flex justify-content-between align-items-center mt-3"),
|
||||||
|
Span(Text("Combined total: ")),
|
||||||
|
Strong(Attr("class", "fs-5"), Text(itoa(a.Get()+b.Get())))),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//gowasm:page /about static layout=public
|
||||||
|
func AboutPage(d Deps) func() *VNode {
|
||||||
|
return func() *VNode {
|
||||||
|
return Div(
|
||||||
|
H2(Attr("class", "h4 mb-3"), Text("About")),
|
||||||
|
P(Attr("class", "lead"),
|
||||||
|
Text("Components are standalone functions; calling a server component looks "+
|
||||||
|
"identical to calling a client one — the //gowasm:server directive and the "+
|
||||||
|
"build-time codegen wire up the round-trip. Static routes are SSR'd; the rest "+
|
||||||
|
"render on the client.")),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//gowasm:page /server layout=app
|
||||||
|
func ServerPage(d Deps) func() *VNode {
|
||||||
|
// ServerCounter is a server component — but calling it is just like calling
|
||||||
|
// any component. On the client this resolves to a generated stub that mounts
|
||||||
|
// it over /rsc; on the server it's the real function. (Not `static`: the
|
||||||
|
// client renders the stub, which round-trips, so there's nothing stable to
|
||||||
|
// pre-render + hydrate.)
|
||||||
|
counter := ServerCounter()
|
||||||
|
return func() *VNode {
|
||||||
|
return Div(
|
||||||
|
H2(Attr("class", "h4 mb-3"), Text("Server component")),
|
||||||
|
P(Attr("class", "text-secondary"),
|
||||||
|
Text("This counter runs on the server. Its state lives there; clicks round-trip "+
|
||||||
|
"and the returned render merges into the DOM. The call site is identical to a "+
|
||||||
|
"client component.")),
|
||||||
|
counter(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
40
go/cmd/examples/go-wasm-web/app/routes.gen.go
Normal file
40
go/cmd/examples/go-wasm-web/app/routes.gen.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
// Code generated by gowasmgen. DO NOT EDIT.
|
||||||
|
package app
|
||||||
|
|
||||||
|
import "kjol/vdom"
|
||||||
|
|
||||||
|
// Routes maps each //gowasm:page path to its instantiated render function.
|
||||||
|
func Routes(d Deps) map[string]func() *vdom.VNode {
|
||||||
|
return map[string]func() *vdom.VNode{
|
||||||
|
"/": HomePage(d),
|
||||||
|
"/about": AboutPage(d),
|
||||||
|
"/chart": ChartPage(d),
|
||||||
|
"/server": ServerPage(d),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// StaticPaths are the routes the server pre-renders (SSR); others render client-side.
|
||||||
|
var StaticPaths = map[string]bool{
|
||||||
|
"/": true,
|
||||||
|
"/about": true,
|
||||||
|
"/chart": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// RouteLayout maps each route to the name of the layout that wraps it.
|
||||||
|
var RouteLayout = map[string]string{
|
||||||
|
"/": "public",
|
||||||
|
"/about": "public",
|
||||||
|
"/chart": "app",
|
||||||
|
"/server": "app",
|
||||||
|
}
|
||||||
|
|
||||||
|
// LayoutFor wraps a page's content in the layout declared for its route.
|
||||||
|
func LayoutFor(d Deps, path string, content *vdom.VNode) *vdom.VNode {
|
||||||
|
switch RouteLayout[path] {
|
||||||
|
case "app":
|
||||||
|
return AppLayout(d, content)
|
||||||
|
case "public":
|
||||||
|
return PublicLayout(d, content)
|
||||||
|
}
|
||||||
|
return AppLayout(d, content)
|
||||||
|
}
|
||||||
11
go/cmd/examples/go-wasm-web/app/server.gen.go
Normal file
11
go/cmd/examples/go-wasm-web/app/server.gen.go
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
// Code generated by gowasmgen. DO NOT EDIT.
|
||||||
|
|
||||||
|
//go:build !(js && wasm)
|
||||||
|
|
||||||
|
package app
|
||||||
|
|
||||||
|
import "kjol/rsc"
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
rsc.Register("ServerCounter", ServerCounter)
|
||||||
|
}
|
||||||
118
go/cmd/examples/go-wasm-web/app/server_counter.go
Normal file
118
go/cmd/examples/go-wasm-web/app/server_counter.go
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
//go:build !(js && wasm)
|
||||||
|
|
||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
chart "github.com/wcharczuk/go-chart/v2"
|
||||||
|
|
||||||
|
. "kjol/vdom"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ServerCounter is a SERVER component — note it's written exactly like a client
|
||||||
|
// 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
|
||||||
|
// round-trip over /rsc.
|
||||||
|
//
|
||||||
|
// The chart plots the counter value against the wall-clock time of each click
|
||||||
|
// (milliseconds since the first click), so spacing clicks out spreads the data
|
||||||
|
// points along the x-axis. Because the component is stateless on the server, the
|
||||||
|
// click points live in a signal that round-trips with the rest of its state
|
||||||
|
// (a plain slice would reset on every request).
|
||||||
|
//
|
||||||
|
//gowasm:server
|
||||||
|
func ServerCounter() func() *VNode {
|
||||||
|
count := NewSignal(0)
|
||||||
|
points := NewSignal([]clickPoint{})
|
||||||
|
bump := func(delta int) {
|
||||||
|
count.Set(count.Get() + delta)
|
||||||
|
points.Set(append(points.Get(), clickPoint{T: time.Now().UnixMilli(), V: count.Get()}))
|
||||||
|
}
|
||||||
|
return func() *VNode {
|
||||||
|
return Div(Attr("class", "card"),
|
||||||
|
Div(Attr("class", "card-body"),
|
||||||
|
Div(Attr("class", "d-flex align-items-center gap-2 mb-2"),
|
||||||
|
Span(Text("Server counter: ")),
|
||||||
|
Strong(Attr("class", "badge text-bg-success fs-6"), Text(strconv.Itoa(count.Get()))),
|
||||||
|
Button(Attr("class", "btn btn-sm btn-outline-secondary"),
|
||||||
|
On(EVENT_CLICK, func() { bump(-1) }), Text("−")),
|
||||||
|
Button(Attr("class", "btn btn-sm btn-success"),
|
||||||
|
On(EVENT_CLICK, func() { bump(1) }), Text("+")),
|
||||||
|
),
|
||||||
|
Div(Attr("class", "border rounded p-2 bg-white overflow-auto"),
|
||||||
|
Raw(clickChartSVG(points.Get()))),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// clickPoint records one click: its wall-clock time and the resulting counter
|
||||||
|
// value. Exported fields so the signal's JSON snapshot round-trips it.
|
||||||
|
type clickPoint struct {
|
||||||
|
T int64 // click time, Unix milliseconds
|
||||||
|
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).
|
||||||
|
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>`
|
||||||
|
}
|
||||||
|
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
|
||||||
|
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]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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()
|
||||||
|
}
|
||||||
24
go/cmd/examples/go-wasm-web/build.sh
Executable file
24
go/cmd/examples/go-wasm-web/build.sh
Executable file
@@ -0,0 +1,24 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Pre-compile step: run the directive codegen, build the Go client to WebAssembly,
|
||||||
|
# and stage the JS shim. Run the dev server instead (go run ./server) for hot
|
||||||
|
# reload; this script is for a one-off/production-style build. Run from anywhere.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
cd "$(dirname "$0")"
|
||||||
|
|
||||||
|
echo "==> Generating directive glue (//gowasm:page, //gowasm:layout, //gowasm:server)"
|
||||||
|
go run kjol/cmd/gowasmgen ./app
|
||||||
|
|
||||||
|
echo "==> Compiling ./wasm to wwwroot/app.wasm (GOOS=js GOARCH=wasm)"
|
||||||
|
GOOS=js GOARCH=wasm go build -o wwwroot/app.wasm ./wasm
|
||||||
|
|
||||||
|
echo "==> Copying Go's wasm_exec.js shim into wwwroot/"
|
||||||
|
GOROOT="$(go env GOROOT)"
|
||||||
|
if [ -f "$GOROOT/lib/wasm/wasm_exec.js" ]; then
|
||||||
|
cp "$GOROOT/lib/wasm/wasm_exec.js" wwwroot/wasm_exec.js # Go >= 1.24
|
||||||
|
else
|
||||||
|
cp "$GOROOT/misc/wasm/wasm_exec.js" wwwroot/wasm_exec.js # Go <= 1.23
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> Done. Run the server with: go run ./server"
|
||||||
|
echo " then open http://localhost:8085"
|
||||||
18
go/cmd/examples/go-wasm-web/go.mod
Normal file
18
go/cmd/examples/go-wasm-web/go.mod
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
// The example is its own module so its go-chart dependency (and freetype /
|
||||||
|
// x/image) stays out of the kjol module — kjol's engine packages are
|
||||||
|
// stdlib-only. kjol is resolved locally via the replace below (no publish step).
|
||||||
|
module gowasmweb
|
||||||
|
|
||||||
|
go 1.26.3
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/wcharczuk/go-chart/v2 v2.1.2
|
||||||
|
kjol v0.0.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
|
||||||
|
golang.org/x/image v0.18.0 // indirect
|
||||||
|
)
|
||||||
|
|
||||||
|
replace kjol => ../../..
|
||||||
66
go/cmd/examples/go-wasm-web/go.sum
Normal file
66
go/cmd/examples/go-wasm-web/go.sum
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
|
||||||
|
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
|
||||||
|
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||||
|
github.com/wcharczuk/go-chart/v2 v2.1.2 h1:Y17/oYNuXwZg6TFag06qe8sBajwwsuvPiJJXcUcLL6E=
|
||||||
|
github.com/wcharczuk/go-chart/v2 v2.1.2/go.mod h1:Zi4hbaqlWpYajnXB2K22IUYVXRXaLfSGNNR7P4ukyyQ=
|
||||||
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
|
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||||
|
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
|
||||||
|
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||||
|
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||||
|
golang.org/x/image v0.18.0 h1:jGzIakQa/ZXI1I0Fxvaa9W7yP25TqT6cHIHn+6CqvSQ=
|
||||||
|
golang.org/x/image v0.18.0/go.mod h1:4yyo5vMFQjVjUcVk4jEQcU9MGy/rulF5WvUILseCM2E=
|
||||||
|
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||||
|
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||||
|
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||||
|
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||||
|
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||||
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
|
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||||
|
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||||
|
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||||
|
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
|
||||||
|
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||||
|
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||||
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
||||||
|
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
|
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
|
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||||
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
|
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||||
|
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||||
|
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
||||||
|
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
|
||||||
|
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||||
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||||
|
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||||
|
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||||
|
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||||
|
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||||
|
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||||
|
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||||
|
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||||
|
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||||
|
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||||
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
BIN
go/cmd/examples/go-wasm-web/server/__debug_bin283327599
Executable file
BIN
go/cmd/examples/go-wasm-web/server/__debug_bin283327599
Executable file
Binary file not shown.
82
go/cmd/examples/go-wasm-web/server/main.go
Normal file
82
go/cmd/examples/go-wasm-web/server/main.go
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
// Command server runs the go-wasm-web example on kjol's reusable wasmdevserver:
|
||||||
|
// it SSRs the app's static routes, hosts the /rsc server-component endpoint, and
|
||||||
|
// hot-swaps the wasm into the browser on change. It shows the coupling
|
||||||
|
// inversion — the framework (wasmdevserver) imports no app code; the app injects
|
||||||
|
// Build/Render/Document here.
|
||||||
|
//
|
||||||
|
// Run it from THIS directory (the relative paths below are resolved against it):
|
||||||
|
//
|
||||||
|
// go run ./server # from cmd/examples/go-wasm-web
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"flag"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"kjol/vdom"
|
||||||
|
"kjol/wasmdevserver"
|
||||||
|
|
||||||
|
"gowasmweb/app"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
addr := flag.String("addr", ":8085", "listen address")
|
||||||
|
watch := flag.Bool("watch", true, "watch sources, rebuild wasm, hot-reload")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
log.Fatal(wasmdevserver.Serve(wasmdevserver.Config{
|
||||||
|
Addr: *addr,
|
||||||
|
Dir: "./wwwroot",
|
||||||
|
Watch: *watch,
|
||||||
|
WatchDirs: []string{"app", "wasm", "../../../vdom", "../../../wasmruntime", "../../../rsc"}, // example + kjol engine
|
||||||
|
Build: buildWasm,
|
||||||
|
Render: render,
|
||||||
|
Document: document,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// render SSRs a static route's #app inner HTML; ok=false ships an empty #app
|
||||||
|
// (client-rendered). It's the same neutral render the client runs, so the client
|
||||||
|
// hydrates it.
|
||||||
|
func render(path string) (string, bool) {
|
||||||
|
if !app.StaticPaths[path] {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
deps := app.Deps{Path: func() string { return path }} // Navigate is nil on the server
|
||||||
|
return vdom.RenderHTML(app.Shell(deps, app.Routes(deps))), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// document wraps the server-rendered inner HTML in the page shell. No whitespace
|
||||||
|
// between <div id="app"> and the markup, so hydration's childNodes line up. The
|
||||||
|
// dev server injects the livereload script before </body> in watch mode.
|
||||||
|
func document(inner string) string {
|
||||||
|
return `<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>gowasm — a tiny Blazor-like engine</title>
|
||||||
|
<link rel="stylesheet" href="/bootstrap.min.css" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app">` + inner + `</div>
|
||||||
|
<script src="/wasm_exec.js"></script>
|
||||||
|
<script src="/bootstrap.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>`
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildWasm runs the directive codegen (kjol/cmd/gowasmgen), then compiles
|
||||||
|
// ./wasm to wwwroot/app.wasm. Returned combined output is shown in the browser
|
||||||
|
// overlay on failure.
|
||||||
|
func buildWasm() ([]byte, error) {
|
||||||
|
if out, err := exec.Command("go", "run", "kjol/cmd/gowasmgen", "./app").CombinedOutput(); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
cmd := exec.Command("go", "build", "-o", filepath.Join("wwwroot", "app.wasm"), "./wasm")
|
||||||
|
cmd.Env = append(os.Environ(), "GOOS=js", "GOARCH=wasm")
|
||||||
|
return cmd.CombinedOutput()
|
||||||
|
}
|
||||||
31
go/cmd/examples/go-wasm-web/wasm/main.go
Normal file
31
go/cmd/examples/go-wasm-web/wasm/main.go
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
//go:build js && wasm
|
||||||
|
|
||||||
|
// Command wasm is the client entry point: it wires client capabilities into the
|
||||||
|
// (generated) routes, then hydrates the server-rendered DOM or renders fresh.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"gowasmweb/app"
|
||||||
|
"kjol/vdom"
|
||||||
|
"kjol/wasmruntime"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Collect the signals created during setup so their values can be preserved
|
||||||
|
// across an in-place hot swap. On a normal load RestoreState is nil (fresh
|
||||||
|
// state); after a dev hot-reload it carries the previous instance's values,
|
||||||
|
// which NewSignal restores by creation order.
|
||||||
|
collector := vdom.BeginCollect(wasmruntime.RestoreState())
|
||||||
|
router := wasmruntime.NewRouter()
|
||||||
|
deps := app.Deps{Path: router.Path, Navigate: router.Navigate}
|
||||||
|
routes := app.Routes(deps)
|
||||||
|
vdom.EndCollect() // signals created later (during renders) aren't preserved
|
||||||
|
wasmruntime.PreserveState(collector)
|
||||||
|
|
||||||
|
render := func() *vdom.VNode { return app.Shell(deps, routes) }
|
||||||
|
if wasmruntime.HasServerContent() {
|
||||||
|
wasmruntime.Hydrate(render) // static route: adopt the server-rendered DOM
|
||||||
|
} else {
|
||||||
|
wasmruntime.Run(render) // client-rendered route
|
||||||
|
}
|
||||||
|
}
|
||||||
9
go/cmd/examples/go-wasm-web/wasm/main_native.go
Normal file
9
go/cmd/examples/go-wasm-web/wasm/main_native.go
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
//go:build !(js && wasm)
|
||||||
|
|
||||||
|
// The wasm client entry point (main.go) builds only under GOOS=js GOARCH=wasm.
|
||||||
|
// This native placeholder keeps the package buildable on the host so a plain
|
||||||
|
// `go build ./...` succeeds; the real client is built by build.sh / the dev
|
||||||
|
// server with GOOS=js GOARCH=wasm.
|
||||||
|
package main
|
||||||
|
|
||||||
|
func main() {}
|
||||||
BIN
go/cmd/examples/go-wasm-web/wwwroot/app.wasm
Executable file
BIN
go/cmd/examples/go-wasm-web/wwwroot/app.wasm
Executable file
Binary file not shown.
24
go/cmd/examples/go-wasm-web/wwwroot/bootstrap.js
vendored
Normal file
24
go/cmd/examples/go-wasm-web/wwwroot/bootstrap.js
vendored
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
// bootstrap.js — boots the Go/Wasm client, and supports flash-free hot swaps.
|
||||||
|
//
|
||||||
|
// On first load the server has already rendered the page's HTML into #app and
|
||||||
|
// the wasm app hydrates it (see wasm/main.go). The dev server's livereload
|
||||||
|
// script hot-swaps a freshly built module WITHOUT a full page reload or a blank
|
||||||
|
// flash: it calls __gowasmPrepare() to fetch + compile the new module while the
|
||||||
|
// current page is still visible, then (in one synchronous step) __gowasmDispose()
|
||||||
|
// to tear down the old instance and start() to run the new one.
|
||||||
|
(function () {
|
||||||
|
// prepare fetches + compiles the module and returns a SYNCHRONOUS start()
|
||||||
|
// thunk. Separating the async work (network + compile) from start (which
|
||||||
|
// renders synchronously) is what lets a swap avoid an intermediate blank #app.
|
||||||
|
async function prepare() {
|
||||||
|
const go = new Go();
|
||||||
|
// cache:no-store so a hot swap always fetches the freshly built bytes.
|
||||||
|
const resp = await fetch("/app.wasm", { cache: "no-store" });
|
||||||
|
const result = await WebAssembly.instantiateStreaming(resp, go.importObject);
|
||||||
|
return function start() { go.run(result.instance); }; // runs main() (renders), then parks on select{}
|
||||||
|
}
|
||||||
|
async function boot() { (await prepare())(); }
|
||||||
|
window.__gowasmPrepare = prepare;
|
||||||
|
window.__gowasmBoot = boot;
|
||||||
|
boot();
|
||||||
|
})();
|
||||||
6
go/cmd/examples/go-wasm-web/wwwroot/bootstrap.min.css
vendored
Normal file
6
go/cmd/examples/go-wasm-web/wwwroot/bootstrap.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
575
go/cmd/examples/go-wasm-web/wwwroot/wasm_exec.js
Normal file
575
go/cmd/examples/go-wasm-web/wwwroot/wasm_exec.js
Normal file
@@ -0,0 +1,575 @@
|
|||||||
|
// Copyright 2018 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
(() => {
|
||||||
|
const enosys = () => {
|
||||||
|
const err = new Error("not implemented");
|
||||||
|
err.code = "ENOSYS";
|
||||||
|
return err;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!globalThis.fs) {
|
||||||
|
let outputBuf = "";
|
||||||
|
globalThis.fs = {
|
||||||
|
constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1, O_DIRECTORY: -1 }, // unused
|
||||||
|
writeSync(fd, buf) {
|
||||||
|
outputBuf += decoder.decode(buf);
|
||||||
|
const nl = outputBuf.lastIndexOf("\n");
|
||||||
|
if (nl != -1) {
|
||||||
|
console.log(outputBuf.substring(0, nl));
|
||||||
|
outputBuf = outputBuf.substring(nl + 1);
|
||||||
|
}
|
||||||
|
return buf.length;
|
||||||
|
},
|
||||||
|
write(fd, buf, offset, length, position, callback) {
|
||||||
|
if (offset !== 0 || length !== buf.length || position !== null) {
|
||||||
|
callback(enosys());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const n = this.writeSync(fd, buf);
|
||||||
|
callback(null, n);
|
||||||
|
},
|
||||||
|
chmod(path, mode, callback) { callback(enosys()); },
|
||||||
|
chown(path, uid, gid, callback) { callback(enosys()); },
|
||||||
|
close(fd, callback) { callback(enosys()); },
|
||||||
|
fchmod(fd, mode, callback) { callback(enosys()); },
|
||||||
|
fchown(fd, uid, gid, callback) { callback(enosys()); },
|
||||||
|
fstat(fd, callback) { callback(enosys()); },
|
||||||
|
fsync(fd, callback) { callback(null); },
|
||||||
|
ftruncate(fd, length, callback) { callback(enosys()); },
|
||||||
|
lchown(path, uid, gid, callback) { callback(enosys()); },
|
||||||
|
link(path, link, callback) { callback(enosys()); },
|
||||||
|
lstat(path, callback) { callback(enosys()); },
|
||||||
|
mkdir(path, perm, callback) { callback(enosys()); },
|
||||||
|
open(path, flags, mode, callback) { callback(enosys()); },
|
||||||
|
read(fd, buffer, offset, length, position, callback) { callback(enosys()); },
|
||||||
|
readdir(path, callback) { callback(enosys()); },
|
||||||
|
readlink(path, callback) { callback(enosys()); },
|
||||||
|
rename(from, to, callback) { callback(enosys()); },
|
||||||
|
rmdir(path, callback) { callback(enosys()); },
|
||||||
|
stat(path, callback) { callback(enosys()); },
|
||||||
|
symlink(path, link, callback) { callback(enosys()); },
|
||||||
|
truncate(path, length, callback) { callback(enosys()); },
|
||||||
|
unlink(path, callback) { callback(enosys()); },
|
||||||
|
utimes(path, atime, mtime, callback) { callback(enosys()); },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!globalThis.process) {
|
||||||
|
globalThis.process = {
|
||||||
|
getuid() { return -1; },
|
||||||
|
getgid() { return -1; },
|
||||||
|
geteuid() { return -1; },
|
||||||
|
getegid() { return -1; },
|
||||||
|
getgroups() { throw enosys(); },
|
||||||
|
pid: -1,
|
||||||
|
ppid: -1,
|
||||||
|
umask() { throw enosys(); },
|
||||||
|
cwd() { throw enosys(); },
|
||||||
|
chdir() { throw enosys(); },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!globalThis.path) {
|
||||||
|
globalThis.path = {
|
||||||
|
resolve(...pathSegments) {
|
||||||
|
return pathSegments.join("/");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!globalThis.crypto) {
|
||||||
|
throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!globalThis.performance) {
|
||||||
|
throw new Error("globalThis.performance is not available, polyfill required (performance.now only)");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!globalThis.TextEncoder) {
|
||||||
|
throw new Error("globalThis.TextEncoder is not available, polyfill required");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!globalThis.TextDecoder) {
|
||||||
|
throw new Error("globalThis.TextDecoder is not available, polyfill required");
|
||||||
|
}
|
||||||
|
|
||||||
|
const encoder = new TextEncoder("utf-8");
|
||||||
|
const decoder = new TextDecoder("utf-8");
|
||||||
|
|
||||||
|
globalThis.Go = class {
|
||||||
|
constructor() {
|
||||||
|
this.argv = ["js"];
|
||||||
|
this.env = {};
|
||||||
|
this.exit = (code) => {
|
||||||
|
if (code !== 0) {
|
||||||
|
console.warn("exit code:", code);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
this._exitPromise = new Promise((resolve) => {
|
||||||
|
this._resolveExitPromise = resolve;
|
||||||
|
});
|
||||||
|
this._pendingEvent = null;
|
||||||
|
this._scheduledTimeouts = new Map();
|
||||||
|
this._nextCallbackTimeoutID = 1;
|
||||||
|
|
||||||
|
const setInt64 = (addr, v) => {
|
||||||
|
this.mem.setUint32(addr + 0, v, true);
|
||||||
|
this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
const setInt32 = (addr, v) => {
|
||||||
|
this.mem.setUint32(addr + 0, v, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
const getInt64 = (addr) => {
|
||||||
|
const low = this.mem.getUint32(addr + 0, true);
|
||||||
|
const high = this.mem.getInt32(addr + 4, true);
|
||||||
|
return low + high * 4294967296;
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadValue = (addr) => {
|
||||||
|
const f = this.mem.getFloat64(addr, true);
|
||||||
|
if (f === 0) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
if (!isNaN(f)) {
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = this.mem.getUint32(addr, true);
|
||||||
|
return this._values[id];
|
||||||
|
}
|
||||||
|
|
||||||
|
const storeValue = (addr, v) => {
|
||||||
|
const nanHead = 0x7FF80000;
|
||||||
|
|
||||||
|
if (typeof v === "number" && v !== 0) {
|
||||||
|
if (isNaN(v)) {
|
||||||
|
this.mem.setUint32(addr + 4, nanHead, true);
|
||||||
|
this.mem.setUint32(addr, 0, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.mem.setFloat64(addr, v, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (v === undefined) {
|
||||||
|
this.mem.setFloat64(addr, 0, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let id = this._ids.get(v);
|
||||||
|
if (id === undefined) {
|
||||||
|
id = this._idPool.pop();
|
||||||
|
if (id === undefined) {
|
||||||
|
id = this._values.length;
|
||||||
|
}
|
||||||
|
this._values[id] = v;
|
||||||
|
this._goRefCounts[id] = 0;
|
||||||
|
this._ids.set(v, id);
|
||||||
|
}
|
||||||
|
this._goRefCounts[id]++;
|
||||||
|
let typeFlag = 0;
|
||||||
|
switch (typeof v) {
|
||||||
|
case "object":
|
||||||
|
if (v !== null) {
|
||||||
|
typeFlag = 1;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "string":
|
||||||
|
typeFlag = 2;
|
||||||
|
break;
|
||||||
|
case "symbol":
|
||||||
|
typeFlag = 3;
|
||||||
|
break;
|
||||||
|
case "function":
|
||||||
|
typeFlag = 4;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
|
||||||
|
this.mem.setUint32(addr, id, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadSlice = (addr) => {
|
||||||
|
const array = getInt64(addr + 0);
|
||||||
|
const len = getInt64(addr + 8);
|
||||||
|
return new Uint8Array(this._inst.exports.mem.buffer, array, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadSliceOfValues = (addr) => {
|
||||||
|
const array = getInt64(addr + 0);
|
||||||
|
const len = getInt64(addr + 8);
|
||||||
|
const a = new Array(len);
|
||||||
|
for (let i = 0; i < len; i++) {
|
||||||
|
a[i] = loadValue(array + i * 8);
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadString = (addr) => {
|
||||||
|
const saddr = getInt64(addr + 0);
|
||||||
|
const len = getInt64(addr + 8);
|
||||||
|
return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
|
||||||
|
}
|
||||||
|
|
||||||
|
const testCallExport = (a, b) => {
|
||||||
|
this._inst.exports.testExport0();
|
||||||
|
return this._inst.exports.testExport(a, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
const timeOrigin = Date.now() - performance.now();
|
||||||
|
this.importObject = {
|
||||||
|
_gotest: {
|
||||||
|
add: (a, b) => a + b,
|
||||||
|
callExport: testCallExport,
|
||||||
|
},
|
||||||
|
gojs: {
|
||||||
|
// Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
|
||||||
|
// may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
|
||||||
|
// function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
|
||||||
|
// This changes the SP, thus we have to update the SP used by the imported function.
|
||||||
|
|
||||||
|
// func wasmExit(code int32)
|
||||||
|
"runtime.wasmExit": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const code = this.mem.getInt32(sp + 8, true);
|
||||||
|
this.exited = true;
|
||||||
|
delete this._inst;
|
||||||
|
delete this._values;
|
||||||
|
delete this._goRefCounts;
|
||||||
|
delete this._ids;
|
||||||
|
delete this._idPool;
|
||||||
|
this.exit(code);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
|
||||||
|
"runtime.wasmWrite": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const fd = getInt64(sp + 8);
|
||||||
|
const p = getInt64(sp + 16);
|
||||||
|
const n = this.mem.getInt32(sp + 24, true);
|
||||||
|
fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func resetMemoryDataView()
|
||||||
|
"runtime.resetMemoryDataView": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
this.mem = new DataView(this._inst.exports.mem.buffer);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func nanotime1() int64
|
||||||
|
"runtime.nanotime1": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func walltime() (sec int64, nsec int32)
|
||||||
|
"runtime.walltime": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const msec = (new Date).getTime();
|
||||||
|
setInt64(sp + 8, msec / 1000);
|
||||||
|
this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func scheduleTimeoutEvent(delay int64) int32
|
||||||
|
"runtime.scheduleTimeoutEvent": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const id = this._nextCallbackTimeoutID;
|
||||||
|
this._nextCallbackTimeoutID++;
|
||||||
|
this._scheduledTimeouts.set(id, setTimeout(
|
||||||
|
() => {
|
||||||
|
this._resume();
|
||||||
|
while (this._scheduledTimeouts.has(id)) {
|
||||||
|
// for some reason Go failed to register the timeout event, log and try again
|
||||||
|
// (temporary workaround for https://github.com/golang/go/issues/28975)
|
||||||
|
console.warn("scheduleTimeoutEvent: missed timeout event");
|
||||||
|
this._resume();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
getInt64(sp + 8),
|
||||||
|
));
|
||||||
|
this.mem.setInt32(sp + 16, id, true);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func clearTimeoutEvent(id int32)
|
||||||
|
"runtime.clearTimeoutEvent": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const id = this.mem.getInt32(sp + 8, true);
|
||||||
|
clearTimeout(this._scheduledTimeouts.get(id));
|
||||||
|
this._scheduledTimeouts.delete(id);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func getRandomData(r []byte)
|
||||||
|
"runtime.getRandomData": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
crypto.getRandomValues(loadSlice(sp + 8));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func finalizeRef(v ref)
|
||||||
|
"syscall/js.finalizeRef": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const id = this.mem.getUint32(sp + 8, true);
|
||||||
|
this._goRefCounts[id]--;
|
||||||
|
if (this._goRefCounts[id] === 0) {
|
||||||
|
const v = this._values[id];
|
||||||
|
this._values[id] = null;
|
||||||
|
this._ids.delete(v);
|
||||||
|
this._idPool.push(id);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// func stringVal(value string) ref
|
||||||
|
"syscall/js.stringVal": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
storeValue(sp + 24, loadString(sp + 8));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueGet(v ref, p string) ref
|
||||||
|
"syscall/js.valueGet": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
|
||||||
|
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||||
|
storeValue(sp + 32, result);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueSet(v ref, p string, x ref)
|
||||||
|
"syscall/js.valueSet": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueDelete(v ref, p string)
|
||||||
|
"syscall/js.valueDelete": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueIndex(v ref, i int) ref
|
||||||
|
"syscall/js.valueIndex": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
|
||||||
|
},
|
||||||
|
|
||||||
|
// valueSetIndex(v ref, i int, x ref)
|
||||||
|
"syscall/js.valueSetIndex": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueCall(v ref, m string, args []ref) (ref, bool)
|
||||||
|
"syscall/js.valueCall": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
try {
|
||||||
|
const v = loadValue(sp + 8);
|
||||||
|
const m = Reflect.get(v, loadString(sp + 16));
|
||||||
|
const args = loadSliceOfValues(sp + 32);
|
||||||
|
const result = Reflect.apply(m, v, args);
|
||||||
|
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||||
|
storeValue(sp + 56, result);
|
||||||
|
this.mem.setUint8(sp + 64, 1);
|
||||||
|
} catch (err) {
|
||||||
|
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||||
|
storeValue(sp + 56, err);
|
||||||
|
this.mem.setUint8(sp + 64, 0);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueInvoke(v ref, args []ref) (ref, bool)
|
||||||
|
"syscall/js.valueInvoke": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
try {
|
||||||
|
const v = loadValue(sp + 8);
|
||||||
|
const args = loadSliceOfValues(sp + 16);
|
||||||
|
const result = Reflect.apply(v, undefined, args);
|
||||||
|
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||||
|
storeValue(sp + 40, result);
|
||||||
|
this.mem.setUint8(sp + 48, 1);
|
||||||
|
} catch (err) {
|
||||||
|
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||||
|
storeValue(sp + 40, err);
|
||||||
|
this.mem.setUint8(sp + 48, 0);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueNew(v ref, args []ref) (ref, bool)
|
||||||
|
"syscall/js.valueNew": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
try {
|
||||||
|
const v = loadValue(sp + 8);
|
||||||
|
const args = loadSliceOfValues(sp + 16);
|
||||||
|
const result = Reflect.construct(v, args);
|
||||||
|
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||||
|
storeValue(sp + 40, result);
|
||||||
|
this.mem.setUint8(sp + 48, 1);
|
||||||
|
} catch (err) {
|
||||||
|
sp = this._inst.exports.getsp() >>> 0; // see comment above
|
||||||
|
storeValue(sp + 40, err);
|
||||||
|
this.mem.setUint8(sp + 48, 0);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueLength(v ref) int
|
||||||
|
"syscall/js.valueLength": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
|
||||||
|
},
|
||||||
|
|
||||||
|
// valuePrepareString(v ref) (ref, int)
|
||||||
|
"syscall/js.valuePrepareString": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const str = encoder.encode(String(loadValue(sp + 8)));
|
||||||
|
storeValue(sp + 16, str);
|
||||||
|
setInt64(sp + 24, str.length);
|
||||||
|
},
|
||||||
|
|
||||||
|
// valueLoadString(v ref, b []byte)
|
||||||
|
"syscall/js.valueLoadString": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const str = loadValue(sp + 8);
|
||||||
|
loadSlice(sp + 16).set(str);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func valueInstanceOf(v ref, t ref) bool
|
||||||
|
"syscall/js.valueInstanceOf": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func copyBytesToGo(dst []byte, src ref) (int, bool)
|
||||||
|
"syscall/js.copyBytesToGo": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const dst = loadSlice(sp + 8);
|
||||||
|
const src = loadValue(sp + 32);
|
||||||
|
if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
|
||||||
|
this.mem.setUint8(sp + 48, 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const toCopy = src.subarray(0, dst.length);
|
||||||
|
dst.set(toCopy);
|
||||||
|
setInt64(sp + 40, toCopy.length);
|
||||||
|
this.mem.setUint8(sp + 48, 1);
|
||||||
|
},
|
||||||
|
|
||||||
|
// func copyBytesToJS(dst ref, src []byte) (int, bool)
|
||||||
|
"syscall/js.copyBytesToJS": (sp) => {
|
||||||
|
sp >>>= 0;
|
||||||
|
const dst = loadValue(sp + 8);
|
||||||
|
const src = loadSlice(sp + 16);
|
||||||
|
if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
|
||||||
|
this.mem.setUint8(sp + 48, 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const toCopy = src.subarray(0, dst.length);
|
||||||
|
dst.set(toCopy);
|
||||||
|
setInt64(sp + 40, toCopy.length);
|
||||||
|
this.mem.setUint8(sp + 48, 1);
|
||||||
|
},
|
||||||
|
|
||||||
|
"debug": (value) => {
|
||||||
|
console.log(value);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async run(instance) {
|
||||||
|
if (!(instance instanceof WebAssembly.Instance)) {
|
||||||
|
throw new Error("Go.run: WebAssembly.Instance expected");
|
||||||
|
}
|
||||||
|
this._inst = instance;
|
||||||
|
this.mem = new DataView(this._inst.exports.mem.buffer);
|
||||||
|
this._values = [ // JS values that Go currently has references to, indexed by reference id
|
||||||
|
NaN,
|
||||||
|
0,
|
||||||
|
null,
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
globalThis,
|
||||||
|
this,
|
||||||
|
];
|
||||||
|
this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id
|
||||||
|
this._ids = new Map([ // mapping from JS values to reference ids
|
||||||
|
[0, 1],
|
||||||
|
[null, 2],
|
||||||
|
[true, 3],
|
||||||
|
[false, 4],
|
||||||
|
[globalThis, 5],
|
||||||
|
[this, 6],
|
||||||
|
]);
|
||||||
|
this._idPool = []; // unused ids that have been garbage collected
|
||||||
|
this.exited = false; // whether the Go program has exited
|
||||||
|
|
||||||
|
// Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory.
|
||||||
|
let offset = 4096;
|
||||||
|
|
||||||
|
const strPtr = (str) => {
|
||||||
|
const ptr = offset;
|
||||||
|
const bytes = encoder.encode(str + "\0");
|
||||||
|
new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
|
||||||
|
offset += bytes.length;
|
||||||
|
if (offset % 8 !== 0) {
|
||||||
|
offset += 8 - (offset % 8);
|
||||||
|
}
|
||||||
|
return ptr;
|
||||||
|
};
|
||||||
|
|
||||||
|
const argc = this.argv.length;
|
||||||
|
|
||||||
|
const argvPtrs = [];
|
||||||
|
this.argv.forEach((arg) => {
|
||||||
|
argvPtrs.push(strPtr(arg));
|
||||||
|
});
|
||||||
|
argvPtrs.push(0);
|
||||||
|
|
||||||
|
const keys = Object.keys(this.env).sort();
|
||||||
|
keys.forEach((key) => {
|
||||||
|
argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
|
||||||
|
});
|
||||||
|
argvPtrs.push(0);
|
||||||
|
|
||||||
|
const argv = offset;
|
||||||
|
argvPtrs.forEach((ptr) => {
|
||||||
|
this.mem.setUint32(offset, ptr, true);
|
||||||
|
this.mem.setUint32(offset + 4, 0, true);
|
||||||
|
offset += 8;
|
||||||
|
});
|
||||||
|
|
||||||
|
// The linker guarantees global data starts from at least wasmMinDataAddr.
|
||||||
|
// Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr.
|
||||||
|
const wasmMinDataAddr = 4096 + 8192;
|
||||||
|
if (offset >= wasmMinDataAddr) {
|
||||||
|
throw new Error("total length of command line and environment variables exceeds limit");
|
||||||
|
}
|
||||||
|
|
||||||
|
this._inst.exports.run(argc, argv);
|
||||||
|
if (this.exited) {
|
||||||
|
this._resolveExitPromise();
|
||||||
|
}
|
||||||
|
await this._exitPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
_resume() {
|
||||||
|
if (this.exited) {
|
||||||
|
throw new Error("Go program has already exited");
|
||||||
|
}
|
||||||
|
this._inst.exports.resume();
|
||||||
|
if (this.exited) {
|
||||||
|
this._resolveExitPromise();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_makeFuncWrapper(id) {
|
||||||
|
const go = this;
|
||||||
|
return function () {
|
||||||
|
const event = { id: id, this: this, args: arguments };
|
||||||
|
go._pendingEvent = event;
|
||||||
|
go._resume();
|
||||||
|
return event.result;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})();
|
||||||
214
go/cmd/gowasmgen/main.go
Normal file
214
go/cmd/gowasmgen/main.go
Normal file
@@ -0,0 +1,214 @@
|
|||||||
|
// Command gowasmgen preprocesses component directives into glue code so that
|
||||||
|
// server-component calls look identical to client-component calls, and routes
|
||||||
|
// can opt into SSR with a tag.
|
||||||
|
//
|
||||||
|
// Directives (as doc comments on functions in the target package):
|
||||||
|
//
|
||||||
|
// //gowasm:page <path> [static] [layout=<name>]
|
||||||
|
// a page factory `func(Deps) func() *vdom.VNode`.
|
||||||
|
// `static` => the server SSRs that route;
|
||||||
|
// `layout=` => wrap it in a named //gowasm:layout.
|
||||||
|
// //gowasm:layout <name> a layout `func(Deps, *vdom.VNode) *vdom.VNode`.
|
||||||
|
// //gowasm:server a server component `func() func() *vdom.VNode`.
|
||||||
|
//
|
||||||
|
// It emits three files in the package:
|
||||||
|
// - routes.gen.go (neutral) Routes(Deps) + StaticPaths + RouteLayout/LayoutFor
|
||||||
|
// - server.gen.go (native) init() registering each server component
|
||||||
|
// - client.gen.go (wasm) a client stub per server component that
|
||||||
|
// mounts it over /rsc
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"go/ast"
|
||||||
|
"go/format"
|
||||||
|
"go/parser"
|
||||||
|
"go/token"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"text/template"
|
||||||
|
)
|
||||||
|
|
||||||
|
type page struct {
|
||||||
|
Func string
|
||||||
|
Path string
|
||||||
|
Static bool
|
||||||
|
Layout string // name of the //gowasm:layout wrapper (empty => default)
|
||||||
|
}
|
||||||
|
|
||||||
|
type layoutDecl struct {
|
||||||
|
Name string
|
||||||
|
Func string
|
||||||
|
}
|
||||||
|
|
||||||
|
type genData struct {
|
||||||
|
Pages []page
|
||||||
|
Servers []string
|
||||||
|
Layouts []layoutDecl
|
||||||
|
DefaultLayout string // func name used when a page declares no layout
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
dir := "app"
|
||||||
|
if len(os.Args) > 1 {
|
||||||
|
dir = os.Args[1]
|
||||||
|
}
|
||||||
|
|
||||||
|
fset := token.NewFileSet()
|
||||||
|
pkgs, err := parser.ParseDir(fset, dir, func(fi os.FileInfo) bool {
|
||||||
|
return !strings.HasSuffix(fi.Name(), ".gen.go")
|
||||||
|
}, parser.ParseComments)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "gowasmgen: parse:", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
var data genData
|
||||||
|
for _, pkg := range pkgs {
|
||||||
|
for _, file := range pkg.Files {
|
||||||
|
for _, decl := range file.Decls {
|
||||||
|
fn, ok := decl.(*ast.FuncDecl)
|
||||||
|
if !ok || fn.Doc == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, c := range fn.Doc.List {
|
||||||
|
line := strings.TrimSpace(strings.TrimPrefix(c.Text, "//"))
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(line, "gowasm:page "):
|
||||||
|
fields := strings.Fields(line[len("gowasm:page "):])
|
||||||
|
if len(fields) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
p := page{Func: fn.Name.Name, Path: fields[0]}
|
||||||
|
for _, f := range fields[1:] {
|
||||||
|
switch {
|
||||||
|
case f == "static":
|
||||||
|
p.Static = true
|
||||||
|
case strings.HasPrefix(f, "layout="):
|
||||||
|
p.Layout = strings.TrimPrefix(f, "layout=")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data.Pages = append(data.Pages, p)
|
||||||
|
case strings.HasPrefix(line, "gowasm:layout "):
|
||||||
|
fields := strings.Fields(line[len("gowasm:layout "):])
|
||||||
|
if len(fields) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
data.Layouts = append(data.Layouts, layoutDecl{Name: fields[0], Func: fn.Name.Name})
|
||||||
|
case line == "gowasm:server":
|
||||||
|
data.Servers = append(data.Servers, fn.Name.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Slice(data.Pages, func(i, j int) bool { return data.Pages[i].Path < data.Pages[j].Path })
|
||||||
|
sort.Strings(data.Servers)
|
||||||
|
sort.Slice(data.Layouts, func(i, j int) bool { return data.Layouts[i].Name < data.Layouts[j].Name })
|
||||||
|
|
||||||
|
// Default layout: prefer one literally named "app", else the first declared.
|
||||||
|
var defaultName string
|
||||||
|
if len(data.Layouts) > 0 {
|
||||||
|
data.DefaultLayout, defaultName = data.Layouts[0].Func, data.Layouts[0].Name
|
||||||
|
for _, l := range data.Layouts {
|
||||||
|
if l.Name == "app" {
|
||||||
|
data.DefaultLayout, defaultName = l.Func, l.Name
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := range data.Pages {
|
||||||
|
if data.Pages[i].Layout == "" {
|
||||||
|
data.Pages[i].Layout = defaultName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
write(filepath.Join(dir, "routes.gen.go"), routesTmpl, data)
|
||||||
|
write(filepath.Join(dir, "server.gen.go"), serverTmpl, data)
|
||||||
|
write(filepath.Join(dir, "client.gen.go"), clientTmpl, data)
|
||||||
|
|
||||||
|
fmt.Printf("gowasmgen: %d page(s), %d server component(s)\n", len(data.Pages), len(data.Servers))
|
||||||
|
}
|
||||||
|
|
||||||
|
func write(path, tmpl string, data genData) {
|
||||||
|
var b strings.Builder
|
||||||
|
if err := template.Must(template.New("g").Parse(tmpl)).Execute(&b, data); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
src, err := format.Source([]byte(b.String()))
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "gowasmgen: format %s: %v\n---\n%s\n", path, err, b.String())
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
// Only write when changed, so re-running codegen doesn't churn mtimes (which
|
||||||
|
// would make the dev server's file watcher loop).
|
||||||
|
if existing, err := os.ReadFile(path); err == nil && string(existing) == string(src) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, src, 0o644); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const routesTmpl = `// Code generated by gowasmgen. DO NOT EDIT.
|
||||||
|
package app
|
||||||
|
|
||||||
|
import "kjol/vdom"
|
||||||
|
|
||||||
|
// Routes maps each //gowasm:page path to its instantiated render function.
|
||||||
|
func Routes(d Deps) map[string]func() *vdom.VNode {
|
||||||
|
return map[string]func() *vdom.VNode{
|
||||||
|
{{range .Pages}} "{{.Path}}": {{.Func}}(d),
|
||||||
|
{{end}} }
|
||||||
|
}
|
||||||
|
|
||||||
|
// StaticPaths are the routes the server pre-renders (SSR); others render client-side.
|
||||||
|
var StaticPaths = map[string]bool{
|
||||||
|
{{range .Pages}}{{if .Static}} "{{.Path}}": true,
|
||||||
|
{{end}}{{end}}}
|
||||||
|
|
||||||
|
// RouteLayout maps each route to the name of the layout that wraps it.
|
||||||
|
var RouteLayout = map[string]string{
|
||||||
|
{{range .Pages}} "{{.Path}}": "{{.Layout}}",
|
||||||
|
{{end}}}
|
||||||
|
|
||||||
|
// LayoutFor wraps a page's content in the layout declared for its route.
|
||||||
|
func LayoutFor(d Deps, path string, content *vdom.VNode) *vdom.VNode {
|
||||||
|
{{if .Layouts}} switch RouteLayout[path] {
|
||||||
|
{{range .Layouts}} case "{{.Name}}":
|
||||||
|
return {{.Func}}(d, content)
|
||||||
|
{{end}} }
|
||||||
|
return {{.DefaultLayout}}(d, content)
|
||||||
|
{{else}} return content
|
||||||
|
{{end}}}
|
||||||
|
`
|
||||||
|
|
||||||
|
const serverTmpl = `// Code generated by gowasmgen. DO NOT EDIT.
|
||||||
|
|
||||||
|
//go:build !(js && wasm)
|
||||||
|
|
||||||
|
package app
|
||||||
|
|
||||||
|
import "kjol/rsc"
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
{{range .Servers}} rsc.Register("{{.}}", {{.}})
|
||||||
|
{{end}}}
|
||||||
|
`
|
||||||
|
|
||||||
|
const clientTmpl = `// Code generated by gowasmgen. DO NOT EDIT.
|
||||||
|
|
||||||
|
//go:build js && wasm
|
||||||
|
|
||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"kjol/rsc"
|
||||||
|
"kjol/vdom"
|
||||||
|
)
|
||||||
|
|
||||||
|
{{range .Servers}}// {{.}} is a generated client stub for the server component of the same name.
|
||||||
|
func {{.}}() func() *vdom.VNode { return rsc.Mount("{{.}}") }
|
||||||
|
{{end}}`
|
||||||
93
go/rsc/client_wasm.go
Normal file
93
go/rsc/client_wasm.go
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
//go:build js && wasm
|
||||||
|
|
||||||
|
package rsc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/gob"
|
||||||
|
"syscall/js"
|
||||||
|
|
||||||
|
"kjol/vdom"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Mount connects to a server component by name and returns a render function.
|
||||||
|
// The generated client stub for a //gowasm:server component just calls this, so
|
||||||
|
// the call site is identical to a client component. It POSTs {name, state,
|
||||||
|
// event} to /rsc and swaps (reconciles) the returned render into the DOM. State
|
||||||
|
// is opaque and round-trips through the client — the server keeps nothing.
|
||||||
|
func Mount(name string) func() *vdom.VNode {
|
||||||
|
tree := vdom.NewSignal[*vdom.VNode](nil)
|
||||||
|
var state [][]byte
|
||||||
|
var post func(kind string, nodeID int, event, value string)
|
||||||
|
|
||||||
|
var convert func(*SNode) *vdom.VNode
|
||||||
|
convert = func(sn *SNode) *vdom.VNode {
|
||||||
|
if sn == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if sn.Tag == "" {
|
||||||
|
return vdom.Text(sn.Text)
|
||||||
|
}
|
||||||
|
mods := make([]vdom.Mod, 0, len(sn.Attrs)+len(sn.Events)+len(sn.Kids)+1)
|
||||||
|
for k, v := range sn.Attrs {
|
||||||
|
mods = append(mods, vdom.Attr(k, v))
|
||||||
|
}
|
||||||
|
if sn.HTML != "" {
|
||||||
|
mods = append(mods, vdom.Raw(sn.HTML))
|
||||||
|
}
|
||||||
|
for _, ev := range sn.Events {
|
||||||
|
event, id := ev, sn.ID
|
||||||
|
mods = append(mods, vdom.OnEvent(ev, func(e vdom.Event) { post("event", id, event, e.Value()) }))
|
||||||
|
}
|
||||||
|
for _, k := range sn.Kids {
|
||||||
|
if c := convert(k); c != nil {
|
||||||
|
mods = append(mods, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return vdom.El(sn.Tag, mods...)
|
||||||
|
}
|
||||||
|
|
||||||
|
onArr := js.FuncOf(func(this js.Value, args []js.Value) any {
|
||||||
|
arr := js.Global().Get("Uint8Array").New(args[0])
|
||||||
|
b := make([]byte, arr.Get("length").Int())
|
||||||
|
js.CopyBytesToGo(b, arr)
|
||||||
|
var resp Response
|
||||||
|
if gob.NewDecoder(bytes.NewReader(b)).Decode(&resp) == nil {
|
||||||
|
state = resp.State
|
||||||
|
tree.Set(convert(resp.Tree)) // re-render -> reconcile into the DOM
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
onResp := js.FuncOf(func(this js.Value, args []js.Value) any {
|
||||||
|
args[0].Call("arrayBuffer").Call("then", onArr)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
loc := js.Global().Get("location")
|
||||||
|
url := loc.Get("protocol").String() + "//" + loc.Get("host").String() + "/rsc"
|
||||||
|
|
||||||
|
post = func(kind string, nodeID int, event, value string) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if gob.NewEncoder(&buf).Encode(Request{Kind: kind, Name: name, State: state, NodeID: nodeID, Event: event, Value: value}) != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
body := js.Global().Get("Uint8Array").New(buf.Len())
|
||||||
|
js.CopyBytesToJS(body, buf.Bytes())
|
||||||
|
opts := js.Global().Get("Object").New()
|
||||||
|
opts.Set("method", "POST")
|
||||||
|
opts.Set("body", body)
|
||||||
|
js.Global().Call("fetch", url, opts).Call("then", onResp)
|
||||||
|
}
|
||||||
|
|
||||||
|
started := false
|
||||||
|
return func() *vdom.VNode {
|
||||||
|
if !started {
|
||||||
|
started = true
|
||||||
|
post("mount", 0, "", "")
|
||||||
|
}
|
||||||
|
if t := tree.Get(); t != nil {
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
return vdom.Div(vdom.Attr("class", "text-muted"), vdom.Text("loading server component…"))
|
||||||
|
}
|
||||||
|
}
|
||||||
38
go/rsc/proto.go
Normal file
38
go/rsc/proto.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
// Package rsc runs server components with a stateless, React/Next-style
|
||||||
|
// request/response: the client POSTs the component name, its (opaque) signal
|
||||||
|
// state, and any triggered event; the server restores the state, applies the
|
||||||
|
// event, re-renders, and returns the new state + rendered tree, which the client
|
||||||
|
// reconciles ("swaps") into the DOM. No persistent connection, no server-held
|
||||||
|
// session — state round-trips through the client.
|
||||||
|
//
|
||||||
|
// This file holds the wire types (gob), shared by server and client.
|
||||||
|
package rsc
|
||||||
|
|
||||||
|
// SNode is a serialized render node. Nodes with server handlers carry an ID and
|
||||||
|
// their event names; the client sends {name, state, ID, event} back so the
|
||||||
|
// server can find and invoke the handler.
|
||||||
|
type SNode struct {
|
||||||
|
ID int
|
||||||
|
Tag string
|
||||||
|
Text string
|
||||||
|
HTML string
|
||||||
|
Attrs map[string]string
|
||||||
|
Events []string
|
||||||
|
Kids []*SNode
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request is client -> server (every request is self-contained).
|
||||||
|
type Request struct {
|
||||||
|
Kind string // "mount" | "event"
|
||||||
|
Name string // component name
|
||||||
|
State [][]byte // opaque signal snapshot from the previous response
|
||||||
|
NodeID int // event: node that fired
|
||||||
|
Event string // event: event name
|
||||||
|
Value string // event: target value (inputs)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Response is server -> client.
|
||||||
|
type Response struct {
|
||||||
|
State [][]byte
|
||||||
|
Tree *SNode
|
||||||
|
}
|
||||||
95
go/rsc/server.go
Normal file
95
go/rsc/server.go
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
//go:build !(js && wasm)
|
||||||
|
|
||||||
|
package rsc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/gob"
|
||||||
|
"net/http"
|
||||||
|
"sort"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"kjol/vdom"
|
||||||
|
)
|
||||||
|
|
||||||
|
// registry maps a server-component name to its factory (created by generated
|
||||||
|
// code — one Register per //gowasm:server component). The factory builds the
|
||||||
|
// component's signals + render closure; here it's re-run per request (stateless).
|
||||||
|
var registry = map[string]func() func() *vdom.VNode{}
|
||||||
|
|
||||||
|
func Register(name string, factory func() func() *vdom.VNode) { registry[name] = factory }
|
||||||
|
|
||||||
|
// renderMu serializes server renders because the vdom signal Collector is a
|
||||||
|
// process-global (see vdom.BeginCollect). Fine for this scale.
|
||||||
|
var renderMu sync.Mutex
|
||||||
|
|
||||||
|
// Handler is the single /rsc endpoint. It restores the component's signals from
|
||||||
|
// the request, applies the event (if any), re-renders, and returns the new
|
||||||
|
// signal snapshot + tree.
|
||||||
|
func Handler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req Request
|
||||||
|
if gob.NewDecoder(r.Body).Decode(&req) != nil {
|
||||||
|
http.Error(w, "bad request", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
factory := registry[req.Name]
|
||||||
|
if factory == nil {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
renderMu.Lock()
|
||||||
|
c := vdom.BeginCollect(req.State) // restore prior signal values (nil on mount)
|
||||||
|
render := factory() // signals created + restored here
|
||||||
|
vdom.EndCollect()
|
||||||
|
|
||||||
|
if req.Kind == "event" {
|
||||||
|
// Reproduce the tree the client currently shows (same state) to find the
|
||||||
|
// handler by node id, then invoke it (mutating signals).
|
||||||
|
_, handlers := renderIDs(render())
|
||||||
|
if hm := handlers[req.NodeID]; hm != nil {
|
||||||
|
if h := hm[req.Event]; h != nil {
|
||||||
|
h(serverEvent{value: req.Value})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tree, _ := renderIDs(render()) // render the result (reflects the mutation)
|
||||||
|
resp := Response{State: c.Snapshot(), Tree: tree}
|
||||||
|
renderMu.Unlock()
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/octet-stream")
|
||||||
|
_ = gob.NewEncoder(w).Encode(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
// renderIDs serializes a VNode tree to SNode, assigning a stable (traversal
|
||||||
|
// order) id to each node with handlers and building the handler table.
|
||||||
|
func renderIDs(root *vdom.VNode) (*SNode, map[int]map[string]func(vdom.Event)) {
|
||||||
|
handlers := map[int]map[string]func(vdom.Event){}
|
||||||
|
id := 0
|
||||||
|
var walk func(*vdom.VNode) *SNode
|
||||||
|
walk = func(v *vdom.VNode) *SNode {
|
||||||
|
sn := &SNode{Tag: v.Tag, Text: v.Text, HTML: v.HTML, Attrs: v.Attrs}
|
||||||
|
if len(v.Events) > 0 {
|
||||||
|
id++
|
||||||
|
sn.ID = id
|
||||||
|
hm := map[string]func(vdom.Event){}
|
||||||
|
for ev, h := range v.Events {
|
||||||
|
sn.Events = append(sn.Events, ev)
|
||||||
|
hm[ev] = h
|
||||||
|
}
|
||||||
|
sort.Strings(sn.Events)
|
||||||
|
handlers[id] = hm
|
||||||
|
}
|
||||||
|
if v.HTML == "" {
|
||||||
|
for _, k := range v.Children {
|
||||||
|
sn.Kids = append(sn.Kids, walk(k))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sn
|
||||||
|
}
|
||||||
|
return walk(root), handlers
|
||||||
|
}
|
||||||
|
|
||||||
|
type serverEvent struct{ value string }
|
||||||
|
|
||||||
|
func (e serverEvent) PreventDefault() {}
|
||||||
|
func (e serverEvent) Value() string { return e.value }
|
||||||
17
go/vdom/events.go
Normal file
17
go/vdom/events.go
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
package vdom
|
||||||
|
|
||||||
|
// DOM event-name constants for On / OnEvent.
|
||||||
|
const (
|
||||||
|
EVENT_CLICK = "click"
|
||||||
|
EVENT_DBLCLICK = "dblclick"
|
||||||
|
EVENT_INPUT = "input"
|
||||||
|
EVENT_CHANGE = "change"
|
||||||
|
EVENT_SUBMIT = "submit"
|
||||||
|
EVENT_KEYDOWN = "keydown"
|
||||||
|
EVENT_KEYUP = "keyup"
|
||||||
|
EVENT_FOCUS = "focus"
|
||||||
|
EVENT_BLUR = "blur"
|
||||||
|
EVENT_MOUSEDOWN = "mousedown"
|
||||||
|
EVENT_MOUSEUP = "mouseup"
|
||||||
|
EVENT_MOUSEMOVE = "mousemove"
|
||||||
|
)
|
||||||
7
go/vdom/mode_native.go
Normal file
7
go/vdom/mode_native.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
//go:build !(js && wasm)
|
||||||
|
|
||||||
|
package vdom
|
||||||
|
|
||||||
|
// IsClient is false on the server (native). Components use it to guard
|
||||||
|
// client-only effects (e.g. fetching) so they don't run during SSR.
|
||||||
|
const IsClient = false
|
||||||
6
go/vdom/mode_wasm.go
Normal file
6
go/vdom/mode_wasm.go
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
//go:build js && wasm
|
||||||
|
|
||||||
|
package vdom
|
||||||
|
|
||||||
|
// IsClient is true in the browser (wasm).
|
||||||
|
const IsClient = true
|
||||||
81
go/vdom/signal.go
Normal file
81
go/vdom/signal.go
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
package vdom
|
||||||
|
|
||||||
|
import "encoding/json"
|
||||||
|
|
||||||
|
// Schedule is installed by the wasm runtime at startup; a signal write
|
||||||
|
// triggers a re-render. On the server it is nil (renders are one-shot).
|
||||||
|
var Schedule func()
|
||||||
|
|
||||||
|
// Signal holds state. On the client, writing it schedules a re-render.
|
||||||
|
type Signal[T any] struct{ v T }
|
||||||
|
|
||||||
|
func NewSignal[T any](initial T) *Signal[T] {
|
||||||
|
s := &Signal[T]{v: initial}
|
||||||
|
if active != nil {
|
||||||
|
active.adopt(s) // server component round-trip: restore prior value, track for snapshot
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Signal[T]) Get() T { return s.v }
|
||||||
|
|
||||||
|
func (s *Signal[T]) Set(v T) {
|
||||||
|
s.v = v
|
||||||
|
if Schedule != nil {
|
||||||
|
Schedule()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Signal[T]) Update(fn func(T) T) { s.Set(fn(s.v)) }
|
||||||
|
|
||||||
|
func (s *Signal[T]) snapshot() []byte { b, _ := json.Marshal(s.v); return b }
|
||||||
|
func (s *Signal[T]) restoreFrom(b []byte) { _ = json.Unmarshal(b, &s.v) }
|
||||||
|
|
||||||
|
// ---- signal-state round-trip for server components ----
|
||||||
|
//
|
||||||
|
// A server component is stateless on the server: its signal values are
|
||||||
|
// serialized and round-tripped through the client. While a Collector is active
|
||||||
|
// (during a server-component render on the server), NewSignal restores each
|
||||||
|
// signal's value from the incoming snapshot by creation order (hook-order), and
|
||||||
|
// remembers it so the new values can be snapshotted back out.
|
||||||
|
|
||||||
|
type signalState interface {
|
||||||
|
snapshot() []byte
|
||||||
|
restoreFrom([]byte)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collector captures the signals created during a server render.
|
||||||
|
type Collector struct {
|
||||||
|
restore [][]byte
|
||||||
|
idx int
|
||||||
|
sigs []signalState
|
||||||
|
}
|
||||||
|
|
||||||
|
var active *Collector
|
||||||
|
|
||||||
|
func (c *Collector) adopt(s signalState) {
|
||||||
|
if c.idx < len(c.restore) {
|
||||||
|
s.restoreFrom(c.restore[c.idx])
|
||||||
|
}
|
||||||
|
c.idx++
|
||||||
|
c.sigs = append(c.sigs, s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// BeginCollect starts collecting signals, restoring them from `restore` (which
|
||||||
|
// may be nil for an initial mount). Call EndCollect when construction is done.
|
||||||
|
func BeginCollect(restore [][]byte) *Collector {
|
||||||
|
active = &Collector{restore: restore}
|
||||||
|
return active
|
||||||
|
}
|
||||||
|
|
||||||
|
// EndCollect stops collecting (rendering/handlers may still read the signals).
|
||||||
|
func EndCollect() { active = nil }
|
||||||
|
|
||||||
|
// Snapshot returns the current values of the collected signals, in order.
|
||||||
|
func (c *Collector) Snapshot() [][]byte {
|
||||||
|
out := make([][]byte, len(c.sigs))
|
||||||
|
for i, s := range c.sigs {
|
||||||
|
out[i] = s.snapshot()
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
30
go/vdom/tags.go
Normal file
30
go/vdom/tags.go
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
package vdom
|
||||||
|
|
||||||
|
// HTML tag helpers over El, for dot-import.
|
||||||
|
func Div(m ...Mod) *VNode { return El("div", m...) }
|
||||||
|
func Span(m ...Mod) *VNode { return El("span", m...) }
|
||||||
|
func P(m ...Mod) *VNode { return El("p", m...) }
|
||||||
|
func Section(m ...Mod) *VNode { return El("section", m...) }
|
||||||
|
func Nav(m ...Mod) *VNode { return El("nav", m...) }
|
||||||
|
func Header(m ...Mod) *VNode { return El("header", m...) }
|
||||||
|
func Main(m ...Mod) *VNode { return El("main", m...) }
|
||||||
|
func Footer(m ...Mod) *VNode { return El("footer", m...) }
|
||||||
|
func H1(m ...Mod) *VNode { return El("h1", m...) }
|
||||||
|
func H2(m ...Mod) *VNode { return El("h2", m...) }
|
||||||
|
func H3(m ...Mod) *VNode { return El("h3", m...) }
|
||||||
|
func Hr(m ...Mod) *VNode { return El("hr", m...) }
|
||||||
|
func A(m ...Mod) *VNode { return El("a", m...) }
|
||||||
|
func Strong(m ...Mod) *VNode { return El("strong", m...) }
|
||||||
|
func Em(m ...Mod) *VNode { return El("em", m...) }
|
||||||
|
func Small(m ...Mod) *VNode { return El("small", m...) }
|
||||||
|
func Code(m ...Mod) *VNode { return El("code", m...) }
|
||||||
|
func Label(m ...Mod) *VNode { return El("label", m...) }
|
||||||
|
func Ul(m ...Mod) *VNode { return El("ul", m...) }
|
||||||
|
func Li(m ...Mod) *VNode { return El("li", m...) }
|
||||||
|
func Form(m ...Mod) *VNode { return El("form", m...) }
|
||||||
|
func Input(m ...Mod) *VNode { return El("input", m...) }
|
||||||
|
func Button(m ...Mod) *VNode { return El("button", m...) }
|
||||||
|
func Table(m ...Mod) *VNode { return El("table", m...) }
|
||||||
|
func Tr(m ...Mod) *VNode { return El("tr", m...) }
|
||||||
|
func Td(m ...Mod) *VNode { return El("td", m...) }
|
||||||
|
func Img(m ...Mod) *VNode { return El("img", m...) }
|
||||||
138
go/vdom/vnode.go
Normal file
138
go/vdom/vnode.go
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
// Package vdom is a platform-neutral virtual DOM shared by the server (renders
|
||||||
|
// to an HTML string) and the client (reconciles into the real DOM). It compiles
|
||||||
|
// on BOTH native and js/wasm, so the same component code runs in both places —
|
||||||
|
// which is what makes server-side rendering + client hydration possible.
|
||||||
|
package vdom
|
||||||
|
|
||||||
|
import (
|
||||||
|
"html"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Event is a DOM event passed to handlers. The client provides a concrete
|
||||||
|
// implementation; on the server events are never invoked.
|
||||||
|
type Event interface {
|
||||||
|
PreventDefault()
|
||||||
|
Value() string // target.value (for inputs)
|
||||||
|
}
|
||||||
|
|
||||||
|
// VNode is a virtual DOM node. Tag == "" is a text node (content in Text). HTML,
|
||||||
|
// if set on an element, is raw innerHTML (children ignored).
|
||||||
|
type VNode struct {
|
||||||
|
Tag string
|
||||||
|
Text string
|
||||||
|
HTML string
|
||||||
|
Attrs map[string]string
|
||||||
|
Props map[string]string
|
||||||
|
Events map[string]func(Event)
|
||||||
|
Children []*VNode
|
||||||
|
|
||||||
|
// Runtime holds the wasm reconciler's per-node bookkeeping (DOM handle,
|
||||||
|
// listener wrappers). It's `any` so this package stays platform-neutral; it
|
||||||
|
// is nil on the server.
|
||||||
|
Runtime any
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mod configures a VNode while it is built.
|
||||||
|
type Mod interface{ apply(*VNode) }
|
||||||
|
|
||||||
|
// El builds an element VNode.
|
||||||
|
func El(tag string, mods ...Mod) *VNode {
|
||||||
|
n := &VNode{Tag: tag, Attrs: map[string]string{}, Props: map[string]string{}, Events: map[string]func(Event){}}
|
||||||
|
for _, m := range mods {
|
||||||
|
m.apply(n)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// Text builds a text VNode.
|
||||||
|
func Text(s string) *VNode { return &VNode{Text: s} }
|
||||||
|
|
||||||
|
func (n *VNode) apply(parent *VNode) { parent.Children = append(parent.Children, n) }
|
||||||
|
|
||||||
|
type attrMod struct{ k, v string }
|
||||||
|
|
||||||
|
func (a attrMod) apply(n *VNode) { n.Attrs[a.k] = a.v }
|
||||||
|
|
||||||
|
// Attr sets an HTML attribute.
|
||||||
|
func Attr(k, v string) Mod { return attrMod{k, v} }
|
||||||
|
|
||||||
|
type propMod struct{ k, v string }
|
||||||
|
|
||||||
|
func (p propMod) apply(n *VNode) { n.Props[p.k] = p.v }
|
||||||
|
|
||||||
|
// Prop sets a live DOM property (e.g. an input's value).
|
||||||
|
func Prop(k, v string) Mod { return propMod{k, v} }
|
||||||
|
|
||||||
|
type htmlMod struct{ html string }
|
||||||
|
|
||||||
|
func (h htmlMod) apply(n *VNode) { n.HTML = h.html }
|
||||||
|
|
||||||
|
// Raw sets inner HTML verbatim (children ignored) — e.g. a server-computed SVG.
|
||||||
|
func Raw(html string) Mod { return htmlMod{html} }
|
||||||
|
|
||||||
|
type eventMod struct {
|
||||||
|
name string
|
||||||
|
h func(Event)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e eventMod) apply(n *VNode) { n.Events[e.name] = e.h }
|
||||||
|
|
||||||
|
// On registers an event handler that ignores the event object.
|
||||||
|
func On(event string, h func()) Mod { return eventMod{event, func(Event) { h() }} }
|
||||||
|
|
||||||
|
// OnEvent registers an event handler that receives the Event.
|
||||||
|
func OnEvent(event string, h func(Event)) Mod { return eventMod{event, h} }
|
||||||
|
|
||||||
|
// --- server-side HTML rendering (used for SSR; runs on any platform) ---
|
||||||
|
|
||||||
|
var voidTags = map[string]bool{"br": true, "hr": true, "img": true, "input": true, "meta": true, "link": true}
|
||||||
|
|
||||||
|
// RenderHTML serializes a VNode tree to HTML with NO extra whitespace, so the
|
||||||
|
// browser's parsed childNodes line up 1:1 with the VNode children on hydration.
|
||||||
|
func RenderHTML(n *VNode) string {
|
||||||
|
var b strings.Builder
|
||||||
|
writeNode(&b, n)
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeNode(b *strings.Builder, n *VNode) {
|
||||||
|
if n.Tag == "" {
|
||||||
|
b.WriteString(html.EscapeString(n.Text))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
b.WriteByte('<')
|
||||||
|
b.WriteString(n.Tag)
|
||||||
|
writeAttrs(b, n.Attrs)
|
||||||
|
writeAttrs(b, n.Props) // props like input value show up as attributes in SSR
|
||||||
|
b.WriteByte('>')
|
||||||
|
if voidTags[n.Tag] {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if n.HTML != "" {
|
||||||
|
b.WriteString(n.HTML) // raw
|
||||||
|
} else {
|
||||||
|
for _, c := range n.Children {
|
||||||
|
writeNode(b, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.WriteString("</")
|
||||||
|
b.WriteString(n.Tag)
|
||||||
|
b.WriteByte('>')
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeAttrs(b *strings.Builder, m map[string]string) {
|
||||||
|
keys := make([]string, 0, len(m))
|
||||||
|
for k := range m {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
for _, k := range keys {
|
||||||
|
b.WriteByte(' ')
|
||||||
|
b.WriteString(k)
|
||||||
|
b.WriteString(`="`)
|
||||||
|
b.WriteString(html.EscapeString(m[k]))
|
||||||
|
b.WriteByte('"')
|
||||||
|
}
|
||||||
|
}
|
||||||
372
go/wasmdevserver/devserver.go
Normal file
372
go/wasmdevserver/devserver.go
Normal file
@@ -0,0 +1,372 @@
|
|||||||
|
// Package wasmdevserver is a reusable development server for gowasm apps: it serves
|
||||||
|
// the built web assets, renders routes server-side (SSR) at request time, hosts
|
||||||
|
// the /rsc server-component endpoint, and hot-swaps the freshly built wasm into
|
||||||
|
// the browser on change (no full reload, state preserved) — surfacing build
|
||||||
|
// failures as an in-page overlay.
|
||||||
|
//
|
||||||
|
// It never imports application code (per kjol's golden rule). The app injects
|
||||||
|
// everything specific to it through Config: how to build the wasm bundle
|
||||||
|
// (Build), how to render a route to HTML (Render), and how to wrap that HTML in
|
||||||
|
// a document (Document). The WebSocket hub and file watcher use only the
|
||||||
|
// standard library.
|
||||||
|
package wasmdevserver
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha1"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"kjol/rsc"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config wires an app into the dev server. Render and Document are called per
|
||||||
|
// request; Build is called for the initial build and on every source change.
|
||||||
|
type Config struct {
|
||||||
|
Addr string // listen address (default ":8085")
|
||||||
|
Dir string // static assets dir; Build writes app.wasm here (default "./wwwroot")
|
||||||
|
Watch bool // rebuild on change + hot reload
|
||||||
|
WatchDirs []string // source dirs to watch when Watch is set
|
||||||
|
Build func() ([]byte, error) // (re)build the wasm bundle; combined output on failure
|
||||||
|
Render func(path string) (inner string, ok bool) // SSR the #app inner HTML for a route (ok=false => client-rendered)
|
||||||
|
Document func(inner string) string // wrap #app inner HTML in a full HTML document
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serve builds once (in watch mode), wires the routes, and blocks serving.
|
||||||
|
func Serve(cfg Config) error {
|
||||||
|
if cfg.Addr == "" {
|
||||||
|
cfg.Addr = ":8085"
|
||||||
|
}
|
||||||
|
if cfg.Dir == "" {
|
||||||
|
cfg.Dir = "./wwwroot"
|
||||||
|
}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
h := newHub()
|
||||||
|
|
||||||
|
if cfg.Watch {
|
||||||
|
if err := ensureShim(cfg.Dir); err != nil {
|
||||||
|
log.Printf("warning: could not stage wasm_exec.js: %v", err)
|
||||||
|
}
|
||||||
|
if cfg.Build != nil {
|
||||||
|
if out, err := cfg.Build(); err != nil {
|
||||||
|
log.Printf("initial build failed: %v\n%s", err, out)
|
||||||
|
h.setError(string(out)) // a browser opened now sees it via the overlay
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mux.HandleFunc("/livereload", h.serveWS)
|
||||||
|
mux.HandleFunc("/livereload.js", serveClientJS)
|
||||||
|
go watchLoop(cfg, h)
|
||||||
|
log.Printf("hot reload enabled (watching %v)", cfg.WatchDirs)
|
||||||
|
}
|
||||||
|
|
||||||
|
mux.HandleFunc("POST /rsc", rsc.Handler) // server components
|
||||||
|
mux.HandleFunc("/", rootHandler(cfg))
|
||||||
|
|
||||||
|
log.Printf("serving %q on http://localhost%s", cfg.Dir, cfg.Addr)
|
||||||
|
return http.ListenAndServe(cfg.Addr, mux)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- serving: assets, and dynamic SSR for HTML routes -------------------
|
||||||
|
|
||||||
|
func rootHandler(cfg Config) http.HandlerFunc {
|
||||||
|
live := ""
|
||||||
|
if cfg.Watch {
|
||||||
|
live = `<script src="/livereload.js"></script>`
|
||||||
|
}
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
clean := filepath.Clean("/" + r.URL.Path)
|
||||||
|
fsPath := filepath.Join(cfg.Dir, clean)
|
||||||
|
if info, err := os.Stat(fsPath); err == nil && !info.IsDir() && clean != "/" {
|
||||||
|
if strings.HasSuffix(fsPath, ".wasm") {
|
||||||
|
w.Header().Set("Content-Type", "application/wasm")
|
||||||
|
}
|
||||||
|
http.ServeFile(w, r, fsPath)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
inner := ""
|
||||||
|
if cfg.Render != nil {
|
||||||
|
inner, _ = cfg.Render(r.URL.Path)
|
||||||
|
}
|
||||||
|
html := inner
|
||||||
|
if cfg.Document != nil {
|
||||||
|
html = cfg.Document(inner)
|
||||||
|
}
|
||||||
|
if live != "" {
|
||||||
|
html = strings.Replace(html, "</body>", live+"\n</body>", 1)
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
io.WriteString(w, html)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- build + watch ------------------------------------------------------
|
||||||
|
|
||||||
|
func watchLoop(cfg Config, h *hub) {
|
||||||
|
prev := fingerprint(cfg.WatchDirs)
|
||||||
|
for {
|
||||||
|
time.Sleep(300 * time.Millisecond)
|
||||||
|
fp := fingerprint(cfg.WatchDirs)
|
||||||
|
if fp == prev {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
prev = fp
|
||||||
|
log.Println("change detected, rebuilding…")
|
||||||
|
h.broadcast(`{"type":"building"}`)
|
||||||
|
if cfg.Build == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if out, err := cfg.Build(); err != nil {
|
||||||
|
log.Printf("build failed: %v\n%s", err, out)
|
||||||
|
h.setError(string(out)) // push the compiler output to the browser overlay
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
log.Println("rebuild ok — reloading clients")
|
||||||
|
h.clearError()
|
||||||
|
h.broadcast(`{"type":"reload"}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fingerprint changes whenever any .go file under dirs is modified.
|
||||||
|
func fingerprint(dirs []string) int64 {
|
||||||
|
var fp int64
|
||||||
|
for _, d := range dirs {
|
||||||
|
filepath.WalkDir(d, func(path string, e fs.DirEntry, err error) error {
|
||||||
|
if err != nil || e.IsDir() || !strings.HasSuffix(path, ".go") {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if info, err := e.Info(); err == nil {
|
||||||
|
fp += info.ModTime().UnixNano() + info.Size()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return fp
|
||||||
|
}
|
||||||
|
|
||||||
|
func jsonStr(s string) string { b, _ := json.Marshal(s); return string(b) }
|
||||||
|
|
||||||
|
// ensureShim copies Go's wasm_exec.js into dir if it isn't already there, so the
|
||||||
|
// server is self-sufficient without a separate build step first.
|
||||||
|
func ensureShim(dir string) error {
|
||||||
|
dst := filepath.Join(dir, "wasm_exec.js")
|
||||||
|
if _, err := os.Stat(dst); err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
root, err := exec.Command("go", "env", "GOROOT").Output()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
goroot := strings.TrimSpace(string(root))
|
||||||
|
for _, p := range []string{
|
||||||
|
filepath.Join(goroot, "lib", "wasm", "wasm_exec.js"), // Go >= 1.24
|
||||||
|
filepath.Join(goroot, "misc", "wasm", "wasm_exec.js"), // Go <= 1.23
|
||||||
|
} {
|
||||||
|
if b, err := os.ReadFile(p); err == nil {
|
||||||
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.WriteFile(dst, b, 0o644)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return os.ErrNotExist
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- injected livereload client -----------------------------------------
|
||||||
|
|
||||||
|
const clientJS = `// Injected by the dev server in watch mode.
|
||||||
|
(function () {
|
||||||
|
// Hot-swap the freshly built wasm in place — no full page reload and no blank
|
||||||
|
// flash. We fetch + compile the NEW module while the current page stays
|
||||||
|
// visible, then tear down the old instance and start the new one in the SAME
|
||||||
|
// task, so the browser never paints the intermediate empty #app. State is
|
||||||
|
// preserved: the old instance snapshots its signals on dispose; the new one
|
||||||
|
// restores them on boot.
|
||||||
|
async function hotSwap() {
|
||||||
|
if (!window.__gowasmPrepare) { location.reload(); return; } // fallback
|
||||||
|
var start;
|
||||||
|
try { start = await window.__gowasmPrepare(); } // network + compile; page still visible
|
||||||
|
catch (err) { console.error(err); location.reload(); return; }
|
||||||
|
hideOverlay();
|
||||||
|
try { if (window.__gowasmDispose) window.__gowasmDispose(); } catch (err) { console.error(err); }
|
||||||
|
start(); // renders synchronously — no await between dispose and first paint
|
||||||
|
}
|
||||||
|
|
||||||
|
// Full-screen overlay showing the Go compiler output when a build fails. The
|
||||||
|
// app underneath keeps running (and its state), so fixing the code and saving
|
||||||
|
// clears the overlay and hot-swaps without losing anything.
|
||||||
|
function ensureOverlay() {
|
||||||
|
var el = document.getElementById("__gowasm_error");
|
||||||
|
if (!el) {
|
||||||
|
el = document.createElement("div");
|
||||||
|
el.id = "__gowasm_error";
|
||||||
|
el.style.cssText = "position:fixed;inset:0;z-index:2147483647;margin:0;padding:24px 28px;" +
|
||||||
|
"background:rgba(24,24,27,0.97);color:#e4e4e7;overflow:auto;" +
|
||||||
|
"font:13px/1.55 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;";
|
||||||
|
document.body.appendChild(el);
|
||||||
|
}
|
||||||
|
return el;
|
||||||
|
}
|
||||||
|
function showOverlay(text) {
|
||||||
|
var el = ensureOverlay();
|
||||||
|
el.textContent = "";
|
||||||
|
var head = document.createElement("div");
|
||||||
|
head.style.cssText = "color:#f87171;font-weight:700;font-size:15px;margin-bottom:14px;";
|
||||||
|
head.textContent = "⚠ gowasm — build failed";
|
||||||
|
var pre = document.createElement("pre");
|
||||||
|
pre.style.cssText = "margin:0;white-space:pre-wrap;word-break:break-word;";
|
||||||
|
pre.textContent = text || "(no compiler output)";
|
||||||
|
el.appendChild(head);
|
||||||
|
el.appendChild(pre);
|
||||||
|
}
|
||||||
|
function hideOverlay() {
|
||||||
|
var el = document.getElementById("__gowasm_error");
|
||||||
|
if (el && el.parentNode) { el.parentNode.removeChild(el); }
|
||||||
|
}
|
||||||
|
window.__gowasmErrorOverlay = { show: showOverlay, hide: hideOverlay };
|
||||||
|
|
||||||
|
function connect() {
|
||||||
|
var proto = location.protocol === "https:" ? "wss://" : "ws://";
|
||||||
|
var ws = new WebSocket(proto + location.host + "/livereload");
|
||||||
|
ws.onmessage = function (e) {
|
||||||
|
var msg = {};
|
||||||
|
try { msg = JSON.parse(e.data); } catch (_) { return; }
|
||||||
|
if (msg.type === "reload") { hotSwap(); } // build ok: swap in place
|
||||||
|
else if (msg.type === "error") { showOverlay(msg.msg); } // build failed: show compiler output
|
||||||
|
else if (msg.type === "building") { console.log("[hot reload] rebuilding…"); }
|
||||||
|
};
|
||||||
|
ws.onclose = function () { setTimeout(connect, 1000); }; // reconnect after reload/restart
|
||||||
|
ws.onerror = function () { try { ws.close(); } catch (_) {} };
|
||||||
|
}
|
||||||
|
connect();
|
||||||
|
})();
|
||||||
|
`
|
||||||
|
|
||||||
|
func serveClientJS(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
io.WriteString(w, clientJS)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- minimal WebSocket hub (stdlib only) --------------------------------
|
||||||
|
|
||||||
|
type hub struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
clients map[*wsConn]struct{}
|
||||||
|
lastError string // most recent build-failure message (JSON), replayed to new clients
|
||||||
|
}
|
||||||
|
|
||||||
|
func newHub() *hub { return &hub{clients: map[*wsConn]struct{}{}} }
|
||||||
|
|
||||||
|
func (h *hub) add(c *wsConn) { h.mu.Lock(); h.clients[c] = struct{}{}; h.mu.Unlock() }
|
||||||
|
func (h *hub) remove(c *wsConn) { h.mu.Lock(); delete(h.clients, c); h.mu.Unlock() }
|
||||||
|
|
||||||
|
// setError records the current build failure (so it survives to new clients) and
|
||||||
|
// pushes it to everyone connected. clearError is called on the next good build.
|
||||||
|
func (h *hub) setError(out string) {
|
||||||
|
msg := `{"type":"error","msg":` + jsonStr(out) + `}`
|
||||||
|
h.mu.Lock()
|
||||||
|
h.lastError = msg
|
||||||
|
h.mu.Unlock()
|
||||||
|
h.broadcast(msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *hub) clearError() { h.mu.Lock(); h.lastError = ""; h.mu.Unlock() }
|
||||||
|
|
||||||
|
func (h *hub) errorMessage() string { h.mu.Lock(); defer h.mu.Unlock(); return h.lastError }
|
||||||
|
|
||||||
|
func (h *hub) broadcast(msg string) {
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
for c := range h.clients {
|
||||||
|
if err := c.sendText(msg); err != nil {
|
||||||
|
c.conn.Close()
|
||||||
|
delete(h.clients, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// serveWS upgrades the request to a WebSocket and keeps the connection until the
|
||||||
|
// client disconnects. We only ever push server->client, so incoming frames are
|
||||||
|
// drained (which also lets us detect disconnects).
|
||||||
|
func (h *hub) serveWS(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !strings.Contains(strings.ToLower(r.Header.Get("Upgrade")), "websocket") {
|
||||||
|
http.Error(w, "expected websocket upgrade", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hj, ok := w.(http.Hijacker)
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, "hijacking unsupported", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
conn, brw, err := hj.Hijack()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
accept := acceptKey(r.Header.Get("Sec-WebSocket-Key"))
|
||||||
|
io.WriteString(brw, "HTTP/1.1 101 Switching Protocols\r\n"+
|
||||||
|
"Upgrade: websocket\r\nConnection: Upgrade\r\n"+
|
||||||
|
"Sec-WebSocket-Accept: "+accept+"\r\n\r\n")
|
||||||
|
if brw.Flush() != nil {
|
||||||
|
conn.Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c := &wsConn{conn: conn}
|
||||||
|
h.add(c)
|
||||||
|
if msg := h.errorMessage(); msg != "" {
|
||||||
|
c.sendText(msg) // opened after a failed build => show the overlay right away
|
||||||
|
}
|
||||||
|
// Drain incoming bytes; return (and clean up) when the client goes away.
|
||||||
|
go func() {
|
||||||
|
io.Copy(io.Discard, brw)
|
||||||
|
conn.Close()
|
||||||
|
h.remove(c)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func acceptKey(key string) string {
|
||||||
|
h := sha1.New()
|
||||||
|
io.WriteString(h, key+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
|
||||||
|
return base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||||||
|
}
|
||||||
|
|
||||||
|
type wsConn struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
conn net.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
// sendText writes a single unmasked text frame (server frames are never masked).
|
||||||
|
func (c *wsConn) sendText(msg string) error {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
|
||||||
|
payload := []byte(msg)
|
||||||
|
n := len(payload)
|
||||||
|
var header []byte
|
||||||
|
switch {
|
||||||
|
case n < 126:
|
||||||
|
header = []byte{0x81, byte(n)}
|
||||||
|
case n < 1<<16:
|
||||||
|
header = []byte{0x81, 126, byte(n >> 8), byte(n)}
|
||||||
|
default:
|
||||||
|
header = []byte{0x81, 127,
|
||||||
|
byte(n >> 56), byte(n >> 48), byte(n >> 40), byte(n >> 32),
|
||||||
|
byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n)}
|
||||||
|
}
|
||||||
|
if _, err := c.conn.Write(header); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err := c.conn.Write(payload)
|
||||||
|
return err
|
||||||
|
}
|
||||||
77
go/wasmruntime/fetch.go
Normal file
77
go/wasmruntime/fetch.go
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
//go:build js && wasm
|
||||||
|
|
||||||
|
package wasmruntime
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"syscall/js"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Fetch performs an HTTP GET via the browser Fetch API and returns the response
|
||||||
|
// body as a string. It bridges a JS Promise into Go: it registers then/catch
|
||||||
|
// callbacks and blocks the calling goroutine on a channel until the request
|
||||||
|
// settles.
|
||||||
|
//
|
||||||
|
// Because it blocks, call it from a goroutine — never from a reactive callback
|
||||||
|
// or event handler — and write the result into signals when it returns, e.g.:
|
||||||
|
//
|
||||||
|
// go func() {
|
||||||
|
// body, err := Fetch(url)
|
||||||
|
// ...
|
||||||
|
// data.Set(...) // updates the UI reactively
|
||||||
|
// }()
|
||||||
|
func Fetch(url string) (string, error) {
|
||||||
|
var (
|
||||||
|
once sync.Once
|
||||||
|
done = make(chan struct{})
|
||||||
|
body string
|
||||||
|
ferr error
|
||||||
|
onResp, onText, onErr js.Func
|
||||||
|
)
|
||||||
|
finish := func() { once.Do(func() { close(done) }) }
|
||||||
|
|
||||||
|
onErr = js.FuncOf(func(this js.Value, args []js.Value) any {
|
||||||
|
msg := "fetch error"
|
||||||
|
if len(args) > 0 && args[0].Truthy() {
|
||||||
|
e := args[0]
|
||||||
|
if m := e.Get("message"); m.Truthy() {
|
||||||
|
msg = m.String()
|
||||||
|
} else {
|
||||||
|
msg = e.Call("toString").String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ferr = errors.New(msg)
|
||||||
|
finish()
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
onText = js.FuncOf(func(this js.Value, args []js.Value) any {
|
||||||
|
if len(args) > 0 {
|
||||||
|
body = args[0].String()
|
||||||
|
}
|
||||||
|
finish()
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
onResp = js.FuncOf(func(this js.Value, args []js.Value) any {
|
||||||
|
resp := args[0]
|
||||||
|
if !resp.Get("ok").Bool() {
|
||||||
|
ferr = fmt.Errorf("HTTP %d", resp.Get("status").Int())
|
||||||
|
finish()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// resp.text() -> Promise<string>
|
||||||
|
resp.Call("text").Call("then", onText).Call("catch", onErr)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
js.Global().Call("fetch", url).Call("then", onResp).Call("catch", onErr)
|
||||||
|
|
||||||
|
<-done
|
||||||
|
onResp.Release()
|
||||||
|
onText.Release()
|
||||||
|
onErr.Release()
|
||||||
|
return body, ferr
|
||||||
|
}
|
||||||
86
go/wasmruntime/mount.go
Normal file
86
go/wasmruntime/mount.go
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
//go:build js && wasm
|
||||||
|
|
||||||
|
package wasmruntime
|
||||||
|
|
||||||
|
import (
|
||||||
|
"syscall/js"
|
||||||
|
|
||||||
|
"kjol/vdom"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
rootRender func()
|
||||||
|
renderScheduled bool
|
||||||
|
disposed bool
|
||||||
|
flushFunc js.Func
|
||||||
|
flushInited bool
|
||||||
|
)
|
||||||
|
|
||||||
|
// HasServerContent reports whether #app already holds server-rendered markup
|
||||||
|
// (so the client should Hydrate rather than build from scratch).
|
||||||
|
func HasServerContent() bool {
|
||||||
|
return document.Call("getElementById", "app").Get("firstChild").Truthy()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run mounts a component fresh (client-side rendering). The component returns a
|
||||||
|
// VNode tree; any signal write re-renders and reconciles into the DOM.
|
||||||
|
func Run(component func() *vdom.VNode) {
|
||||||
|
vdom.Schedule = scheduleRender
|
||||||
|
root := document.Call("getElementById", "app")
|
||||||
|
var prev *vdom.VNode
|
||||||
|
rootRender = func() {
|
||||||
|
next := component()
|
||||||
|
patchChildren(root, one(prev), one(next))
|
||||||
|
prev = next
|
||||||
|
}
|
||||||
|
rootRender()
|
||||||
|
finish(root)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hydrate attaches to server-rendered DOM: it renders the same initial tree the
|
||||||
|
// server did, adopts the existing nodes (wiring events, no re-creation), then
|
||||||
|
// re-renders reactively from there.
|
||||||
|
func Hydrate(component func() *vdom.VNode) {
|
||||||
|
vdom.Schedule = scheduleRender
|
||||||
|
root := document.Call("getElementById", "app")
|
||||||
|
prev := component()
|
||||||
|
hydrateNode(root.Get("firstChild"), prev)
|
||||||
|
rootRender = func() {
|
||||||
|
next := component()
|
||||||
|
patchChildren(root, one(prev), one(next))
|
||||||
|
prev = next
|
||||||
|
}
|
||||||
|
finish(root)
|
||||||
|
}
|
||||||
|
|
||||||
|
func finish(root js.Value) {
|
||||||
|
// Allow a JS loader to tear this instance down before an in-place hot swap:
|
||||||
|
// snapshot signal state (so the next instance restores it), then clear #app.
|
||||||
|
js.Global().Set("__gowasmDispose", js.FuncOf(func(this js.Value, args []js.Value) any {
|
||||||
|
disposed = true
|
||||||
|
saveState()
|
||||||
|
root.Set("innerHTML", "")
|
||||||
|
return nil
|
||||||
|
}))
|
||||||
|
select {} // keep the runtime alive for event callbacks
|
||||||
|
}
|
||||||
|
|
||||||
|
func scheduleRender() {
|
||||||
|
if disposed || rootRender == nil || renderScheduled {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
renderScheduled = true
|
||||||
|
js.Global().Call("queueMicrotask", ensureFlush())
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureFlush() js.Func {
|
||||||
|
if !flushInited {
|
||||||
|
flushFunc = js.FuncOf(func(this js.Value, args []js.Value) any {
|
||||||
|
renderScheduled = false
|
||||||
|
rootRender()
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
flushInited = true
|
||||||
|
}
|
||||||
|
return flushFunc
|
||||||
|
}
|
||||||
68
go/wasmruntime/persist_wasm.go
Normal file
68
go/wasmruntime/persist_wasm.go
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
//go:build js && wasm
|
||||||
|
|
||||||
|
package wasmruntime
|
||||||
|
|
||||||
|
import (
|
||||||
|
"syscall/js"
|
||||||
|
|
||||||
|
"kjol/vdom"
|
||||||
|
)
|
||||||
|
|
||||||
|
// State preservation across an in-place hot swap (see the dev server's
|
||||||
|
// livereload script). A fresh wasm instance has fresh Go memory, so signal
|
||||||
|
// values would reset on every rebuild. To keep them, the outgoing instance
|
||||||
|
// snapshots its signals (by creation order, via a vdom.Collector) into
|
||||||
|
// sessionStorage on dispose, and the incoming instance restores them on boot.
|
||||||
|
//
|
||||||
|
// It's best-effort: if an edit adds/removes/reorders signals, the by-order match
|
||||||
|
// shifts and unmatched signals fall back to their initial value — the same
|
||||||
|
// hook-order caveat as server components.
|
||||||
|
|
||||||
|
const stateKey = "__gowasm_hmr_state"
|
||||||
|
|
||||||
|
var stateCollector *vdom.Collector
|
||||||
|
|
||||||
|
// PreserveState registers the collector whose signals are snapshotted to
|
||||||
|
// sessionStorage when this instance is disposed for a hot swap.
|
||||||
|
func PreserveState(c *vdom.Collector) { stateCollector = c }
|
||||||
|
|
||||||
|
// RestoreState returns the signal snapshot saved by a prior instance before a
|
||||||
|
// hot swap, or nil if there is none. It is one-shot: the entry is cleared so a
|
||||||
|
// manual page refresh starts from initial state.
|
||||||
|
func RestoreState() [][]byte {
|
||||||
|
ss := js.Global().Get("sessionStorage")
|
||||||
|
if !ss.Truthy() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
raw := ss.Call("getItem", stateKey)
|
||||||
|
if !raw.Truthy() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
ss.Call("removeItem", stateKey)
|
||||||
|
arr := js.Global().Get("JSON").Call("parse", raw)
|
||||||
|
if arr.Type() != js.TypeObject {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
out := make([][]byte, arr.Length())
|
||||||
|
for i := range out {
|
||||||
|
out[i] = []byte(arr.Index(i).String())
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// saveState writes the preserved collector's current signal values to
|
||||||
|
// sessionStorage. Called from the dispose hook before the DOM is torn down.
|
||||||
|
func saveState() {
|
||||||
|
if stateCollector == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ss := js.Global().Get("sessionStorage")
|
||||||
|
if !ss.Truthy() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
arr := js.Global().Get("Array").New()
|
||||||
|
for _, b := range stateCollector.Snapshot() {
|
||||||
|
arr.Call("push", string(b))
|
||||||
|
}
|
||||||
|
ss.Call("setItem", stateKey, js.Global().Get("JSON").Call("stringify", arr))
|
||||||
|
}
|
||||||
228
go/wasmruntime/reconcile.go
Normal file
228
go/wasmruntime/reconcile.go
Normal file
@@ -0,0 +1,228 @@
|
|||||||
|
//go:build js && wasm
|
||||||
|
|
||||||
|
// Package wasmruntime is the wasm client runtime for the neutral vdom package: it
|
||||||
|
// reconciles vdom.VNode trees into the real DOM (fresh mount or hydration of
|
||||||
|
// server-rendered DOM), and drives re-renders when signals change.
|
||||||
|
package wasmruntime
|
||||||
|
|
||||||
|
import (
|
||||||
|
"syscall/js"
|
||||||
|
|
||||||
|
"kjol/vdom"
|
||||||
|
)
|
||||||
|
|
||||||
|
var document = js.Global().Get("document")
|
||||||
|
|
||||||
|
// nodeRT is the per-node bookkeeping stored in VNode.Runtime (wasm only).
|
||||||
|
type nodeRT struct {
|
||||||
|
dom js.Value
|
||||||
|
jsFuncs map[string]js.Func
|
||||||
|
refs map[string]*handlerRef
|
||||||
|
}
|
||||||
|
|
||||||
|
type handlerRef struct{ fn func(vdom.Event) }
|
||||||
|
|
||||||
|
func rt(n *vdom.VNode) *nodeRT {
|
||||||
|
if n.Runtime == nil {
|
||||||
|
n.Runtime = &nodeRT{jsFuncs: map[string]js.Func{}, refs: map[string]*handlerRef{}}
|
||||||
|
}
|
||||||
|
return n.Runtime.(*nodeRT)
|
||||||
|
}
|
||||||
|
|
||||||
|
// clientEvent adapts a DOM event to vdom.Event.
|
||||||
|
type clientEvent struct{ js js.Value }
|
||||||
|
|
||||||
|
func (e clientEvent) PreventDefault() { e.js.Call("preventDefault") }
|
||||||
|
|
||||||
|
func (e clientEvent) Value() string {
|
||||||
|
t := e.js.Get("target")
|
||||||
|
if !t.Truthy() {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
v := t.Get("value")
|
||||||
|
if !v.Truthy() {
|
||||||
|
return "" // e.g. a button has no value
|
||||||
|
}
|
||||||
|
return v.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func one(n *vdom.VNode) []*vdom.VNode {
|
||||||
|
if n == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return []*vdom.VNode{n}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- fresh create + diff ----
|
||||||
|
|
||||||
|
func createDOM(n *vdom.VNode) js.Value {
|
||||||
|
if n.Tag == "" {
|
||||||
|
d := document.Call("createTextNode", n.Text)
|
||||||
|
rt(n).dom = d
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
el := document.Call("createElement", n.Tag)
|
||||||
|
rt(n).dom = el
|
||||||
|
for k, v := range n.Attrs {
|
||||||
|
el.Call("setAttribute", k, v)
|
||||||
|
}
|
||||||
|
for k, v := range n.Props {
|
||||||
|
el.Set(k, v)
|
||||||
|
}
|
||||||
|
for name, h := range n.Events {
|
||||||
|
addListener(n, name, h)
|
||||||
|
}
|
||||||
|
if n.HTML != "" {
|
||||||
|
el.Set("innerHTML", n.HTML)
|
||||||
|
return el
|
||||||
|
}
|
||||||
|
for _, c := range n.Children {
|
||||||
|
el.Call("appendChild", createDOM(c))
|
||||||
|
}
|
||||||
|
return el
|
||||||
|
}
|
||||||
|
|
||||||
|
func patchChildren(parent js.Value, old, next []*vdom.VNode) {
|
||||||
|
n := max(len(old), len(next))
|
||||||
|
for i := range n {
|
||||||
|
var o, x *vdom.VNode
|
||||||
|
if i < len(old) {
|
||||||
|
o = old[i]
|
||||||
|
}
|
||||||
|
if i < len(next) {
|
||||||
|
x = next[i]
|
||||||
|
}
|
||||||
|
patch(parent, o, x)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func patch(parent js.Value, o, x *vdom.VNode) {
|
||||||
|
switch {
|
||||||
|
case o == nil && x == nil:
|
||||||
|
return
|
||||||
|
case o == nil:
|
||||||
|
parent.Call("appendChild", createDOM(x))
|
||||||
|
case x == nil:
|
||||||
|
parent.Call("removeChild", rt(o).dom)
|
||||||
|
release(o)
|
||||||
|
case o.Tag != x.Tag:
|
||||||
|
parent.Call("replaceChild", createDOM(x), rt(o).dom)
|
||||||
|
release(o)
|
||||||
|
default:
|
||||||
|
x.Runtime = o.Runtime // adopt dom + listeners
|
||||||
|
dom := rt(x).dom
|
||||||
|
if x.Tag == "" {
|
||||||
|
if x.Text != o.Text {
|
||||||
|
dom.Set("nodeValue", x.Text)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
updateAttrs(o, x)
|
||||||
|
updateProps(o, x)
|
||||||
|
updateEvents(o, x)
|
||||||
|
if x.HTML != "" {
|
||||||
|
if x.HTML != o.HTML {
|
||||||
|
dom.Set("innerHTML", x.HTML)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
patchChildren(dom, o.Children, x.Children)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateAttrs(o, x *vdom.VNode) {
|
||||||
|
dom := rt(x).dom
|
||||||
|
for k := range o.Attrs {
|
||||||
|
if _, ok := x.Attrs[k]; !ok {
|
||||||
|
dom.Call("removeAttribute", k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for k, v := range x.Attrs {
|
||||||
|
if o.Attrs[k] != v {
|
||||||
|
dom.Call("setAttribute", k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateProps(o, x *vdom.VNode) {
|
||||||
|
dom := rt(x).dom
|
||||||
|
for k, v := range x.Props {
|
||||||
|
if o.Props[k] != v && dom.Get(k).String() != v {
|
||||||
|
dom.Set(k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateEvents(o, x *vdom.VNode) {
|
||||||
|
r := rt(x) // same nodeRT as o (adopted above)
|
||||||
|
for name, fn := range r.jsFuncs {
|
||||||
|
if _, ok := x.Events[name]; !ok {
|
||||||
|
r.dom.Call("removeEventListener", name, fn)
|
||||||
|
fn.Release()
|
||||||
|
delete(r.jsFuncs, name)
|
||||||
|
delete(r.refs, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name, h := range x.Events {
|
||||||
|
if ref, ok := r.refs[name]; ok {
|
||||||
|
ref.fn = h
|
||||||
|
} else {
|
||||||
|
addListener(x, name, h)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func addListener(n *vdom.VNode, name string, handler func(vdom.Event)) {
|
||||||
|
r := rt(n)
|
||||||
|
ref := &handlerRef{fn: handler}
|
||||||
|
fn := js.FuncOf(func(this js.Value, args []js.Value) any {
|
||||||
|
var ev js.Value
|
||||||
|
if len(args) > 0 {
|
||||||
|
ev = args[0]
|
||||||
|
}
|
||||||
|
ref.fn(clientEvent{js: ev})
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
r.dom.Call("addEventListener", name, fn)
|
||||||
|
r.jsFuncs[name] = fn
|
||||||
|
r.refs[name] = ref
|
||||||
|
}
|
||||||
|
|
||||||
|
func release(n *vdom.VNode) {
|
||||||
|
if n.Runtime != nil {
|
||||||
|
for _, fn := range rt(n).jsFuncs {
|
||||||
|
fn.Release()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, c := range n.Children {
|
||||||
|
release(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- hydration: adopt server-rendered DOM instead of creating it ----
|
||||||
|
|
||||||
|
func hydrateNode(dom js.Value, n *vdom.VNode) {
|
||||||
|
if !dom.Truthy() {
|
||||||
|
return // structural mismatch; leave a hole (a later re-render will fix)
|
||||||
|
}
|
||||||
|
rt(n).dom = dom
|
||||||
|
if n.Tag == "" {
|
||||||
|
if dom.Get("nodeValue").String() != n.Text {
|
||||||
|
dom.Set("nodeValue", n.Text)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for name, h := range n.Events {
|
||||||
|
addListener(n, name, h)
|
||||||
|
}
|
||||||
|
for k, v := range n.Props {
|
||||||
|
dom.Set(k, v)
|
||||||
|
}
|
||||||
|
if n.HTML != "" {
|
||||||
|
return // trust server-rendered HTML
|
||||||
|
}
|
||||||
|
childNodes := dom.Get("childNodes")
|
||||||
|
for i, c := range n.Children {
|
||||||
|
hydrateNode(childNodes.Index(i), c)
|
||||||
|
}
|
||||||
|
}
|
||||||
38
go/wasmruntime/router.go
Normal file
38
go/wasmruntime/router.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
//go:build js && wasm
|
||||||
|
|
||||||
|
package wasmruntime
|
||||||
|
|
||||||
|
import (
|
||||||
|
"syscall/js"
|
||||||
|
|
||||||
|
"kjol/vdom"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Router holds the current path in a signal, so reading Path() during render
|
||||||
|
// re-renders on navigation (and browser back/forward).
|
||||||
|
type Router struct {
|
||||||
|
path *vdom.Signal[string]
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRouter() *Router {
|
||||||
|
r := &Router{path: vdom.NewSignal(currentPath())}
|
||||||
|
popstate := js.FuncOf(func(this js.Value, args []js.Value) any {
|
||||||
|
r.path.Set(currentPath())
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
js.Global().Call("addEventListener", "popstate", popstate)
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func currentPath() string {
|
||||||
|
return js.Global().Get("location").Get("pathname").String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Path returns the current route (reactive when read during render).
|
||||||
|
func (r *Router) Path() string { return r.path.Get() }
|
||||||
|
|
||||||
|
// Navigate pushes a history entry and re-renders (client-side SPA navigation).
|
||||||
|
func (r *Router) Navigate(path string) {
|
||||||
|
js.Global().Get("history").Call("pushState", nil, "", path)
|
||||||
|
r.path.Set(path)
|
||||||
|
}
|
||||||
7
go/wasmruntime/wasmruntime.go
Normal file
7
go/wasmruntime/wasmruntime.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
//go:build !(js && wasm)
|
||||||
|
|
||||||
|
// Package wasmruntime is the browser-side client runtime (reconciler, mount /
|
||||||
|
// hydrate, router, fetch, hot-reload state preservation). Its implementation
|
||||||
|
// compiles only under GOOS=js GOARCH=wasm; this placeholder keeps the package
|
||||||
|
// non-empty on other platforms so `go build ./...` / `go vet ./...` succeed.
|
||||||
|
package wasmruntime
|
||||||
Reference in New Issue
Block a user