add WASM blazor-like thing
This commit is contained in:
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)
|
||||
}
|
||||
Reference in New Issue
Block a user