wasm

package
v1.6.0-beta.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 22, 2026 License: MIT Imports: 7 Imported by: 0

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/gothicframework/core/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

Constants

View Source
const WireVersion byte = 1

WireVersion is the codec's frame-format version (server-side stub — mirrors runtime.WireVersion). Written as byte 0 of every top-level frame by NewEncoder and validated by NewDecoder.

Variables

View Source
var HTMX htmxAPI

HTMX is the htmx API singleton (server-side no-op).

View Source
var RuntimeFS embed.FS

Functions

func AddClass

func AddClass(id, className string)

func AddEventListener

func AddEventListener(el JSValue, event string, fn func())

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

func AddEventListenerWithEvent(el JSValue, event string, fn func(JSValue))

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 CaptureScope

func CaptureScope() string

CaptureScope returns the scope active at the call site (server-side no-op: always ""). In the WASM runtime it captures the active [data-gothic-scope] so a goroutine can re-establish it with RunInScope when its work runs later — a goroutine does not inherit the scope across a suspension point.

scope := CaptureScope()
go func() { RunInScope(scope, func() { SetText("out", result) }) }()

func ClickElement

func ClickElement(el JSValue)

func ConsoleLog

func ConsoleLog(args ...any)

func CookieDelete

func CookieDelete(key string)

func CookieGet

func CookieGet(key string) string

func CookieSet

func CookieSet(key, value string, opts ...CookieOptions)

Cookie helpers — server-side no-ops.

func CopyBytesToGo

func CopyBytesToGo(dst []byte, src JSValue) int

func CopyBytesToJS

func CopyBytesToJS(dst JSValue, src []byte) int

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 CreateWasmBoolFunc(name string, fn func(bool))

func CreateWasmFunc

func CreateWasmFunc(name string, fn func())

func CreateWasmStringFunc

func CreateWasmStringFunc(name string, fn func(string))

func Decode added in v1.4.0

func Decode[T any](r Response) (T, error)

Decode parses r's JSON body into a value of struct type T and returns it (server-side no-op: returns the zero value and nil). At WASM build time the gothic CLI REPLACES each Decode[T](resp) call with a generated, reflection-free _jsonDecode_T(resp): the CLI reads T's fields (and json tags) via go/types and emits code that reads them out of the runtime's reflection-free JSON parse — so NEITHER reflect NOR encoding/json is pulled into the TinyGo binary. This server-side stub exists only so a ClientSideState block calling Decode[T] type-checks during SSR / ScanPages.

T must be a struct type. Fields are matched by json tag (falling back to the Go field name); JSON numbers coerce to numeric fields (int64 magnitudes above 2^53 lose precision), and a missing key or JSON null yields the field's zero value. Nested structs, slices, pointers, and string-keyed maps are supported; unsupported field types decode as their zero value.

Example:

resp, err := Fetch("/api/user/1")
if err == nil && resp.OK() {
    user, err := Decode[User](resp)
    if err == nil { SetText("name", user.Name) }
}

func DurableKey

func DurableKey() string

DurableKey returns the placement's stable durable key (data-gothic-durable-key) or "" when not durable (server-side no-op: always ""). In the WASM runtime it reads the attribute off the component wrapper so DurableObserve can rehydrate from the full-Go core across a teardown→re-mount.

func DurableObserve

func DurableObserve[T any](field string, obs *Observable[T], encode func(T) string, decode func(string) T)

DurableObserve binds an observable to the core's page-session durable cache under `field` so its value SURVIVES the component's teardown→re-mount (server-side no-op). OPT-IN: when the placement has no durable key it does nothing and the observable behaves exactly as a plain one — so SSR output is identical whether or not a component opts into durability. encode/decode are the field's string codec (same shape as CustomKey).

count := CreateObservable(0)
DurableObserve("count", count, strconv.Itoa,
    func(s string) int { n, _ := strconv.Atoi(s); return n })

func Encode added in v1.4.0

func Encode[T any](v T) []byte

Encode marshals a value of struct type T to a JSON []byte, for use as a request body (server-side no-op: returns nil). It is the write-direction mirror of Decode. At WASM build time the gothic CLI REPLACES each Encode[T](v) call with a generated, reflection-free _jsonEncode_T(v): the CLI reads T's fields (and json tags) via go/types and emits code that appends their JSON by hand — so NEITHER reflect NOR encoding/json is pulled into the TinyGo binary. This server-side stub exists only so a ClientSideState block calling Encode[T] type-checks during SSR / ScanPages.

T must be a struct type, and the call MUST carry an explicit type argument (Encode[T](v)) — the build-time rewrite is syntactic and cannot recover an inferred T. Fields are emitted in struct order, keyed by json tag (falling back to the field name); `json:"-"` is skipped; `,omitempty` is ignored (the field is always written); nil slices/pointers/maps become JSON null.

Example:

body := Encode[CreateUser](CreateUser{Name: name})
Fetch("/api/users", FetchConfig{Method: "POST", BodyBytes: body})

func ExecJS

func ExecJS(script string)

ExecJS executes a JavaScript snippet in the browser. Server-side no-op.

func ExtractRuntime

func ExtractRuntime(destDir string) error

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 FetchAsync added in v1.4.0

func FetchAsync(url string, cfg FetchConfig, done func(Response, error))

FetchAsync makes an HTTP request and invokes done(Response, error) when it completes, without blocking (server-side no-op). done runs inside the scope active at the call site so DOM writes hit the right subtree, and the request is aborted on component teardown. Use it when a blocking Fetch would stall a handler.

Example:

FetchAsync("/api/todos", FetchConfig{}, func(resp Response, err error) {
    if err == nil && resp.OK() {
        SetText("out", resp.Text())
    }
})

func FetchChan added in v1.4.0

func FetchChan(url string, cfg ...FetchConfig) <-chan FetchResult

FetchChan makes an HTTP request and returns a receive-only channel that yields exactly one FetchResult when it completes (server-side no-op mirror). It does not block — select on the returned channel. Use it to await one of several requests or to combine a fetch with a timeout in a select.

Example:

select {
case r := <-FetchChan("/api/todos"):
    if r.Err == nil && r.Response.OK() { SetText("out", r.Response.Text()) }
}

func GetFileBytes

func GetFileBytes(id string) []byte

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 GetValue

func GetValue(id string) string

func GoBack

func GoBack()

func LocalStorageGet

func LocalStorageGet(key string) string

func LocalStorageRemove

func LocalStorageRemove(key string)

func LocalStorageSet

func LocalStorageSet(key, value string)

LocalStorage helpers — server-side no-ops.

func Navigate(url string)

Navigation helpers — server-side no-ops.

func OnUnmount

func OnUnmount(fn func()) func()

OnUnmount registers a cleanup callback run when the component's [data-gothic-scope] element is removed from the DOM (server-side no-op). In the WASM runtime it releases things created outside the component's subtree (document listeners, timers, topic mounts, in-flight fetch AbortControllers). It returns a deregister func (a no-op here) that drops the callback early once it becomes dead weight — callers may ignore it.

func PushState

func PushState(url, title string)

func Reload

func Reload()

func RemoveClass

func RemoveClass(id, className string)

func RemoveElement

func RemoveElement(el JSValue)

func RunInScope

func RunInScope(id string, fn func())

RunInScope runs fn with the given scope active, restoring the previous scope afterwards (server-side no-op: fn is not executed, matching Observe). Pair it with CaptureScope to carry a scope into a goroutine or deferred callback.

func SessionStorageGet

func SessionStorageGet(key string) string

func SessionStorageRemove

func SessionStorageRemove(key string)

func SessionStorageSet

func SessionStorageSet(key, value string)

SessionStorage helpers — server-side no-ops.

func SetAttr

func SetAttr(id, attr, value string)

func SetHTML

func SetHTML(id, html string)

func SetStyle

func SetStyle(id, property, value string)

func SetText

func SetText(id, value string)

func SetValue

func SetValue(id, value string)

func ToggleClass

func ToggleClass(id, className string)

func TriggerDownload

func TriggerDownload(filename string, data []byte, mimeType string)

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 AjaxOpts added in v1.4.0

type AjaxOpts struct {
	Target string            // CSS selector for where to swap the response
	Source string            // CSS selector for the request's source element
	Swap   SwapStrategy      // swap style for the response
	Values map[string]string // extra values sent with the request
}

AjaxOpts is the optional context for HTMX.Ajax (maps onto htmx's ajax() context object). Zero fields are omitted.

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

type Decoder struct {
	Buf []byte
	Pos int
	Err error
}

Decoder reads a little-endian binary stream (server-side stub — mirrors runtime.Decoder).

func NewDecoder

func NewDecoder(buf []byte) *Decoder

NewDecoder opens a frame produced by NewEncoder: it validates the WireVersion header byte and positions Pos after it, or sets Err on an empty/wrong-version buffer without panicking (mirrors runtime.NewDecoder).

func (*Decoder) Bool

func (d *Decoder) Bool() bool

func (*Decoder) Bytes

func (d *Decoder) Bytes() []byte

func (*Decoder) F32

func (d *Decoder) F32() float32

func (*Decoder) F64

func (d *Decoder) F64() float64

func (*Decoder) I32

func (d *Decoder) I32() int32

func (*Decoder) I64

func (d *Decoder) I64() int64

func (*Decoder) String

func (d *Decoder) String() string

func (*Decoder) U8

func (d *Decoder) U8() uint8

func (*Decoder) U16

func (d *Decoder) U16() uint16

func (*Decoder) U32

func (d *Decoder) U32() uint32

func (*Decoder) U64

func (d *Decoder) U64() uint64

type Encoder

type Encoder struct{ Buf []byte }

Encoder writes a little-endian binary stream (server-side stub — mirrors runtime.Encoder).

func NewEncoder

func NewEncoder(cap int) *Encoder

NewEncoder opens a new frame whose buffer already carries the WireVersion header byte at position 0 (mirrors runtime.NewEncoder).

func (*Encoder) Bool

func (e *Encoder) Bool(v bool)

func (*Encoder) Bytes

func (e *Encoder) Bytes(v []byte)

func (*Encoder) F32

func (e *Encoder) F32(v float32)

func (*Encoder) F64

func (e *Encoder) F64(v float64)

func (*Encoder) I32

func (e *Encoder) I32(v int32)

func (*Encoder) I64

func (e *Encoder) I64(v int64)

func (*Encoder) String

func (e *Encoder) String(v string)

func (*Encoder) U8

func (e *Encoder) U8(v uint8)

func (*Encoder) U16

func (e *Encoder) U16(v uint16)

func (*Encoder) U32

func (e *Encoder) U32(v uint32)

func (*Encoder) U64

func (e *Encoder) U64(v uint64)

type Event added in v1.4.0

type Event = JSValue

Event is the browser Event passed to On/OnGlobal handlers (server-side: JSValue stub). In the WASM runtime it exposes the DOM Event — call e.Get("detail"), e.Get("target"), e.Call("preventDefault"), etc.

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 FetchResult added in v1.4.0

type FetchResult struct {
	Response Response
	Err      error
}

FetchResult pairs a Response with its error for delivery over a channel (server-side no-op mirror of the WASM runtime type). It is what FetchChan sends: exactly one FetchResult per request.

type HtmxEvent added in v1.4.0

type HtmxEvent string

HtmxEvent is a string-backed htmx event name. The consts are the full htmx 2.0.3 event catalog; a custom/extension event is reachable via a string cast, e.g. HtmxEvent("htmx:sse:message").

const (
	EvtAbort                     HtmxEvent = "htmx:abort"
	EvtAfterOnLoad               HtmxEvent = "htmx:afterOnLoad"
	EvtAfterProcessNode          HtmxEvent = "htmx:afterProcessNode"
	EvtAfterRequest              HtmxEvent = "htmx:afterRequest"
	EvtAfterSettle               HtmxEvent = "htmx:afterSettle"
	EvtAfterSwap                 HtmxEvent = "htmx:afterSwap"
	EvtBadResponseURL            HtmxEvent = "htmx:badResponseUrl"
	EvtBeforeCleanupElement      HtmxEvent = "htmx:beforeCleanupElement"
	EvtBeforeHistorySave         HtmxEvent = "htmx:beforeHistorySave"
	EvtBeforeHistoryUpdate       HtmxEvent = "htmx:beforeHistoryUpdate"
	EvtBeforeOnLoad              HtmxEvent = "htmx:beforeOnLoad"
	EvtBeforeProcessNode         HtmxEvent = "htmx:beforeProcessNode"
	EvtBeforeRequest             HtmxEvent = "htmx:beforeRequest"
	EvtBeforeSend                HtmxEvent = "htmx:beforeSend"
	EvtBeforeSwap                HtmxEvent = "htmx:beforeSwap"
	EvtBeforeTransition          HtmxEvent = "htmx:beforeTransition"
	EvtConfigRequest             HtmxEvent = "htmx:configRequest"
	EvtConfirm                   HtmxEvent = "htmx:confirm"
	EvtError                     HtmxEvent = "htmx:error"
	EvtEvalDisallowedError       HtmxEvent = "htmx:evalDisallowedError"
	EvtEventFilterError          HtmxEvent = "htmx:eventFilter:error"
	EvtHistoryCacheError         HtmxEvent = "htmx:historyCacheError"
	EvtHistoryCacheMiss          HtmxEvent = "htmx:historyCacheMiss"
	EvtHistoryCacheMissLoad      HtmxEvent = "htmx:historyCacheMissLoad"
	EvtHistoryCacheMissLoadError HtmxEvent = "htmx:historyCacheMissLoadError"
	EvtHistoryItemCreated        HtmxEvent = "htmx:historyItemCreated"
	EvtHistoryRestore            HtmxEvent = "htmx:historyRestore"
	EvtInvalidPath               HtmxEvent = "htmx:invalidPath"
	EvtLoad                      HtmxEvent = "htmx:load"
	EvtOnLoadError               HtmxEvent = "htmx:onLoadError"
	EvtOobAfterSwap              HtmxEvent = "htmx:oobAfterSwap"
	EvtOobBeforeSwap             HtmxEvent = "htmx:oobBeforeSwap"
	EvtOobErrorNoTarget          HtmxEvent = "htmx:oobErrorNoTarget"
	EvtPrompt                    HtmxEvent = "htmx:prompt"
	EvtPushedIntoHistory         HtmxEvent = "htmx:pushedIntoHistory"
	EvtReplacedInHistory         HtmxEvent = "htmx:replacedInHistory"
	EvtResponseError             HtmxEvent = "htmx:responseError"
	EvtRestored                  HtmxEvent = "htmx:restored"
	EvtSendAbort                 HtmxEvent = "htmx:sendAbort"
	EvtSendError                 HtmxEvent = "htmx:sendError"
	EvtSwapError                 HtmxEvent = "htmx:swapError"
	EvtSyntaxError               HtmxEvent = "htmx:syntax:error"
	EvtTargetError               HtmxEvent = "htmx:targetError"
	EvtTimeout                   HtmxEvent = "htmx:timeout"
	EvtTrigger                   HtmxEvent = "htmx:trigger"
	EvtValidateURL               HtmxEvent = "htmx:validateUrl"
	EvtValidationValidate        HtmxEvent = "htmx:validation:validate"
	EvtValidationFailed          HtmxEvent = "htmx:validation:failed"
	EvtValidationHalted          HtmxEvent = "htmx:validation:halted"
	EvtXHRAbort                  HtmxEvent = "htmx:xhr:abort"
	EvtXHRLoadstart              HtmxEvent = "htmx:xhr:loadstart"
	EvtXHRLoadend                HtmxEvent = "htmx:xhr:loadend"
	EvtXHRProgress               HtmxEvent = "htmx:xhr:progress"
)

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 CreateElement(tag string) JSValue

func CreateWasmFuncWithReturn

func CreateWasmFuncWithReturn(name string, fn func(this JSValue, args []JSValue) any) JSValue

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 Document

func Document() JSValue

func GetElementById

func GetElementById(id string) JSValue

func JS

func JS() JSValue

func QuerySelector

func QuerySelector(sel string) JSValue

func QuerySelectorAll

func QuerySelectorAll(sel string) JSValue

func Window

func Window() JSValue

func (JSValue) Bool

func (v JSValue) Bool() bool

func (JSValue) Call

func (v JSValue) Call(method string, args ...any) JSValue

func (JSValue) Float

func (v JSValue) Float() float64

func (JSValue) Get

func (v JSValue) Get(key string) JSValue

func (JSValue) Index

func (v JSValue) Index(i int) JSValue

func (JSValue) Int

func (v JSValue) Int() int

func (JSValue) IsNull

func (v JSValue) IsNull() bool

func (JSValue) IsUndefined

func (v JSValue) IsUndefined() bool

func (JSValue) Length

func (v JSValue) Length() int

func (JSValue) New

func (v JSValue) New(args ...any) JSValue

func (JSValue) Set

func (v JSValue) Set(key string, val any)

func (JSValue) SetIndex

func (v JSValue) SetIndex(i int, val any)

func (JSValue) String

func (v JSValue) String() string

func (JSValue) Truthy

func (v JSValue) Truthy() bool

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.

func (*Observable[T]) Set

func (s *Observable[T]) Set(v T)

Set updates the 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 Response added in v1.4.0

type Response struct {
	Status  int               // HTTP status code
	Headers map[string]string // response headers
	Body    []byte            // raw response body bytes
}

Response is the result of a Fetch call (server-side no-op mirror of the WASM runtime type). Body holds the raw response bytes; use Text()/Bytes()/OK().

func Fetch

func Fetch(url string, config ...FetchConfig) (Response, 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. The body is read as raw bytes; use Response.Text() for a string view, Response.Bytes() for binary, Response.OK() for a 2xx check. Must be called from inside a goroutine or CreateWasmFunc handler.

Example:

resp, err := Fetch("https://api.example.com/todos/1")
if err == nil && resp.OK() {
    body := resp.Text()
}

resp, err := Fetch("https://api.example.com/todos", FetchConfig{
    Method:  "POST",
    Headers: map[string]string{"Content-Type": "application/json"},
    Body:    `{"title":"foo"}`,
})

func (Response) Bytes added in v1.4.0

func (r Response) Bytes() []byte

Bytes returns the raw response body bytes.

func (Response) MapAny added in v1.4.0

func (r Response) MapAny() (map[string]any, error)

MapAny parses the response body as a JSON object into a map[string]any (server-side no-op mirror: always nil, nil). In the WASM runtime it uses a reflection-free, TinyGo-safe parser that never panics on malformed input — invalid JSON returns a non-nil error. The top-level value must be a JSON object; nested values are coerced to map[string]any / []any / string / float64 (int64 > 2^53 loses precision) / bool / nil.

Example:

resp, err := Fetch("/api/user/1")
if err == nil && resp.OK() {
    m, err := resp.MapAny()
    if err == nil { name, _ := m["name"].(string) }
}

func (Response) OK added in v1.4.0

func (r Response) OK() bool

OK reports whether the response status is in the 2xx (200..299) range.

func (Response) Text added in v1.4.0

func (r Response) Text() string

Text returns the response body decoded as a UTF-8 string.

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 SwapStrategy added in v1.4.0

type SwapStrategy string

SwapStrategy is a string-backed htmx swap style (the hx-swap vocabulary). The eight canonical values give autocomplete; a custom style is reachable via a string cast, e.g. SwapStrategy("innerHTML show:top").

const (
	InnerHTML   SwapStrategy = "innerHTML"   // replace the target's inner HTML (default)
	OuterHTML   SwapStrategy = "outerHTML"   // replace the entire target element
	BeforeBegin SwapStrategy = "beforebegin" // insert before the target element
	AfterBegin  SwapStrategy = "afterbegin"  // insert as the target's first child
	BeforeEnd   SwapStrategy = "beforeend"   // insert as the target's last child
	AfterEnd    SwapStrategy = "afterend"    // insert after the target element
	Delete      SwapStrategy = "delete"      // delete the target regardless of response
	None        SwapStrategy = "none"        // do not append the response content
)

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)
}

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

type TopicKey[T any] struct {
	Name string
	// contains filtered or unexported fields
}

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.

func AutoKey

func AutoKey[T any](name string) TopicKey[T]

AutoKey is rewritten to BinaryKey by the CLI before TinyGo compiles. Server-side this is a no-op stub so the code compiles.

func BinaryKey

func BinaryKey[T any](name string, encode func(T, *Encoder), decode func(*Decoder) T) TopicKey[T]

BinaryKey is used exclusively by CLI-generated code in src/topics/topic_gen.go.

type WasmCompiler

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
Command core-runtime is the Gothic Framework full-Go STATIC CORE: a prebuilt, type-agnostic RPC / registration hub.
Command core-runtime is the Gothic Framework full-Go STATIC CORE: a prebuilt, type-agnostic RPC / registration hub.
protocol
Package protocol holds the PURE, host-testable decision logic of the Gothic full-Go static core's control plane.
Package protocol holds the PURE, host-testable decision logic of the Gothic full-Go static core's control plane.
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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL