Documentation
¶
Overview ¶
Package wasm provides server-side stubs for the WASM reactive runtime. Import this package with a dot import in page files so the state function compiles server-side:
import . "github.com/felipegenef/gothicframework/v2/pkg/wasm"
At WASM compile time the framework substitutes the real TinyGo implementation (signal tracking, DOM manipulation, JS event registration) from the embedded wasm-runtime module. On the server these are all no-ops.
Index ¶
- Variables
- func AddClass(id, className string)
- func AddEventListener(el JSValue, event string, fn func())
- func AddEventListenerWithEvent(el JSValue, event string, fn func(JSValue))
- func AppendChild(parent, child JSValue)
- func ClickElement(el JSValue)
- func ConsoleLog(args ...any)
- func CookieDelete(key string)
- func CookieGet(key string) string
- func CookieSet(key, value string, opts ...CookieOptions)
- func CopyBytesToGo(dst []byte, src JSValue) int
- func CopyBytesToJS(dst JSValue, src []byte) int
- func CreateTopic[T any](zero T, cfg TopicConfig) func() interface{}
- func CreateWasmBoolFunc(name string, fn func(bool))
- func CreateWasmFunc(name string, fn func())
- func CreateWasmStringFunc(name string, fn func(string))
- func ExecJS(script string)
- func ExtractRuntime(destDir string) error
- func Fetch(url string, config ...FetchConfig) (string, error)
- func FetchBytes(url string, config ...FetchConfig) ([]byte, error)
- func GetFileBytes(id string) []byte
- func GetValue(id string) string
- func GoBack()
- func LocalStorageGet(key string) string
- func LocalStorageRemove(key string)
- func LocalStorageSet(key, value string)
- func Navigate(url string)
- func PushState(url, title string)
- func Reload()
- func RemoveClass(id, className string)
- func RemoveElement(el JSValue)
- func SessionStorageGet(key string) string
- func SessionStorageRemove(key string)
- func SessionStorageSet(key, value string)
- func SetAttr(id, attr, value string)
- func SetHTML(id, html string)
- func SetStyle(id, property, value string)
- func SetText(id, value string)
- func SetValue(id, value string)
- func ToggleClass(id, className string)
- func TriggerDownload(filename string, data []byte, mimeType string)
- func WriteClipboard(text string)
- type Compression
- type CookieOptions
- type Decoder
- func (d *Decoder) Bool() bool
- func (d *Decoder) Bytes() []byte
- func (d *Decoder) F32() float32
- func (d *Decoder) F64() float64
- func (d *Decoder) I32() int32
- func (d *Decoder) I64() int64
- func (d *Decoder) String() string
- func (d *Decoder) U8() uint8
- func (d *Decoder) U16() uint16
- func (d *Decoder) U32() uint32
- func (d *Decoder) U64() uint64
- type Encoder
- func (e *Encoder) Bool(v bool)
- func (e *Encoder) Bytes(v []byte)
- func (e *Encoder) F32(v float32)
- func (e *Encoder) F64(v float64)
- func (e *Encoder) I32(v int32)
- func (e *Encoder) I64(v int64)
- func (e *Encoder) String(v string)
- func (e *Encoder) U8(v uint8)
- func (e *Encoder) U16(v uint16)
- func (e *Encoder) U32(v uint32)
- func (e *Encoder) U64(v uint64)
- type FetchConfig
- type JSValue
- func CreateElement(tag string) JSValue
- func CreateWasmFuncWithReturn(name string, fn func(this JSValue, args []JSValue) any) JSValue
- func Document() JSValue
- func GetElementById(id string) JSValue
- func JS() JSValue
- func QuerySelector(sel string) JSValue
- func QuerySelectorAll(sel string) JSValue
- func Window() JSValue
- func (v JSValue) Bool() bool
- func (v JSValue) Call(method string, args ...any) JSValue
- func (v JSValue) Float() float64
- func (v JSValue) Get(key string) JSValue
- func (v JSValue) Index(i int) JSValue
- func (v JSValue) Int() int
- func (v JSValue) IsNull() bool
- func (v JSValue) IsUndefined() bool
- func (v JSValue) Length() int
- func (v JSValue) New(args ...any) JSValue
- func (v JSValue) Set(key string, val any)
- func (v JSValue) SetIndex(i int, val any)
- func (v JSValue) String() string
- func (v JSValue) Truthy() bool
- type Observable
- type ObservableField
- type SharedTopicObservable
- type Subscription
- type TopicConfig
- type TopicKey
- type WasmCompiler
Constants ¶
This section is empty.
Variables ¶
var RuntimeFS embed.FS
Functions ¶
func AddEventListener ¶
AddEventListener attaches a persistent event listener to el for the given event name. fn is called with no arguments each time the event fires. The listener stays alive for the lifetime of the page — it is never removed automatically.
Common use cases: reacting to browser events (click, input, toggle) or framework events (htmx:afterSwap, htmx:beforeSwap) on any JSValue element including Document() and Window().
Example:
body := Document().Get("body")
AddEventListener(body, "htmx:afterSwap", func() {
// re-sync DOM after HTMX swaps content
})
details := QuerySelector("details#menu")
AddEventListener(details, "toggle", func() {
// react to open/close state changes
})
func AddEventListenerWithEvent ¶
AddEventListenerWithEvent attaches a persistent event listener to el for the given event name. fn receives the browser Event object as a JSValue, giving access to event properties and methods. Use this when you need to inspect or interact with the event itself — call preventDefault, read event.target, event.key, event.clientX, event.detail, etc. The listener stays alive for the lifetime of the page — it is never removed automatically.
Example:
AddEventListenerWithEvent(form, "submit", func(e JSValue) {
e.Call("preventDefault") // stop the default form submission
val := e.Get("target").Get("value").String()
})
AddEventListenerWithEvent(Document(), "keydown", func(e JSValue) {
if e.Get("key").String() == "Escape" {
// close modal, etc.
}
})
func AppendChild ¶
func AppendChild(parent, child JSValue)
Element tree helpers — server-side no-ops.
func ClickElement ¶
func ClickElement(el JSValue)
func ConsoleLog ¶
func ConsoleLog(args ...any)
func CookieDelete ¶
func CookieDelete(key string)
func CookieSet ¶
func CookieSet(key, value string, opts ...CookieOptions)
Cookie helpers — server-side no-ops.
func CopyBytesToGo ¶
func CopyBytesToJS ¶
func CreateTopic ¶
func CreateTopic[T any](zero T, cfg TopicConfig) func() interface{}
CreateTopic declares a topic. The CLI AST scanner detects this call and generates the concrete typed accessor. Server-side this is a no-op stub.
func CreateWasmBoolFunc ¶
func CreateWasmFunc ¶
func CreateWasmFunc(name string, fn func())
func CreateWasmStringFunc ¶
func ExecJS ¶
func ExecJS(script string)
ExecJS executes a JavaScript snippet in the browser. Server-side no-op.
func ExtractRuntime ¶
ExtractRuntime writes the embedded WASM runtime source files into destDir so TinyGo can compile against them. The resulting layout is:
destDir/
go.mod (module wasm-runtime, go 1.21)
runtime/
signal.go
effect.go
...
The caller is responsible for removing destDir when the build is done.
func Fetch ¶
func Fetch(url string, config ...FetchConfig) (string, error)
Fetch makes an HTTP request using the browser's fetch API and blocks until complete. Config is optional — omit for a simple GET request. Must be called from inside a goroutine or CreateWasmFunc handler.
Example:
body, err := Fetch("https://api.example.com/todos/1")
body, err := Fetch("https://api.example.com/todos", FetchConfig{
Method: "POST",
Headers: map[string]string{"Content-Type": "application/json"},
Body: `{"title":"foo"}`,
})
func FetchBytes ¶
func FetchBytes(url string, config ...FetchConfig) ([]byte, error)
FetchBytes makes an HTTP request and returns the response as raw bytes. Use this instead of Fetch when the response is binary (images, PDFs, ZIPs, etc.). Config is optional — omit for a simple GET. Must be called from inside a goroutine or CreateWasmFunc handler.
func GetFileBytes ¶
GetFileBytes reads the contents of the first file selected in a <input type="file"> element. Returns nil if the element is not found, no file is selected, or reading fails.
func LocalStorageGet ¶
func LocalStorageRemove ¶
func LocalStorageRemove(key string)
func LocalStorageSet ¶
func LocalStorageSet(key, value string)
LocalStorage helpers — server-side no-ops.
func RemoveClass ¶
func RemoveClass(id, className string)
func RemoveElement ¶
func RemoveElement(el JSValue)
func SessionStorageGet ¶
func SessionStorageRemove ¶
func SessionStorageRemove(key string)
func SessionStorageSet ¶
func SessionStorageSet(key, value string)
SessionStorage helpers — server-side no-ops.
func ToggleClass ¶
func ToggleClass(id, className string)
func TriggerDownload ¶
TriggerDownload prompts the browser to download `data` as a file named `filename` with the given MIME type. Server-side no-op.
func WriteClipboard ¶
func WriteClipboard(text string)
WriteClipboard writes text to the system clipboard. Server-side no-op.
Types ¶
type Compression ¶
type Compression int
Compression is the compression algorithm used for a topic's WASM payload.
const ( GZIP Compression = iota // default BROTLI Compression = iota )
type CookieOptions ¶
type CookieOptions struct {
MaxAge int // seconds; 0 = session cookie
Path string // defaults to "/"
SameSite string // "Strict", "Lax", or "None"
Secure bool
}
CookieOptions configures CookieSet behaviour.
type Decoder ¶
Decoder reads a little-endian binary stream (server-side stub — mirrors runtime.Decoder).
type Encoder ¶
type Encoder struct{ Buf []byte }
Encoder writes a little-endian binary stream (server-side stub — mirrors runtime.Encoder).
func NewEncoder ¶
type FetchConfig ¶
type FetchConfig struct {
Method string // "GET", "POST", "PUT", "DELETE" — default: "GET"
Headers map[string]string // request headers
Body string // request body (for POST/PUT) — text body
BodyBytes []byte // binary body — used when Body is empty
Query map[string]string // query parameters appended to the URL
}
FetchConfig configures an HTTP request made via Fetch.
type JSValue ¶
type JSValue struct{}
JSValue is a server-side stub for syscall/js.Value. All methods are no-ops; the real implementation lives in the WASM runtime.
func CreateElement ¶
func CreateWasmFuncWithReturn ¶ added in v2.17.4
CreateWasmFuncWithReturn registers a named global JS function that can return a value back to JS. Wraps syscall/js.FuncOf. Use when a JS library expects a callback that returns a value synchronously (e.g. option objects, formatters, renderers). The function persists for the lifetime of the page. Returns a JSValue so it can be passed directly to JS object properties.
Example:
// Register a callback and pass it as a property on a JS config object:
cb := CreateWasmFuncWithReturn("myCallback", func(this JSValue, args []JSValue) any {
return args[0].String() + "_suffix"
})
config.Set("formatter", cb)
func GetElementById ¶
func QuerySelector ¶
func QuerySelectorAll ¶
func (JSValue) IsUndefined ¶
type Observable ¶
type Observable[T any] struct { // contains filtered or unexported fields }
Observable is a typed reactive state container (server-side no-op). Similar to useState in React — holds a value and notifies observers on change.
func CreateObservable ¶
func CreateObservable[T any](initial T) *Observable[T]
CreateObservable creates an Observable with the given initial value. It is the Gothic equivalent of React's useState hook.
Example:
count := CreateObservable(0)
label := CreateObservable("hello")
count.Set(count.Get() + 1) // triggers all Observe callbacks that depend on count
func (*Observable[T]) Get ¶
func (s *Observable[T]) Get() T
Get returns the current observable value.
type ObservableField ¶
type ObservableField[T any] struct { // contains filtered or unexported fields }
ObservableField is a per-field reactive observable for a generated topic struct. Server-side stub — no broadcast, no effect tracking.
func NewObservableField ¶
func NewObservableField[T any](initial T) *ObservableField[T]
NewObservableField creates an ObservableField with the given initial value.
func (*ObservableField[T]) ApplyExternal ¶
func (f *ObservableField[T]) ApplyExternal(v T)
func (*ObservableField[T]) Get ¶
func (f *ObservableField[T]) Get() T
func (*ObservableField[T]) Peek ¶
func (f *ObservableField[T]) Peek() T
func (*ObservableField[T]) Set ¶
func (f *ObservableField[T]) Set(v T)
func (*ObservableField[T]) SetBroadcast ¶
func (f *ObservableField[T]) SetBroadcast(fn func())
type SharedTopicObservable ¶
type SharedTopicObservable[T any] struct { // contains filtered or unexported fields }
SharedTopicObservable is the internal type backing auto-generated topic constructors. Users access shared topic state via the generated accessor e.g. PageTopic() — not directly.
func (*SharedTopicObservable[T]) Get ¶
func (s *SharedTopicObservable[T]) Get() T
func (*SharedTopicObservable[T]) Set ¶
func (s *SharedTopicObservable[T]) Set(v T)
type Subscription ¶
type Subscription struct{}
Subscription is a reactive computation (server-side no-op).
func Observe ¶
func Observe(fn func(), deps ...any) *Subscription
Observe runs fn immediately and re-runs it whenever a listed dep changes. It is the Gothic equivalent of React's useEffect hook. Pass no deps to run fn exactly once with no reactive subscription.
Example:
count := CreateObservable(0)
Observe(func() {
SetText("counter", fmt.Sprintf("%d", count.Get()))
}, count)
func ObserveWithCleanup ¶
func ObserveWithCleanup(fn func() func(), deps ...any) *Subscription
ObserveWithCleanup is like Observe with a cleanup function.
func (*Subscription) Stop ¶
func (e *Subscription) Stop()
Stop deactivates an effect (no-op server-side).
type TopicConfig ¶
type TopicConfig struct {
Name string
Compression Compression // GZIP (default) or BROTLI
Compiler WasmCompiler // GothicTinyGo (default), LocalTinyGo, or Golang
SubscriberFnName string // overrides generated accessor func name (default: <StructName>Topic)
ComponentFnName string // overrides generated mount component func name (default: Add<StructName>Topic)
}
TopicConfig holds per-topic configuration. The CLI AST scanner reads the Name and Compression fields from CreateTopic call sites to drive code generation.
type TopicKey ¶
TopicKey is a typed key used by the auto-generated topic system. Users never construct these directly — the CLI generates them from src/topics/*.go.
type WasmCompiler ¶ added in v2.17.2
type WasmCompiler int
WasmCompiler selects the WASM build toolchain for a topic.
const ( GothicTinyGo WasmCompiler = iota // default: embedded TinyGo binary LocalTinyGo // system tinygo binary in PATH Golang // GOOS=js GOARCH=wasm standard Go compiler )
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
parity
This file is a byte-identical copy of pkg/wasm/wasm-runtime/runtime/codec.go used by codec_parity_test.go to validate that the server-side stub in pkg/wasm/stubs.go and the WASM-side runtime stay in sync.
|
This file is a byte-identical copy of pkg/wasm/wasm-runtime/runtime/codec.go used by codec_parity_test.go to validate that the server-side stub in pkg/wasm/stubs.go and the WASM-side runtime stay in sync. |
|
wasm-runtime
|
|