ui

package
v4.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2026 License: MIT Imports: 25 Imported by: 0

README

GWC | Ui Library

GoWebComponents (GWC)

High-Level Overview

The ui library is the primary GWC UI runtime surface, including node construction, rendering orchestration, effects, and hydration helpers.

Start Here

Use ui when you need:

  • component composition and rendering
  • hooks and local state
  • hydration or SSR bootstrap helpers
  • form helpers, async boundaries, overlays, and worker-task helpers

Recommended reading order:

  1. ../README.md for the repo-level picture
  2. ../docs/REFERENCE_MANUAL/04-ui-rendering-and-hooks.md for the guided ui learning path
  3. This README for the package surface
  4. ../examples/README.md for runnable API examples

If you are debugging implementation internals rather than using the public surface, jump to ../internal/runtime/README.md instead of reading the API list below as architecture documentation.

CSP Nonces

Use RenderBootstrapScriptWithOptions or RenderBootstrapReferenceScriptWithOptions with SSRScriptOptions.Nonce when serving under strict CSP. The nonce is HTML-escaped and applied to generated bootstrap script tags; streamed SSR boundary scripts accept the matching nonce through SSRStreamOptions.ScriptNonce.

Public APIs

github.com/monstercameron/GoWebComponents/ui (package ui)
  • Functions: AccessibleOverlay, ActiveDescendant, ActiveID, ActiveIndex, AddStateUpdatePayload, AnalyzeSSRBootstrapSize, Announce, ApplySSRStateUpdate, ApplyServerActionResult, ApplyServerErrors, Assertive, AssertiveID, AsyncBoundary, Cancel, Clear, Closed, Component, CorrelationIDFromContext, CreateContext, CreateElement, Default, Dirty, DirtyAny, Dispatch, Error, Errors, ExtractFiles, FieldMessage, FieldStatus, FileFromJSValue, FocusByID, FocusFirst, FocusFirstError, FocusSelector, FormError, FormErrors, FormField, FormMessage, Fragment, Get, GetKey, GetKeyCode, GetValue, HasErrors, HasFieldError, HasRedirect, HasRefresh, Header, HotReloadBoundary, Hydrate, HydrateInto, If, InspectBootstrapPayloads, IntentPending, IsActive, IsChecked, IsValid, JSValue, LastModified, Lazy, MarshalSSRBootstrap, MarshalSSRBootstrapBinary, MarshalSSRBootstrapBinaryObserved, MarshalSSRBootstrapObserved, MarshalSSRStateUpdateBinary, MarshalSSRStateUpdateText, Match, MoveEnd, MoveHome, MoveNext, MovePrevious, Name, NewCSRFToken, NewSSRBootstrapBudget, ObserveSSR, Ok, OnKeyDown, Overlay, Pending, Polite, PoliteID, Portal, PreventDefault, ReactiveRegion, ReadBootstrapPayload, ReadBootstrapReference, ReadBootstrapReferenceScript, ReadBootstrapScript, ReadCacheBootstrapSeed, ReadFormBootstrapDefaults, ReadRouteBootstrapData, ReadSessionBootstrapHint, RedirectLocation, Region, RegisterBootstrapPayload, RegisterCacheBootstrapSeed, RegisterFormBootstrapDefaults, RegisterRouteBootstrapData, RegisterSessionBootstrapHint, Reload, RememberActive, Render, RenderBootstrapReferenceScript, RenderBootstrapScript, RenderBootstrapScriptObserved, RenderInto, RenderToString, RenderToStringObserved, Reset, Restore, SSRCorrelationMiddleware, SSRObservabilityOptionsFromContext, SSRObservationAttributes, Set, SetActive, SetBootstrapCorrelationID, SetErrors, SetField, SetFormError, SetSubmitIntent, Size, Start, StartTransition, StopPropagation, Submit, SubmitError, SubmitIntent, SubmitWithIntent, Submitted, Submitting, TabIndex, Text, Touch, Touched, TouchedAny, TraceContextFromContext, Traceparent, Type, UnmarshalSSRBootstrap, UnmarshalSSRBootstrapBinary, UnmarshalSSRBootstrapReference, UnmarshalSSRStateUpdateBinary, UnmarshalSSRStateUpdateText, UnsupportedOnServer, Update, UseAnnouncer, UseCallback, UseChannel, UseCompositeNavigation, UseContext, UseDebounced, UseDeferredValue, UseEffect, UseEvent, UseFocusManager, UseFocusTrap, UseForm, UseId, UseLazyNode, UseMemo, UseOverlayStack, UsePrevious, UseReducer, UseRef, UseState, UseTask, UseThrottled, UseTransition, UseWorkerTask, Validate, ValidateAsync, ValidateIntent, Validated, Validating, Value, When, WithCorrelationID, WithW3CTraceContext, WrapHandler
  • Types: AccessibleOverlayProps, AnnouncementMode, Announcer, AsyncBoundaryProps, CSRFToken, ChangeEvent, Channel, CompositeItem, CompositeNavigation, CompositeNavigationOptions, Context, ContextProvider, ContextProviderProps, Debounced, Element, ErrorBoundaryProps, Event, FieldErrors, FieldStatus, File, FocusEvent, FocusManager, FocusOptions, FocusTrapOptions, Form, FormEvent, Handler, HotReloadBoundaryProps, HydrationOptions, InputEvent, KeyboardEvent, LazyNode, LazyNodeState, LazyProps, MatchBuilder, MouseEvent, Node, NodeFactory, OverlayKind, OverlayProps, OverlayStack, OverlayStackOptions, PortalProps, PortalTarget, Previous, ReactiveSource, Reducer, Ref, SSRBootstrap, SSRBootstrapBudget, SSRBootstrapMetrics, SSRBootstrapReference, SSRBootstrapSizeReport, SSRHydrationMetrics, SSRI18nBootstrap, SSRI18nMessage, SSRObservabilityOptions, SSRObservation, SSRPayloadEncoding, SSRPayloadEnvelope, SSRPayloadFilter, SSRPayloadKind, SSRPayloadMetadata, SSRPayloadOptions, SSRPayloadReusePolicy, SSRPayloadScope, SSRPayloadValue, SSRRenderMetrics, SSRRouteBootstrap, SSRStateUpdate, ServerActionFlash, ServerActionOutcome, ServerActionRedirect, ServerActionRefresh, ServerActionResult, ServerFormErrors, State, Task, TaskState, Throttled, Transition, W3CTraceContext, WorkerTask, WorkerTaskState
  • Variables: ErrorBoundary
  • Constants: AnnouncementAssertive, AnnouncementPolite, CurrentSSRBootstrapVersion, CurrentSSRStateUpdateVersion, DefaultBootstrapReferenceScriptID, DefaultBootstrapScriptID, DefaultCSRFFormFieldName, DefaultCSRFHeaderName, DefaultRouteBootstrapPayloadKey, OverlayKindCustom, OverlayKindDialog, OverlayKindMenu, OverlayKindPopover, OverlayKindSheet, OverlayKindTooltip, SSRBootstrapFormatCBOR, SSRBootstrapFormatJSON, SSRPayloadEncodingBinary, SSRPayloadEncodingCBOR, SSRPayloadEncodingJSON, SSRPayloadEncodingText, SSRPayloadEncodingTimeRFC3339, SSRPayloadEncodingTimeUnixNano, SSRPayloadKindCacheSeed, SSRPayloadKindData, SSRPayloadKindFormDefaults, SSRPayloadKindRouteData, SSRPayloadKindSessionHint, SSRPayloadReuseClientOwned, SSRPayloadReuseRevalidateAfterResume, SSRPayloadReuseTrustOnFirstResume, SSRPayloadScopeApp, SSRPayloadScopeRoute, SSRPayloadScopeSubtree, ServerActionOutcomeAuthError, ServerActionOutcomeRedirect, ServerActionOutcomeRetryableError, ServerActionOutcomeSuccess, ServerActionOutcomeValidationError

Subfiles And Purpose

  • accessibility_native.go - Native (non-WASM) implementation for accessibility
  • accessibility_shared.go - Core implementation for accessibility_shared
  • accessibility_wasm.go - WebAssembly-specific implementation for accessibility
  • bootstrap_wasm.go - WebAssembly-specific implementation for bootstrap
  • branching.go - Core implementation for branching
  • component_handle_shared.go - Core implementation for component_handle_shared
  • component_handle_test.go - Tests for component_handle behavior
  • context_shared.go - Core implementation for context_shared
  • correlation_native.go - Native (non-WASM) implementation for correlation
  • correlation_native_test.go - Tests for correlation_native behavior
  • doc.go - Package-level Go documentation
  • error_boundary_shared.go - Core implementation for error_boundary_shared
  • file_native.go - Native (non-WASM) implementation for file
  • file_wasm.go - WebAssembly-specific implementation for file
  • form.go - Core implementation for form
  • form_native.go - Native (non-WASM) implementation for form
  • form_native_test.go - Tests for form_native behavior
  • hot_reload_boundary.go - Core implementation for hot_reload_boundary
  • hot_reload_boundary_shared.go - Core implementation for hot_reload_boundary_shared
  • hot_reload_boundary_test.go - Tests for hot_reload_boundary behavior
  • hydration.go - Core implementation for hydration
  • overlay.go - Core implementation for overlay
  • overlay_manager_test.go - Tests for overlay_manager behavior
  • overlay_native.go - Native (non-WASM) implementation for overlay
  • overlay_runtime_wasm.go - WebAssembly-specific implementation for overlay_runtime
  • overlay_subscribe_wasm.go - WebAssembly-specific implementation for overlay_subscribe
  • overlay_wasm.go - WebAssembly-specific implementation for overlay
  • panic_logging.go - Core implementation for panic_logging
  • panic_logging_native.go - Native (non-WASM) implementation for panic_logging
  • shared_helpers_test.go - Tests for shared_helpers behavior
  • ssr_bootstrap.go - Core implementation for ssr_bootstrap
  • ssr_bootstrap_test.go - Tests for ssr_bootstrap behavior
  • ssr_observability.go - Core implementation for ssr_observability
  • ssr_transfer.go - Core implementation for ssr_transfer
  • ssr_transfer_additional_test.go - Tests for ssr_transfer_additional behavior
  • ssr_transfer_test.go - Tests for ssr_transfer behavior
  • ui.go - Core implementation for ui
  • ui_native.go - Native (non-WASM) implementation for ui
  • ui_native_additional_test.go - Tests for ui_native_additional behavior
  • ui_native_benchmark_test.go - Tests for ui_native_benchmark behavior
  • ui_native_test.go - Tests for ui_native behavior
  • ui_wasm_test.go - Tests for ui_wasm behavior
  • worker_wasm.go - WebAssembly-specific implementation for worker

File Map

ui/
|-- accessibility_native.go
|-- accessibility_shared.go
|-- accessibility_wasm.go
|-- bootstrap_wasm.go
|-- branching.go
|-- component_handle_shared.go
|-- component_handle_test.go
|-- context_shared.go
|-- correlation_native.go
|-- correlation_native_test.go
|-- doc.go
|-- error_boundary_shared.go
|-- file_native.go
|-- file_wasm.go
|-- form.go
|-- form_native.go
|-- form_native_test.go
|-- hot_reload_boundary.go
|-- hot_reload_boundary_shared.go
|-- hot_reload_boundary_test.go
|-- hydration.go
|-- overlay.go
|-- overlay_manager_test.go
|-- overlay_native.go
|-- overlay_runtime_wasm.go
|-- overlay_subscribe_wasm.go
|-- overlay_wasm.go
|-- panic_logging.go
|-- panic_logging_native.go
|-- shared_helpers_test.go
|-- ssr_bootstrap.go
|-- ssr_bootstrap_test.go
|-- ssr_observability.go
|-- ssr_transfer.go
|-- ssr_transfer_additional_test.go
|-- ssr_transfer_test.go
|-- ui.go
|-- ui_native.go
|-- ui_native_additional_test.go
|-- ui_native_benchmark_test.go
|-- ui_native_test.go
|-- ui_wasm_test.go
\-- worker_wasm.go

Documentation

Overview

UseAnnouncer provides an application-local live-region helper for polite and assertive announcements. It is intended for validation feedback, route or async status updates, and other spoken status changes that should be wired to ordinary HTML rather than a separate runtime subsystem.

CreateContext and UseContext are intended for subtree-scoped values such as theme, auth/session state, app configuration, or service-style helpers that should not be threaded manually through many intermediate component props. Missing providers currently resolve to the context default value.

AsyncBoundary is an explicit async rendering primitive for loading and error fallbacks around a subtree. Lazy builds on top of it by resolving a ui.Node asynchronously and routing the result through the same boundary semantics. Components can also call SuspendUntil or Await during render to suspend the subtree until a data dependency signals readiness. RenderToStream turns those suspended async boundaries into fallback-first shell markup and later boundary replacement chunks, while RenderToString keeps the synchronous all-at-once HTML path. ErrorBoundary is the sibling recovery primitive for unexpected panics during render, effect, cleanup, and event-handler execution. It renders a fallback subtree instead of letting a child failure tear down the entire app tree. StartTransition and UseTransition provide a small non-urgent scheduling lane for background tree refreshes, while UseDeferredValue keeps rendering the last committed value until a transition catches up. The current scheduler deliberately does not expose a separate layout-effect hook yet; DOM-read- before-paint scenarios should continue to use explicit event sequencing and the existing UseEffect surface until a stronger concrete need appears.

The public composition model deliberately centers on ordinary children, explicit props structs, context, portals, and router layout routes. There is no first-class slot API today. If a component needs named insertion points, model them as explicit props or child subtrees rather than depending on an undocumented slot convention.

The ui package is the recommended replacement for the older dom/hooks/render split when authoring new components.

Index

Examples

Constants

View Source
const (
	SSRBootstrapFormatJSON = "json"
	SSRBootstrapFormatCBOR = "cbor"
)
View Source
const (
	// SSRStreamChunkShell identifies the initial streaming SSR shell chunk.
	SSRStreamChunkShell = runtime.SSRStreamChunkShell
	// SSRStreamChunkBoundary identifies an async boundary replacement chunk.
	SSRStreamChunkBoundary = runtime.SSRStreamChunkBoundary
)
View Source
const CurrentSSRBootstrapVersion = 1
View Source
const CurrentSSRStateUpdateVersion = 1
View Source
const DefaultBootstrapReferenceScriptID = "__GWC_BOOTSTRAP_REF__"
View Source
const DefaultBootstrapScriptID = "__GWC_BOOTSTRAP__"
View Source
const DefaultCSRFFormFieldName = "csrf_token"
View Source
const DefaultCSRFHeaderName = "X-CSRF-Token"
View Source
const (
	DefaultRouteBootstrapPayloadKey = "route:data"
)

Variables

View Source
var ErrorBoundary = &errorBoundaryComponent{boundaryType: runtime.NewErrorBoundaryType()}

ErrorBoundary creates a subtree boundary with fallback rendering and reset behavior.

Functions

func ApplySSRStateUpdate

func ApplySSRStateUpdate(parseBootstrap *SSRBootstrap, parseUpdate SSRStateUpdate) error

ApplySSRStateUpdate merges a text or binary update envelope into a bootstrap payload snapshot.

func Await

func Await[T any](parseValue SuspenseValue[T]) T

Await returns a ready value or suspends the current render until it is ready.

func BuildParallelRegionSourceIDs

func BuildParallelRegionSourceIDs(parseSources ...ReactiveSource) ([]string, error)

BuildParallelRegionSourceIDs flattens declared reactive sources into a stable public source-ID list.

func CSSEscape

func CSSEscape(parseValue string) string

CSSEscape escapes a string for safe use as a CSS identifier, implementing the WHATWG CSS.escape algorithm (https://drafts.csswg.org/cssom/#serialize-an-identifier).

Element ids returned by UseId are already CSS-safe by construction (see G29), so escaping them is unnecessary. CSSEscape exists for the general case: any id derived from user data, external systems, or string concatenation that is then fed into a CSS selector. Use it together with SelectorID:

node := document.Call("querySelector", ui.SelectorID(userProvidedID))

Passing an un-escaped arbitrary string to querySelector("#"+id) can throw a SyntaxError (and, in a wasm callback, panic the page) when the id contains a colon, space, or other CSS metacharacter.

func ConfigureBootstrapCorrelation

func ConfigureBootstrapCorrelation(parseCtx context.Context, parseBootstrap *SSRBootstrap)

ConfigureBootstrapCorrelation embeds the correlation ID from ctx into the bootstrap payload so the client can auto-adopt it during hydration without manual threading.

ui.ConfigureBootstrapCorrelation(r.Context(), &bootstrap)

func ConfigureHydrationIslandBudget

func ConfigureHydrationIslandBudget(parseBudget HydrationIslandBudget)

ConfigureHydrationIslandBudget is a browser-only runtime setting. Native SSR can still validate plans with InspectHydrationIslandBudget.

func CorrelationIDFromContext

func CorrelationIDFromContext(parseCtx context.Context) string

CorrelationIDFromContext returns the correlation ID stored by WithCorrelationID or WrapSSRCorrelation, or an empty string if none is present.

func CurrentTheme

func CurrentTheme() string

CurrentTheme returns the active theme name without subscribing (safe to call outside a render). Returns "" when no theme has been set.

func Download

func Download(parseData []byte, parseName, parseMime string)

Download saves bytes as a file with the given name and MIME type. No-op on the native/SSR build.

func GetSSRObservationAttributes

func GetSSRObservationAttributes(parseObservation SSRObservation) map[string]string

GetSSRObservationAttributes maps one SSRObservation to OTel-compatible span attribute key-value pairs.

The returned map uses stable "gwc.*" attribute keys following OpenTelemetry naming conventions. Pass them to your OTel SDK with SetAttributes or equivalent:

attrs := ui.GetSSRObservationAttributes(event)
for k, v := range attrs {
    span.SetAttributes(attribute.String(k, v))
}

Keys are guaranteed stable across patch releases once the observability surface is marked stable.

func HydrateIsland

func HydrateIsland(parseRoot Node, parseOptions HydrationIslandOptions) (func(), error)

HydrateIsland is browser-only. Server builds can render HydrationIsland wrappers and validate their budget plan before emitting HTML.

func MarshalSSRBootstrap

func MarshalSSRBootstrap(parsePayload SSRBootstrap) ([]byte, error)

MarshalSSRBootstrap serializes a bootstrap payload to safe inline JSON.

func MarshalSSRBootstrapBinary

func MarshalSSRBootstrapBinary(parsePayload SSRBootstrap) ([]byte, error)

MarshalSSRBootstrapBinary serializes a bootstrap payload to CBOR.

func MarshalSSRBootstrapBinaryObserved

func MarshalSSRBootstrapBinaryObserved(parsePayload SSRBootstrap, parseOptions SSRObservabilityOptions) ([]byte, error)

MarshalSSRBootstrapBinaryObserved serializes a bootstrap payload to CBOR and emits size metrics.

func MarshalSSRBootstrapObserved

func MarshalSSRBootstrapObserved(parsePayload SSRBootstrap, parseOptions SSRObservabilityOptions) ([]byte, error)

MarshalSSRBootstrapObserved serializes a bootstrap payload and emits size metrics.

func MarshalSSRStateUpdateBinary

func MarshalSSRStateUpdateBinary(parseUpdate SSRStateUpdate) ([]byte, error)

MarshalSSRStateUpdateBinary encodes a state-update envelope as CBOR.

func MarshalSSRStateUpdateText

func MarshalSSRStateUpdateText(parseUpdate SSRStateUpdate) ([]byte, error)

MarshalSSRStateUpdateText encodes a state-update envelope as JSON text.

func OnReady

func OnReady(parseFn func())

OnReady registers fn to run once, right after the first render commits (the initial UI is on screen and its effects have run). If the app has already rendered, fn runs immediately. Use it to drop a loading splash, kick off post-mount work, or signal readiness — instead of guessing with timeouts.

ui.OnReady(func() { /* hide splash, start telemetry, … */ })

On wasm the runtime additionally dispatches a "gwc:ready" event on document, so a plain host page can drop its splash without any Go glue:

document.addEventListener("gwc:ready", () => splash.remove())

func PickFile

func PickFile(parseAccept string, parseOnPick func(PickedFile))

PickFile opens the OS file picker (filtered by accept, e.g. "image/*" or ".csv") and calls onPick with the chosen file. No-op on native/SSR. onPick runs asynchronously after the user selects a file.

func RegisterBootstrapPayload

func RegisterBootstrapPayload[T any](parseBootstrap *SSRBootstrap, parseKey string, parseValue T, parseOptions ...SSRPayloadOptions) error

RegisterBootstrapPayload stores one typed payload entry under SSRBootstrap.Data.

func RegisterCacheBootstrapSeed

func RegisterCacheBootstrapSeed[T any](parseBootstrap *SSRBootstrap, cacheKey string, parseValue T, parseOptions ...SSRPayloadOptions) error

RegisterCacheBootstrapSeed stores a typed cache seed under a cache-scoped payload key.

func RegisterFormBootstrapDefaults

func RegisterFormBootstrapDefaults[T any](parseBootstrap *SSRBootstrap, parseFormID string, parseValue T, parseOptions ...SSRPayloadOptions) error

RegisterFormBootstrapDefaults stores typed form defaults under a form-scoped payload key.

func RegisterParallelRegion

func RegisterParallelRegion[Props any](parseRendererID string, parseRender func(Props) Node) error

RegisterParallelRegion registers one public parallel-region renderer and bridges it into the runtime2 registry.

func RegisterRouteBootstrapData

func RegisterRouteBootstrapData[T any](parseBootstrap *SSRBootstrap, parseKey string, parseRoutePath string, parseValue T, parseOptions ...SSRPayloadOptions) error

RegisterRouteBootstrapData stores typed route data under a route-scoped payload key.

func RegisterSessionBootstrapHint

func RegisterSessionBootstrapHint[T any](parseBootstrap *SSRBootstrap, parseHintKey string, parseValue T, parseOptions ...SSRPayloadOptions) error

RegisterSessionBootstrapHint stores a typed session hint under an app-scoped payload key.

func RegisterStateUpdatePayload

func RegisterStateUpdatePayload[T any](parseUpdate *SSRStateUpdate, parseKey string, parseValue T, parseOptions ...SSRPayloadOptions) error

RegisterStateUpdatePayload stores one typed payload upsert in a state-update envelope.

func Render

func Render(parseRoot Node, parseSelector string)

Render is browser-only; the native SSR slice exposes RenderToString instead.

func RenderBootstrapReferenceScript

func RenderBootstrapReferenceScript(parseRef SSRBootstrapReference, parseScriptID string) (string, error)

RenderBootstrapReferenceScript renders an inline script tag that points at an external bootstrap payload.

func RenderBootstrapReferenceScriptWithOptions

func RenderBootstrapReferenceScriptWithOptions(parseRef SSRBootstrapReference, parseScriptID string, parseScriptOptions SSRScriptOptions) (string, error)

func RenderBootstrapScript

func RenderBootstrapScript(parsePayload SSRBootstrap, parseScriptID string) (string, error)

RenderBootstrapScript renders an inline bootstrap script tag.

func RenderBootstrapScriptObserved

func RenderBootstrapScriptObserved(parsePayload SSRBootstrap, parseScriptID string, parseOptions SSRObservabilityOptions) (string, error)

RenderBootstrapScriptObserved renders an inline bootstrap script tag and emits size metrics.

func RenderBootstrapScriptWithOptions

func RenderBootstrapScriptWithOptions(parsePayload SSRBootstrap, parseScriptID string, parseScriptOptions SSRScriptOptions) (string, error)

func RenderInto

func RenderInto(parseRoot Node, parseTarget any) error

RenderInto is a non-browser stub that returns an UnsupportedOnServer error.

func RenderToStream

func RenderToStream(parseCtx context.Context, parseWriter io.Writer, parseRoot Node, parseOptions ...SSRStreamOptions) error

RenderToStream writes an SSR shell immediately and then streams async boundary replacements as render-time suspensions resolve.

func RenderToStreamObserved

func RenderToStreamObserved(parseCtx context.Context, parseWriter io.Writer, parseRoot Node, parseObservability SSRObservabilityOptions, parseOptions ...SSRStreamOptions) error

RenderToStreamObserved streams an SSR tree and emits SSR render metrics.

func RenderToString

func RenderToString(parseRoot Node) (string, error)

RenderToString renders a ui.Node tree to HTML on non-browser targets.

func RenderToStringObserved

func RenderToStringObserved(parseRoot Node, parseOptions SSRObservabilityOptions) (string, error)

RenderToStringObserved renders a ui.Node tree to HTML and emits SSR metrics.

func ResetWASMStackFrameMapper

func ResetWASMStackFrameMapper()

ResetWASMStackFrameMapper clears the installed wasm stack-frame mapper.

func Run

func Run(parseSelector string, parseComponent any, parseProps ...any)

Run is browser-only; on the native/SSR slice it panics like Render. Server-side code should call RenderToString (or the SSR streaming APIs) instead of mounting and blocking.

func SafeGo

func SafeGo(parseSubject string, parseFn func())

SafeGo starts fn on a new goroutine with framework crash containment. In wasm a panic that escapes any goroutine exits the whole Go program and leaves the page dead; SafeGo recovers the panic, prints the structured agent-readable crash report to the console, and lets the rest of the app keep running. Use it instead of the bare go statement for application background work. The subject names the task in the crash report.

func SelectorID

func SelectorID(parseID string) string

SelectorID returns a CSS id selector ("#" + escaped id) for the given element id, safe to pass to querySelector/querySelectorAll for an id from any source.

el := document.Call("querySelector", ui.SelectorID(id))

For ids generated by UseId the escaping is a no-op, but using SelectorID everywhere keeps call sites uniformly safe.

func SetInspectSink

func SetInspectSink(parseSink func(string)) func()

SetInspectSink redirects UseInspect output (e.g. to the devtools bridge or a test buffer) and returns a function that restores the previous sink. Pass a no-op to silence inspection in production builds.

func SetParallelRegionWorkerRenderer

func SetParallelRegionWorkerRenderer(parseRendererID string, parseRender runtime2.WorkerRegionRenderer) error

SetParallelRegionWorkerRenderer registers one explicit worker-native renderer for an already-registered public parallel region.

func SetParallelRegionWorkerRendererWithConfig

func SetParallelRegionWorkerRendererWithConfig(
	parseRendererID string,
	parseRender runtime2.WorkerRegionRenderer,
	parseConfig ParallelRegionWorkerRendererConfig,
) error

SetParallelRegionWorkerRendererWithConfig registers one explicit worker-native renderer with optional trust and validation settings.

func SetTheme

func SetTheme(parseName string)

SetTheme switches the active theme from anywhere — including outside a render (a global hotkey handler, the OS theme-change listener, a goroutine). It re-renders all UseTheme subscribers and applies <html data-theme="...">. Passing "" clears the attribute (revert to default/unthemed).

func SetWASMStackFrameMapper

func SetWASMStackFrameMapper(parseMapper func(WASMStackFrame) (WASMStackFrame, bool))

SetWASMStackFrameMapper installs a mapper that translates an observed wasm/browser panic frame back to a higher-signal application Go source location. The runtime threads every panic frame through it before the in-page error overlay and the devtools panel render it, so a panic shows your Go function/file/line instead of an opaque wasm offset.

This is the public C4 "stack-correlation workaround" — the supported bridge until the Go toolchain emits browser-consumable source maps for js/wasm natively. Install one at startup (sourced from your build's symbol dump or a hand-maintained table for hot paths).

func StartTransition

func StartTransition(parseFn func())

StartTransition runs fn immediately on non-browser targets.

func SuspendUntil

func SuspendUntil(parseDone <-chan struct{}, parseReason ...string)

SuspendUntil interrupts the current render until done closes.

func Typed added in v4.2.0

func Typed[P any](parseComponent func(P) Node) func(P) Node

Typed registers a props-taking component once and returns a constructor that creates its elements without any reflection on the render path.

A component passed to CreateElement with a custom props struct renders through a reflect.Value.Call trampoline on every render — measurable overhead in wasm, where reflection is expensive. Typed builds a statically dispatched renderer instead:

var HookCell = ui.Typed(renderHookCell) // package level, once
...
HookCell(HookCellProps{Index: i})       // in render bodies

The returned constructor is equivalent to ui.CreateElement(component, props): same component identity (handle cache), same reconciliation, hooks work unchanged. Mixing is safe — plain CreateElement calls for the same function value keep the static renderer (the implementation-identity guard skips re-registration).

func UnsupportedOnServer

func UnsupportedOnServer(parseName string) error

UnsupportedOnServer explains the current SSR limitation for hook-based components.

func UseAction

func UseAction[T any](parseCache *query.Cache, parseKey string) (query.Result[T], func(parseOptimistic T, parseFn func() (T, error)))

UseAction binds a server action to key in the cache: it returns the current result and a run function that fires the action with an optimistic value and reconciles in the background (commit or rollback), re-rendering on settle. Pair run's fn with serverfn.Call to make a one-call optimistic server action.

res, runLike := ui.UseAction[int](appCache, "post/"+id+"/likes")
onClick := func() { runLike(res.Data+1, func() (int, error) { return serverfn.Call(...) }) }

func UseAnimationRestart

func UseAnimationRestart(parseRef DOMRef, parseClassName string, parseDeps ...any)

UseAnimationRestart is a no-op on native/SSR.

func UseAsyncMutation

func UseAsyncMutation[T any](parseCache *query.Cache, parseKey string) func(parseOptimistic T, parseFn func() (T, error))

UseAsyncMutation is the async sibling of UseMutation: the returned function applies the optimistic value immediately (re-rendering now) and reconciles in the background — committing the server result or rolling back on error and re-rendering again when it settles. This is the fire-and-forget optimistic action; UseMutation wraps the *blocking* query.Mutate, this one wraps query.MutateAsync.

func UseAutoFocus

func UseAutoFocus(parseRef DOMRef, parseDeps ...any)

UseAutoFocus moves keyboard focus to a referenced element after it mounts (G22).

The HTML autofocus attribute (html.AutoFocus) only fires on the initial page load, not when an element is mounted later in a single-page app — so inline editors, dialogs, and revealed fields never receive focus from it. UseAutoFocus closes that gap without the focusByID/getElementById workaround: pair it with a DOM ref and the element is focused once it is live.

r := ui.UseDOMRef()
ui.UseAutoFocus(r)                    // focus once, on mount
return shorthand.Input(shorthand.Ref(r))

Pass deps to re-focus when they change (focus-follows-reveal):

ui.UseAutoFocus(r, isEditing)         // focus each time isEditing flips true-with-mount

With no deps it runs exactly once on mount (it must not run every render, or it would steal focus continuously). Focusing is a no-op before mount, after unmount, and on the native/SSR build.

func UseCallback

func UseCallback[T any](parseFn T, parseDeps ...any) T

UseCallback returns fn unchanged on non-browser targets.

func UseContext

func UseContext[T any](parseContext *Context[T]) T

UseContext is a core package helper.

func UseDefer

func UseDefer(parseTriggered bool) bool

UseDefer latches a deferred view: it returns false until triggered first becomes true, then stays true for the rest of the component's lifetime (mount-once). Feed it a trigger derived from component state — `UseIntersection` (viewport), `UseIdle` (browser idle), or `UseTimerTrigger` (after a delay) — so that when the trigger flips, the component re-renders and the deferred subtree mounts for good (it will not flicker back to the placeholder if the trigger later goes false).

visible := UseIntersection(ref)          // a state-backed browser trigger
if ui.UseDefer(visible) { /* render heavy view */ } else { /* render placeholder */ }

This defers RENDER work (the subtree is not constructed until shown). It does not lazy-load a separate wasm *chunk* per view — Go compiles to a single wasm binary, so all code is already present; "deferrable views" here means deferred construction/mount, not code splitting.

func UseDeferredValue

func UseDeferredValue[T any](parseValue T) T

UseDeferredValue returns value unchanged on non-browser targets.

func UseDocumentEvent

func UseDocumentEvent(eventType string, handler func(Event), deps ...any)

UseDocumentEvent subscribes the calling component to a document-level event for as long as it is mounted.

func UseEffect

func UseEffect(parseEffect func() func(), parseDeps ...any)

UseEffect is a no-op on non-browser targets.

func UseEffectOf added in v4.2.0

func UseEffectOf[D comparable](parseEffect func() func(), parseDep D)

UseEffectOf is a no-op on non-browser targets (native UseEffect parity).

func UseElementGeometry

func UseElementGeometry(parseRef DOMRef) interop.Rect

UseElementGeometry returns the zero Rect on native/SSR.

func UseFocusTrap

func UseFocusTrap(parseOptions FocusTrapOptions)

UseFocusTrap is a no-op for non-browser targets.

func UseForceUpdate

func UseForceUpdate() func()

UseForceUpdate returns a function that triggers a re-render of the calling component (G5). Use it after a mutation that does not change a subscribed value — an in-place edit or an external store write — instead of bumping a dummy "version" state by hand.

rerender := ui.UseForceUpdate()
... onExternalChange: rerender()

func UseGlobalKey

func UseGlobalKey(handler func(KeyboardEvent), deps ...any)

UseGlobalKey subscribes to document keydown — app-wide keyboard shortcuts. To ignore keystrokes while the user is typing, check the event target in the handler (e.g. skip when document.activeElement is an input/textarea).

func UseId

func UseId() string

UseId returns a stable generated identifier for the current component instance.

func UseIdle

func UseIdle() bool

UseIdle returns true once the browser has reached an idle point after mount — the idle trigger (`@defer (on idle)`). It is approximated with a deferred (next-task) timeout, which schedules after the current render/commit work, where a true requestIdleCallback is unavailable.

func UseInspect

func UseInspect[T any](parseLabel string, parseValue T)

UseInspect logs a labeled value whenever it changes between renders — GoWebComponents' answer to Svelte's $inspect. It records the initial value on mount and, on each subsequent render, logs an "old -> new" line when the value changed (by structural equality), routed through the current inspect sink. A pure dev aid: leave it in during development and silence it in production either at runtime with SetInspectSink(func(string){}) or, at zero per-call cost, by building with the gwcsilent tag (`go build -tags gwcsilent`), which wires the sink to a no-op.

count := ui.UseState(0)
ui.UseInspect("count", count.Get()) // logs each time count changes

func UseInteraction

func UseInteraction(parseRef DOMRef) bool

UseInteraction returns true after the first pointer interaction with the referenced element — the interaction trigger (`@defer (on interaction)`), for deferring a heavy view until the user actually touches it.

func UseIntersection

func UseIntersection(parseRef DOMRef, parseOptions ...interop.IntersectionObserverOptions) bool

UseIntersection returns false on native/SSR.

func UseInterval

func UseInterval(parseFn func(), parseInterval time.Duration, parseDeps ...any)

UseInterval runs fn every interval while the component is mounted; cancelled on unmount or when deps change.

func UseLayoutEffect

func UseLayoutEffect(parseEffect func() func(), parseDeps ...any)

UseLayoutEffect is a no-op on non-browser targets (G36).

func UseMediaQuery

func UseMediaQuery(parseQuery string) bool

UseMediaQuery reports whether the given CSS media query currently matches, and re-renders the component when it changes (G20). It reflects the query at mount, updates live via the MediaQueryList change event, and releases its listener on unmount. On builds without media-query support it returns false.

wide := ui.UseMediaQuery("(min-width: 768px)")

func UseMemo

func UseMemo[T any](parseCompute func() T, parseDeps ...any) T

UseMemo computes value immediately on non-browser targets.

func UseMemoOf added in v4.2.0

func UseMemoOf[T any, D comparable](parseCompute func(D) T, parseDep D) T

UseMemoOf computes directly on non-browser targets (native UseMemo parity).

func UseMount

func UseMount(parseFn func() func())

UseMount runs fn once after the component first mounts and runs the returned cleanup (if any) on unmount (G38). It is the self-documenting form of the "run once" effect — clearer and safer than the UseEffect(fn, true) constant-dep idiom, which silently changes behavior if dep-equality is ever refactored.

ui.UseMount(func() func() {
    sub := subscribe()
    return func() { sub.Close() }   // cleanup on unmount
})

On the native/SSR build effects do not run, so UseMount is a no-op there (matching UseEffect).

func UseMutation

func UseMutation[T any](parseCache *query.Cache, parseKey string) func(parseOptimistic T, parseFn func() (T, error)) query.Result[T]

UseMutation returns a typed mutate function bound to key in a query.Cache. Calling it applies the optimistic value to the cache immediately, runs fn, commits fn's result on success or rolls back to the exact prior state on error, then re-renders the component with the outcome. This is the one-call optimistic-update path.

like := ui.UseMutation[int](appCache, "post/"+id+"/likes")
onClick := func() {
    like(current+1, func() (int, error) { return api.Like(id) }) // optimistic +1, auto-rollback
}

func UseNetworkStatus

func UseNetworkStatus() bool

UseNetworkStatus reports whether the browser is currently online and re-renders the component when connectivity changes (G32). It seeds from navigator.onLine and stays live via the window online/offline events, with the listeners released on unmount. On native/SSR builds it reports true (assume connectivity) and never changes.

online := ui.UseNetworkStatus()

func UseOptimistic

func UseOptimistic[T any](parseCache *query.Cache, parseKey string) (query.Result[T], func(T))

UseOptimistic returns the current value for key plus a setter that applies an optimistic value immediately and re-renders — GoWebComponents' answer to React's useOptimistic, backed by the query cache. The optimistic value is superseded by the next authoritative write (a mutation result or a query refresh) for the same key.

value, setOptimistic := ui.UseOptimistic[int](appCache, "likes")
onClick := func() {
    setOptimistic(value.Data + 1)                       // UI updates now
    go ui.UseAsyncMutation[int](appCache, "likes")(...) // server reconciles
}

func UsePointerEvents

func UsePointerEvents(parseRef DOMRef, parseHandlers PointerHandlers)

UsePointerEvents is a no-op on native/SSR.

func UsePrefersReducedMotion

func UsePrefersReducedMotion() bool

UsePrefersReducedMotion reports whether the user has requested reduced motion. It reflects the media query at mount and updates live when the emulated or OS preference flips, unsubscribing on unmount (the underlying js.Func handle is released). On builds without media-query support it returns false.

func UseQuery

func UseQuery[T any](parseCache *query.Cache, parseKey string, parseFetcher func() (T, error), parseDeps ...any) query.Result[T]

UseQuery subscribes the calling component to a key in a query.Cache and returns the current result. It renders cached data immediately (a pure, no-fetch read) and, after commit, revalidates in the background via stale-while-revalidate — re-rendering the component when fresh data lands. Re-subscribes whenever key (or any extra dep) changes.

The fetcher is an ordinary func() (T, error): no special async plumbing, and the same call works against a server-seeded cache during SSR.

func UserCard(props UserProps) ui.Node {
    res := ui.UseQuery(appCache, "user/"+props.ID, func() (User, error) {
        return api.GetUser(props.ID)
    })
    if res.Status == query.StatusLoading {
        return Spinner()
    }
    return Text(res.Data.Name) // updates in place when the background refresh resolves
}

When the fetcher closes over values that change independently of key (auth headers, a current user ID, filters), pass them as deps so the subscription re-runs with the fresh closure instead of silently using the stale one:

res := ui.UseQuery(appCache, "feed", func() (Feed, error) {
    return api.GetFeed(token) // token captured by the closure
}, token) // re-subscribe when token changes

func UseRevalidateOnFocus

func UseRevalidateOnFocus(parseCache *query.Cache)

UseRevalidateOnFocus wires the standard SWR freshness triggers: when the tab regains focus or the browser comes back online, every cached query is marked stale and the component re-renders, so its UseQuery hooks revalidate against the server. Mount it once near the app root. It is a no-op on native/SSR (no window).

func App(props AppProps) ui.Node {
    ui.UseRevalidateOnFocus(appCache) // refetch stale data on focus / reconnect
    ...
}

func UseSpring

func UseSpring(parseTarget float64, parseConfig anim.SpringConfig) float64

UseSpring animates a float64 value toward parseTarget using a damped harmonic spring. It returns the current animated position, which updates each animation frame via requestAnimationFrame until the spring settles. It honors prefers-reduced-motion by default: when the user requests reduced motion the value snaps to the target instead of animating, with no requestAnimationFrame loop.

func UseSuspenseQuery

func UseSuspenseQuery[T any](parseCache *query.Cache, parseKey string, parseFetcher func() (T, error), parseDeps ...any) T

UseSuspenseQuery is the suspending sibling of UseQuery: instead of returning a Result the caller must switch on, it returns the data directly, suspending the render until the data is ready and throwing the error to the nearest ErrorBoundary on failure. Wrap the subtree in an AsyncBoundary (for the loading fallback) and an ErrorBoundary (for failures); the component body then reads the value unconditionally — the React use(promise) / Solid createResource shape.

func UserCard(props UserProps) ui.Node {
    user := ui.UseSuspenseQuery(appCache, "user/"+props.ID, func() (User, error) {
        return api.GetUser(props.ID)
    })
    return Text(user.Name) // no Status switch — AsyncBoundary shows the fallback while loading
}

Like UseQuery, pass deps when the fetcher closes over values that change independently of key; changing key or any dep starts a fresh load (and re-suspends until it resolves).

func UseTheme

func UseTheme(parseDefault string) (string, func(string))

UseTheme subscribes the calling component to the active theme name and returns it together with a setter. Switching the theme (via the returned setter or SetTheme) re-renders every UseTheme subscriber and applies the name to <html data-theme="..."> so `[data-theme="..."]` CSS rules and :root token overrides take effect. It is the reactive capstone over the typed-CSS token system (css.Theme.RootRules / css.Var): style with tokens, switch with UseTheme.

theme, setTheme := ui.UseTheme("dark")
onClick := ui.UseEvent(func() {
    if theme == "dark" { setTheme("light") } else { setTheme("dark") }
})

Seed from the OS preference by passing it as the default:

theme, setTheme := ui.UseTheme(string(ui.UsePrefersColorScheme()))

func UseTimeout

func UseTimeout(parseFn func(), parseDelay time.Duration, parseDeps ...any)

UseTimeout runs fn once after delay while the component is mounted; it is cancelled (and its js.Func released) on unmount or when deps change.

func UseTimerTrigger

func UseTimerTrigger(parseDelay time.Duration) bool

UseTimerTrigger returns true once delay has elapsed since mount — the timer trigger for a deferred view (Angular `@defer (on timer(...))`).

func UseWheel

func UseWheel(parseRef DOMRef, parseHandler func(Event))

UseWheel is a no-op on native/SSR.

func UseWindowEvent

func UseWindowEvent(eventType string, handler func(Event), deps ...any)

UseWindowEvent subscribes the calling component to a window-level event (resize, scroll, hashchange, …) for as long as it is mounted.

func ViewTransition

func ViewTransition(parseApply func())

ViewTransition calls apply directly on non-browser builds (no View Transitions API). See the wasm implementation for the animated path.

func WithCorrelationID

func WithCorrelationID(parseCtx context.Context, parseId string) context.Context

WithCorrelationID stores a correlation ID in the request context. Retrieve it later with CorrelationIDFromContext.

func WithW3CTraceContext

func WithW3CTraceContext(parseCtx context.Context, parseTc W3CTraceContext) context.Context

WithW3CTraceContext stores a W3CTraceContext in ctx. WrapSSRCorrelation calls this automatically when a valid traceparent is present.

func WrapSSRCorrelation

func WrapSSRCorrelation(parseNext http.Handler) http.Handler

WrapSSRCorrelation is an HTTP middleware that propagates per-request trace context following W3C Trace Context (https://www.w3.org/TR/trace-context/) and common correlation ID conventions.

Resolution order:

  1. W3C traceparent header — trace-id used as the correlation ID; a new span ID is generated for this server operation; traceparent is written to the response.
  2. X-Correlation-ID, X-Request-ID, X-Trace-ID — used as-is; a synthetic W3CTraceContext is generated using the value as the trace ID.
  3. Generated — a fresh OTel-compatible 128-bit trace ID and 64-bit span ID are generated using crypto/rand.

For every request the middleware:

  • stores the correlation ID in ctx (retrieve with CorrelationIDFromContext)
  • stores W3CTraceContext in ctx (retrieve with TraceContextFromContext)
  • writes X-Correlation-ID and Traceparent to the response
  • forwards the incoming Tracestate header unchanged

Security note: correlation IDs must not encode user IDs, session tokens, or sensitive metadata. The middleware does not validate incoming header values beyond structural format — callers are responsible for ensuring IDs are opaque.

Types

type AccessibleOverlayProps

type AccessibleOverlayProps struct {
	Open                  bool
	Target                PortalTarget
	AppRootSelector       string
	SurfaceID             string
	Kind                  OverlayKind
	LabelledBy            string
	DescribedBy           string
	Role                  string
	Modal                 bool
	InitialFocusSelector  string
	FallbackFocusSelector string
	RestoreFocus          bool
	TrapFocus             bool
	CloseOnEscape         bool
	CloseOnOutsideClick   bool
	LockScroll            bool
	BackgroundInert       bool
	Backdrop              bool
	BaseZIndex            int
	AnchorSelector        string
	Positioning           string
	BackdropClass         string
	SurfaceClass          string
	BackdropStyle         map[string]string
	SurfaceStyle          map[string]string
	Child                 Node
	Children              []Node
	OnDismiss             func()
}

type AnnouncementMode

type AnnouncementMode string
const (
	AnnouncementPolite    AnnouncementMode = "polite"
	AnnouncementAssertive AnnouncementMode = "assertive"
)

type Announcer

type Announcer struct{}

func UseAnnouncer

func UseAnnouncer() Announcer

UseAnnouncer returns a no-op Announcer for non-browser targets.

func (Announcer) Announce

func (parseA Announcer) Announce(parseMode AnnouncementMode, parseMessage string)

Announce is a core package helper.

func (Announcer) Assertive

func (parseA Announcer) Assertive(parseMessage string)

Assertive is a core package helper.

func (Announcer) AssertiveID

func (parseA Announcer) AssertiveID() string

AssertiveID is a core package helper.

func (Announcer) Clear

func (parseA Announcer) Clear()

Clear is a core package helper.

func (Announcer) Polite

func (parseA Announcer) Polite(parseMessage string)

Polite is a core package helper.

func (Announcer) PoliteID

func (parseA Announcer) PoliteID() string

PoliteID is a core package helper.

func (Announcer) Region

func (parseA Announcer) Region() Node

Region is a core package helper.

type AsyncBoundaryProps

type AsyncBoundaryProps struct {
	Pending         bool
	Error           error
	Fallback        Node
	TimeoutFallback Node
	ErrorFallback   func(error) Node
	Content         Node
	Delay           time.Duration
	Timeout         time.Duration
}

type CSRFToken

type CSRFToken struct {
	Value         string
	HeaderName    string
	FormFieldName string
}

func NewCSRFToken

func NewCSRFToken(parseValue string) CSRFToken

NewCSRFToken creates a CSRFToken with the given value and default header and form field names.

func (CSRFToken) FormField

func (parseT CSRFToken) FormField() (string, string)

FormField is a core package helper.

func (CSRFToken) Header

func (parseT CSRFToken) Header() (string, string)

Header is a core package helper.

type ChangeEvent

type ChangeEvent = Event

type ColorScheme

type ColorScheme string

ColorScheme is the user's preferred color scheme as reported by the prefers-color-scheme media feature.

const (
	// ColorSchemeLight is the default when no dark preference is expressed or
	// when media queries are unavailable (for example native/SSR builds).
	ColorSchemeLight ColorScheme = "light"
	// ColorSchemeDark indicates the user prefers a dark color scheme.
	ColorSchemeDark ColorScheme = "dark"
)

func UsePrefersColorScheme

func UsePrefersColorScheme() ColorScheme

UsePrefersColorScheme reports the user's preferred color scheme, defaulting to ColorSchemeLight. Like UsePrefersReducedMotion it reflects the value at mount, updates live on preference changes, and cleans up its listener on unmount.

type CompositeItem

type CompositeItem struct {
	ID       string
	Text     string
	Disabled bool
}

type CompositeNavigation

type CompositeNavigation struct{}

func UseCompositeNavigation

func UseCompositeNavigation(parseItems []CompositeItem, parseOptions ...CompositeNavigationOptions) CompositeNavigation

UseCompositeNavigation returns a no-op CompositeNavigation for non-browser targets.

func (CompositeNavigation) ActiveDescendant

func (parseN CompositeNavigation) ActiveDescendant() string

ActiveDescendant is a core package helper.

func (CompositeNavigation) ActiveID

func (parseN CompositeNavigation) ActiveID() string

ActiveID is a core package helper.

func (CompositeNavigation) ActiveIndex

func (parseN CompositeNavigation) ActiveIndex() int

ActiveIndex is a core package helper.

func (CompositeNavigation) IsActive

func (parseN CompositeNavigation) IsActive(parseIndex int) bool

IsActive is a core package helper.

func (CompositeNavigation) MoveEnd

func (parseN CompositeNavigation) MoveEnd()

MoveEnd is a core package helper.

func (CompositeNavigation) MoveHome

func (parseN CompositeNavigation) MoveHome()

MoveHome is a core package helper.

func (CompositeNavigation) MoveNext

func (parseN CompositeNavigation) MoveNext()

MoveNext is a core package helper.

func (CompositeNavigation) MovePrevious

func (parseN CompositeNavigation) MovePrevious()

MovePrevious is a core package helper.

func (CompositeNavigation) OnKeyDown

func (parseN CompositeNavigation) OnKeyDown(parseEvent any)

OnKeyDown is a core package helper.

func (CompositeNavigation) SetActive

func (parseN CompositeNavigation) SetActive(parseIndex int)

SetActive is a core package helper.

func (CompositeNavigation) TabIndex

func (parseN CompositeNavigation) TabIndex(parseIndex int) int

TabIndex is a core package helper.

type CompositeNavigationOptions

type CompositeNavigationOptions struct {
	Orientation  string
	Loop         bool
	InitialIndex int
}

type Context

type Context[T any] struct {
	Provider *ContextProvider[T]
	// contains filtered or unexported fields
}

func CreateContext

func CreateContext[T any](parseDefaultValue T) *Context[T]

CreateContext creates a typed context with its default value and provider.

type ContextProvider

type ContextProvider[T any] struct {
	// contains filtered or unexported fields
}

ContextProvider creates a provider element for a Context value.

type ContextProviderProps

type ContextProviderProps[T any] struct {
	Value    T
	Child    Node
	Children []Node
}

ContextProviderProps defines the value and child content for a context provider.

type DOMRef

type DOMRef struct {
	// contains filtered or unexported fields
}

DOMRef is a handle to a rendered DOM element.

func UseDOMRef

func UseDOMRef() DOMRef

UseDOMRef creates a DOMRef that is stable across renders. Call it unconditionally at a stable hook position, like any other hook.

func (DOMRef) Blur

func (parseR DOMRef) Blur()

Blur removes keyboard focus from the referenced element. Like Focus, it routes through the node's optional capability (real blur on wasm, no-op on native/SSR) and is safe before mount / after unmount.

func (DOMRef) Click

func (parseR DOMRef) Click()

Click synthesizes a click on the referenced element (element.click()). Cross-build no-op when unsupported.

func (DOMRef) Focus

func (parseR DOMRef) Focus()

Focus moves keyboard focus to the referenced element if it is mounted and focusable. Cross-build: it routes through the node's optional Focuser capability (real focus on wasm, no-op on native/SSR), so callers need no build tags. Safe to call before mount / after unmount (no-op).

func (DOMRef) Mounted

func (parseR DOMRef) Mounted() bool

Mounted reports whether the ref currently points at a live DOM node.

func (DOMRef) Node

func (parseR DOMRef) Node() runtime.DOMNode

Node returns the live DOM node, or nil before mount / after unmount / on native.

func (DOMRef) ScrollIntoView

func (parseR DOMRef) ScrollIntoView(parseBehavior string)

ScrollIntoView scrolls the referenced element into the visible area. behavior is "" (browser default), "smooth", "instant", or "auto". Cross-build no-op when unsupported.

func (DOMRef) Sink

func (parseR DOMRef) Sink() runtime.DOMRefSink

Sink returns the underlying runtime sink for the html.Ref PropOption. It is an internal wiring seam, not part of the everyday API.

type Debounced

type Debounced[T any] struct {
	// contains filtered or unexported fields
}

Debounced returns a delayed view of a value on browser builds; on native builds it is immediate.

func UseDebounced

func UseDebounced[T any](parseValue T, parseDelay time.Duration) Debounced[T]

UseDebounced returns the current value unchanged on non-browser targets.

func (Debounced[T]) Get

func (parseD Debounced[T]) Get() T

Get returns the current debounced value.

func (Debounced[T]) Pending

func (parseD Debounced[T]) Pending() bool

Pending reports whether a debounced update is pending.

type DeferBlocks

type DeferBlocks[T any] struct {
	Placeholder func() Node
	Loading     func() Node
	Content     func(T) Node
	Error       func(error) Node
}

DeferBlocks[T] supplies the renderers for each state of a deferred view — the @defer sub-block set. Placeholder and Loading are optional (a nil renderer contributes nothing); Content renders the resolved data and Error renders the failure.

type DeferState

type DeferState[T any] struct {
	Status DeferStatus
	Data   T
	Err    error
}

DeferState[T] is the current state of a deferred view: its status plus the resolved data or error. It is a small value; copy it freely.

func UseAsyncDefer

func UseAsyncDefer[T any](parseTriggered bool, parseLoad func() (T, error)) DeferState[T]

UseAsyncDefer drives a deferred async resource through the placeholder → loading → ready/error states. It does nothing until triggered first becomes true (pair it with UseIntersection / UseIdle / UseTimerTrigger); then it runs load exactly once, showing Loading while it resolves and Ready or Error when it settles, re-rendering on each transition. Once started it never reverts to the placeholder. Pair it with RenderDefer to render the matching block.

Natively (SSR/tests) effects are no-ops, so the resource is resolved in the browser; the returned state is always a valid snapshot to render.

type DeferStatus

type DeferStatus int

DeferStatus is the state of a deferred, possibly-async view. It models Angular @defer's blocks: a placeholder before work begins, a loading block while an async resource resolves, the content once ready, and an error block on failure.

const (
	// DeferPlaceholder is the pre-trigger state: the deferred work has not started.
	DeferPlaceholder DeferStatus = iota
	// DeferLoading is shown while the deferred async resource is resolving.
	DeferLoading
	// DeferReady is shown once the resource resolved successfully.
	DeferReady
	// DeferError is shown when the resource failed to resolve.
	DeferError
)

type Element

type Element = runtime.Element

Node is the public UI tree node type.

type ErrorBoundaryProps

type ErrorBoundaryProps struct {
	Fallback      Node
	ErrorFallback func(error, func()) Node
	OnError       func(error)
	Child         Node
	Children      []Node
	ResetKeys     []any
}

type Event

type Event struct{}

func (Event) GetKey

func (Event) GetKey() string

GetKey is a core package helper.

func (Event) GetKeyCode

func (Event) GetKeyCode() int

GetKeyCode is a core package helper.

func (Event) GetValue

func (Event) GetValue() string

GetValue is a core package helper.

func (Event) IsChecked

func (Event) IsChecked() bool

IsChecked is a core package helper.

func (Event) PreventDefault

func (Event) PreventDefault()

PreventDefault is a core package helper.

func (Event) StopPropagation

func (Event) StopPropagation()

StopPropagation is a core package helper.

type FieldErrors

type FieldErrors map[string]string

type FieldStatus

type FieldStatus struct {
	Name    string
	Touched bool
	Dirty   bool
	Pending bool
	Error   string
}

type File

type File struct{}

File is the native no-op counterpart of the browser File wrapper.

func GetFiles

func GetFiles(parseFileEvent Event) []File

GetFiles returns no files outside the browser wasm runtime.

func (File) LastModified

func (File) LastModified() int64

LastModified is a core package helper.

func (File) Name

func (File) Name() string

Name is a core package helper.

func (File) Size

func (File) Size() int64

Size is a core package helper.

func (File) Type

func (File) Type() string

Type is a core package helper.

type FocusEvent

type FocusEvent = Event

type FocusManager

type FocusManager struct{}

func UseFocusManager

func UseFocusManager() FocusManager

UseFocusManager returns a no-op FocusManager for non-browser targets.

func (FocusManager) FocusByID

func (parseM FocusManager) FocusByID(parseId string, parseOptions ...FocusOptions) bool

FocusByID is a core package helper.

func (FocusManager) FocusFirst

func (parseM FocusManager) FocusFirst(parseContainerSelector string, parseOptions ...FocusOptions) bool

FocusFirst is a core package helper.

func (FocusManager) FocusFirstError

func (parseM FocusManager) FocusFirstError(parseErrors FieldErrors, parseFieldIDs map[string]string, parseOrder ...string) bool

FocusFirstError is a core package helper.

func (FocusManager) FocusSelector

func (parseM FocusManager) FocusSelector(parseSelector string, parseOptions ...FocusOptions) bool

FocusSelector is a core package helper.

func (FocusManager) RememberActive

func (parseM FocusManager) RememberActive() bool

RememberActive is a core package helper.

func (FocusManager) Restore

func (parseM FocusManager) Restore(parseOptions ...FocusOptions) bool

Restore is a core package helper.

type FocusOptions

type FocusOptions struct {
	PreventScroll bool
}

type FocusTrapOptions

type FocusTrapOptions struct {
	ContainerSelector     string
	InitialFocusSelector  string
	FallbackFocusSelector string
	Active                bool
	RestoreFocus          bool
}

type Form

type Form[T any] struct {
	// contains filtered or unexported fields
}

Form exposes local form state, validation helpers, and submission lifecycle state.

func UseForm

func UseForm[T any](parseInitial T) Form[T]

UseForm creates a typed form state container.

func (Form[T]) ApplyServerActionResult

func (parseF Form[T]) ApplyServerActionResult(parseResult ServerActionResult) bool

ApplyServerActionResult projects a typed server-action envelope onto the existing form error surface and returns whether the result is free of form-level errors.

func (Form[T]) ApplyServerErrors

func (parseF Form[T]) ApplyServerErrors(parseResponse ServerFormErrors) bool

ApplyServerErrors projects a structured server validation response onto the form state.

func (Form[T]) Dirty

func (parseF Form[T]) Dirty(parseName string) bool

Dirty reports whether a field differs from its initial value.

func (Form[T]) DirtyAny

func (parseF Form[T]) DirtyAny() bool

DirtyAny reports whether any field differs from its initial value.

func (Form[T]) Error

func (parseF Form[T]) Error(parseName string) string

Error returns the field error for name.

func (Form[T]) Errors

func (parseF Form[T]) Errors() FieldErrors

Errors returns a copy of the current field error map.

func (Form[T]) FieldMessage

func (parseF Form[T]) FieldMessage(parseName string) string

FieldMessage returns the current message for one field.

func (Form[T]) FieldStatus

func (parseF Form[T]) FieldStatus(parseName string) FieldStatus

FieldStatus returns the current touched, dirty, pending, and error state for one field.

func (Form[T]) FormError

func (parseF Form[T]) FormError() string

FormError returns the form-level error message.

func (Form[T]) Get

func (parseF Form[T]) Get() T

Get returns the current form value.

func (Form[T]) HasErrors

func (parseF Form[T]) HasErrors() bool

HasErrors reports whether the form currently has field or form-level errors.

func (Form[T]) HasField

func (parseF Form[T]) HasField(parseName string) bool

HasField reports whether T has a field addressable by name (the same names SetField/Touch use). SetField returns false for both an unknown field AND a type mismatch; HasField lets a test or a dev-time guard catch a misspelled field name specifically.

func (Form[T]) HasFieldError

func (parseF Form[T]) HasFieldError(parseName string) bool

HasFieldError reports whether a field currently has an error message.

func (Form[T]) IntentPending

func (parseF Form[T]) IntentPending(parseIntent string) bool

IntentPending reports whether the given intent is the currently pending submit action.

func (Form[T]) MustSetField

func (parseF Form[T]) MustSetField(parseName string, parseValue any)

MustSetField is SetField that panics when the field does not exist or the value's type does not match — turning a silent no-op into a loud failure that surfaces a typo'd field name during development. Prefer it where the field name is a hardcoded literal.

func (Form[T]) Reset

func (parseF Form[T]) Reset(parseNext ...T)

Reset restores the form to its initial value or the provided next value.

func (Form[T]) Set

func (parseF Form[T]) Set(parseValue T)

Set replaces the current form value.

func (Form[T]) SetErrors

func (parseF Form[T]) SetErrors(parseErrors FieldErrors)

SetErrors replaces the current field error map.

func (Form[T]) SetField

func (parseF Form[T]) SetField(parseName string, parseValue any) bool

SetField updates one named struct field and marks it touched.

func (Form[T]) SetFormError

func (parseF Form[T]) SetFormError(parseMessage string)

SetFormError sets the form-level error message.

func (Form[T]) SetSubmitIntent

func (parseF Form[T]) SetSubmitIntent(parseIntent string)

SetSubmitIntent records the current submit intent for intent-aware validation or submission flows.

func (Form[T]) Submit

func (parseF Form[T]) Submit(parseRun func(T) error)

Submit runs the submit function in a goroutine and updates submission lifecycle state.

func (Form[T]) SubmitError

func (parseF Form[T]) SubmitError() error

SubmitError returns the last submission error.

func (Form[T]) SubmitIntent

func (parseF Form[T]) SubmitIntent() string

SubmitIntent returns the most recently selected submit intent.

func (Form[T]) SubmitWithIntent

func (parseF Form[T]) SubmitWithIntent(parseIntent string, parseRun func(T, string) error)

SubmitWithIntent runs the submit function with an explicit intent and tracks that intent while submission is pending.

func (Form[T]) Submitted

func (parseF Form[T]) Submitted() bool

Submitted reports whether the last submission completed successfully.

func (Form[T]) Submitting

func (parseF Form[T]) Submitting() bool

Submitting reports whether a submission is in flight.

func (Form[T]) Touch

func (parseF Form[T]) Touch(parseName string)

Touch marks one field as touched.

func (Form[T]) Touched

func (parseF Form[T]) Touched(parseName string) bool

Touched reports whether a field has been touched.

func (Form[T]) TouchedAny

func (parseF Form[T]) TouchedAny() bool

TouchedAny reports whether any field has been touched.

func (Form[T]) Update

func (parseF Form[T]) Update(parseFn func(T) T)

Update replaces the current form value using the previous value.

func (Form[T]) Validate

func (parseF Form[T]) Validate(parseValidate func(T) FieldErrors) bool

Validate runs synchronous validation and stores the resulting field errors.

func (Form[T]) ValidateAsync

func (parseF Form[T]) ValidateAsync(parseValidate func(T) (FieldErrors, string), parseOnComplete func(bool))

ValidateAsync runs asynchronous validation and updates form state when it completes.

func (Form[T]) ValidateIntent

func (parseF Form[T]) ValidateIntent(parseIntent string, parseValidate func(T, string) FieldErrors) bool

ValidateIntent runs validation against the current value plus an explicit submit intent.

func (Form[T]) ValidateStruct

func (parseF Form[T]) ValidateStruct() bool

ValidateStruct validates the form's current value against the `validate:"..."` struct tags on T and stores the resulting field errors, returning true when the value is valid.

It is the turnkey path for shared client/server validation: the SAME struct, with the SAME tags, validates here in the browser (via wasm) and in a server handler, so the two can never drift — no hand-written client validator required.

type Signup struct {
    Email string `json:"email" validate:"required,email"`
    Age   int    `json:"age"   validate:"gte=13"`
}

form := ui.UseForm(Signup{})
if form.ValidateStruct() { /* submit; the server re-runs validate.Struct on the same type */ }

func (Form[T]) Validated

func (parseF Form[T]) Validated() bool

Validated reports whether validation has completed at least once.

func (Form[T]) Validating

func (parseF Form[T]) Validating() bool

Validating reports whether async validation is in flight.

type FormEvent

type FormEvent = Event

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler stores an event handler value in a form the runtime can consume.

func UseEvent

func UseEvent(parseFn any) Handler

UseEvent wraps a Go function so it can be used as a stable event handler.

func WrapHandler

func WrapHandler(parseValue any) Handler

WrapHandler wraps an already-prepared handler value.

func (Handler) Value

func (parseH Handler) Value() any

Value returns the wrapped handler payload.

type HotReloadBoundaryProps

type HotReloadBoundaryProps struct {
	Child     Node
	Children  []Node
	ResetKeys []any
}

type HydrationIslandBudget

type HydrationIslandBudget struct {
	MaxInitial    int
	MaxConcurrent int
}

HydrationIslandBudget caps how many islands can hydrate during startup and how many deferred resumptions may run at once. Zero values are treated as unbounded so apps can opt into one budget at a time.

type HydrationIslandBudgetReport

type HydrationIslandBudgetReport struct {
	Initial    int
	Deferred   int
	Violations []string
}

HydrationIslandBudgetReport summarizes whether a plan fits its budget.

func InspectHydrationIslandBudget

func InspectHydrationIslandBudget(parsePlan HydrationIslandPlan) HydrationIslandBudgetReport

InspectHydrationIslandBudget validates a progressive hydration plan against the configured startup and concurrency caps.

func (HydrationIslandBudgetReport) OK

func (parseR HydrationIslandBudgetReport) OK() bool

OK reports whether the plan stayed within every configured budget cap.

type HydrationIslandOptions

type HydrationIslandOptions struct {
	ID         string
	Selector   string
	Strategy   HydrationStrategy
	Events     []string
	RootMargin string
	Timeout    time.Duration
	Hydration  HydrationOptions
}

HydrationIslandOptions describes one independently resumable SSR island.

func NormalizeHydrationIslandOptions

func NormalizeHydrationIslandOptions(parseOptions HydrationIslandOptions) (HydrationIslandOptions, error)

NormalizeHydrationIslandOptions returns a canonical island configuration.

type HydrationIslandPlan

type HydrationIslandPlan struct {
	Islands []HydrationIslandOptions
	Budget  HydrationIslandBudget
}

HydrationIslandPlan groups island options with a startup budget.

type HydrationOptions

type HydrationOptions struct {
	ScriptID          string
	ReferenceScriptID string
	Bootstrap         SSRBootstrap
	BootstrapRef      SSRBootstrapReference
	Strict            bool
	Observability     SSRObservabilityOptions
}

HydrationOptions configures how a server-rendered tree is resumed in the browser.

type HydrationStrategy

type HydrationStrategy string

HydrationStrategy controls when an independently rendered island resumes in the browser.

const (
	HydrateImmediately   HydrationStrategy = "immediate"
	HydrateOnVisible     HydrationStrategy = "visible"
	HydrateOnInteraction HydrationStrategy = "interaction"
	HydrateOnIdle        HydrationStrategy = "idle"
)

type InputEvent

type InputEvent = Event

type KeyboardEvent

type KeyboardEvent = Event

type LazyNode

type LazyNode struct {
	// contains filtered or unexported fields
}

func UseLazyNode

func UseLazyNode(parseLoader func(context.Context) (Node, error), parseDeps ...any) LazyNode

UseLazyNode executes the loader synchronously on the server and returns the result as a LazyNode.

func (LazyNode) Cancel

func (parseL LazyNode) Cancel()

Cancel is a core package helper.

func (LazyNode) Get

func (parseL LazyNode) Get() LazyNodeState

Get is a core package helper.

func (LazyNode) Reload

func (parseL LazyNode) Reload()

Reload is a core package helper.

type LazyNodeState

type LazyNodeState struct {
	Node    Node
	Loading bool
	Error   error
	Ready   bool
}

type LazyProps

type LazyProps struct {
	Loader          func(context.Context) (Node, error)
	Dependencies    []any
	Fallback        Node
	TimeoutFallback Node
	ErrorFallback   func(error) Node
	Delay           time.Duration
	Timeout         time.Duration
}

type MatchBuilder

type MatchBuilder struct {
	// contains filtered or unexported fields
}

MatchBuilder lazily resolves the first matching branch and a default.

func Match

func Match() MatchBuilder

Match starts a lazy conditional chain.

func (MatchBuilder) Default

func (parseMatchBuilder MatchBuilder) Default(parseBranchRender NodeFactory) Node

Default resolves the chain to the first matching node or the default branch.

func (MatchBuilder) When

func (parseMatchBuilder MatchBuilder) When(isCondition bool, parseBranchRender NodeFactory) MatchBuilder

When records the first matching branch in the chain.

type MouseEvent

type MouseEvent = Event

type Node

type Node = *runtime.Element

func AccessibleOverlay

func AccessibleOverlay(parseProps AccessibleOverlayProps) Node

AccessibleOverlay renders an accessible overlay node delegating to Overlay for server rendering.

func AsyncBoundary

func AsyncBoundary(parseProps AsyncBoundaryProps) Node

AsyncBoundary renders children resolving async loading, error, and pending states on the server.

func Component

func Component(parseComponentType any, parseComponentProps ...any) Node

Component is a concise alias for CreateElement when rendering components.

func CreateElement

func CreateElement(parseComponent any, parseProps ...any) Node

CreateElement creates a UI node from a component function, provider, boundary, or existing node.

func Fragment

func Fragment(parseChildren ...Node) Node

Fragment groups children without introducing an extra host element.

func HotReloadBoundary

func HotReloadBoundary(parseBoundaryProps HotReloadBoundaryProps) Node

HotReloadBoundary wraps a subtree in a keyed fragment so changing ResetKeys forces that subtree to remount during the next render, including hot reload.

func HydrationIsland

func HydrationIsland(parseOptions HydrationIslandOptions, parseContent Node) Node

HydrationIsland wraps SSR markup with stable attributes used by HydrateIsland.

func If

func If(isCondition bool, parseBranchTrue NodeFactory, parseBranchFalse ...NodeFactory) Node

If lazily renders one of two branches.

func Lazy

func Lazy(parseProps LazyProps) Node

Lazy renders a lazy-loaded node, delegating to AsyncBoundary for fallback and error states.

func NewErrorBoundary

func NewErrorBoundary(parseProps ErrorBoundaryProps) Node

NewErrorBoundary is the function entry point for an error boundary, mirroring AsyncBoundary(props) and Lazy(props): NewErrorBoundary(ErrorBoundaryProps{...}) instead of CreateElement(ErrorBoundary, props). (The ErrorBoundary identifier is a component var, so the func needs a distinct name.)

func Overlay

func Overlay(parseOverlayProps OverlayProps) Node

Overlay renders overlay children as a Fragment on the server.

func ParallelRegion

func ParallelRegion[Props any](parseSpec ParallelRegionSpec[Props]) Node

ParallelRegion renders one public parallel region through a stable component wrapper.

func Portal

func Portal(parseProps PortalProps) Node

Portal renders children inline on non-browser targets.

func ReactiveRegion

func ReactiveRegion(render func() Node, parseSources ...ReactiveSource) Node

ReactiveRegion creates an explicit fine-grained subscribed region.

func RenderDefer

func RenderDefer[T any](parseState DeferState[T], parseBlocks DeferBlocks[T]) Node

RenderDefer selects the block to render for a deferred view's current state — the pure heart of the @defer state machine. It is independent of the hook/render lifecycle, so the block-routing logic is unit-testable without a browser:

state := ui.UseAsyncDefer(visible, loadReport)
return ui.RenderDefer(state, ui.DeferBlocks[Report]{
    Placeholder: func() ui.Node { return h.Div(h.Text("scroll to load")) },
    Loading:     func() ui.Node { return h.Spinner() },
    Content:     func(r Report) ui.Node { return reportView(r) },
    Error:       func(err error) ui.Node { return h.Div(h.Text(err.Error())) },
})

func Text

func Text(parseContent string) Node

Text creates a text node.

type NodeFactory

type NodeFactory func() Node

NodeFactory lazily produces a ui.Node when a branch is selected.

type OverlayKind

type OverlayKind string

OverlayKind describes the semantic role a layered surface plays in the shared overlay stack.

const (
	OverlayKindDialog  OverlayKind = "dialog"
	OverlayKindPopover OverlayKind = "popover"
	OverlayKindTooltip OverlayKind = "tooltip"
	OverlayKindMenu    OverlayKind = "menu"
	OverlayKindSheet   OverlayKind = "sheet"
	OverlayKindCustom  OverlayKind = "custom"
)

type OverlayProps

type OverlayProps struct {
	Open                  bool
	Target                PortalTarget
	AppRootSelector       string
	SurfaceID             string
	Kind                  OverlayKind
	Role                  string
	LabelledBy            string
	DescribedBy           string
	InitialFocusSelector  string
	FallbackFocusSelector string
	Modal                 bool
	Backdrop              bool
	TrapFocus             bool
	RestoreFocus          bool
	CloseOnEscape         bool
	CloseOnOutsideClick   bool
	LockScroll            bool
	BackgroundInert       bool
	BaseZIndex            int
	AnchorSelector        string
	Positioning           string
	BackdropClass         string
	SurfaceClass          string
	BackdropStyle         map[string]string
	SurfaceStyle          map[string]string
	Child                 Node
	Children              []Node
	OnDismiss             func()
}

OverlayProps configures a stack-aware layered surface that can optionally render through a portal target.

type OverlayStack

type OverlayStack struct {
	ID                  string
	Kind                OverlayKind
	Depth               int
	LayerCount          int
	IsTop               bool
	HandlesEscape       bool
	HandlesOutsideClick bool
	TrapFocusActive     bool
	BackdropZIndex      int
	SurfaceZIndex       int
}

OverlayStack reports where the current surface sits in the shared overlay stack.

func UseOverlayStack

func UseOverlayStack(parseOverlayOptions OverlayStackOptions) OverlayStack

UseOverlayStack registers and manages an overlay layer for the given stack options.

type OverlayStackOptions

type OverlayStackOptions struct {
	ID                  string
	Open                bool
	Kind                OverlayKind
	BaseZIndex          int
	TrapFocus           bool
	CloseOnEscape       bool
	CloseOnOutsideClick bool
}

OverlayStackOptions configures shared stack registration for a layered surface.

type ParallelRegionSpec

type ParallelRegionSpec[Props any] struct {
	RendererID        string
	RegionInstanceID  string
	Props             Props
	SourceIDs         []string
	SchedulerShardIDs []string
}

ParallelRegionSpec stores the public serializable input contract for one parallel region instance.

type ParallelRegionStatus

type ParallelRegionStatus struct {
	GetRegionInstanceID            string
	GetRegionMode                  string
	GetAssignedWorkerShard         string
	GetRendererID                  string
	GetEpoch                       uint64
	GetIsHydrationComplete         bool
	HasHydratedShellAnchor         bool
	HasPostHydrationAttached       bool
	GetLastSnapshotVersion         uint64
	GetLastDispatchedVersion       uint64
	GetLastCommittedVersion        uint64
	GetTransportTier               string
	GetDroppedStalePatchCount      uint64
	GetIgnoredStaleDiagnosticCount uint64
	GetFallbackReason              string
}

ParallelRegionStatus reports one read-only public runtime snapshot for a tracked parallel region instance.

func GetParallelRegionRuntimeStatus

func GetParallelRegionRuntimeStatus(parseRegionInstanceID string) (ParallelRegionStatus, bool, error)

GetParallelRegionRuntimeStatus reports one read-only public runtime snapshot for one tracked parallel region instance.

type ParallelRegionWorkerRendererConfig

type ParallelRegionWorkerRendererConfig struct {
	IsTrusted                        bool
	HasUpdateValidationOverride      bool
	ShouldValidateUpdateRenderOutput bool
}

ParallelRegionWorkerRendererConfig stores optional trust and validation settings for one public worker-native renderer.

type PersistStorageArea

type PersistStorageArea string

PersistStorageArea identifies which browser storage area to use.

const (
	// PersistLocal uses localStorage (persists across sessions).
	PersistLocal PersistStorageArea = "local"
	// PersistSession uses sessionStorage (cleared when tab closes).
	PersistSession PersistStorageArea = "session"
)

type PersistedState

type PersistedState[T any] struct {
	// contains filtered or unexported fields
}

PersistedState is a state handle backed by browser storage. On native/SSR builds, storage writes are silently degraded to in-memory state.

func UsePersistedState

func UsePersistedState[T any](parseKey string, parseInitial T, parseArea PersistStorageArea) PersistedState[T]

UsePersistedState returns a PersistedState backed by the chosen storage area. On first use it reads the stored JSON for parseKey from the chosen storage area; if found and decodable, that value is used as the initial state, otherwise parseInitial is used. Corrupted stored values do not panic — they are silently discarded. On native/SSR builds, storage is unavailable and the hook degrades to plain in-memory state.

func (PersistedState[T]) Err

func (parsePs PersistedState[T]) Err() error

Err returns the last storage error, or nil when no error has occurred.

func (PersistedState[T]) Get

func (parsePs PersistedState[T]) Get() T

Get returns the current value.

func (PersistedState[T]) Set

func (parsePs PersistedState[T]) Set(parseVal T)

Set writes the value to in-memory state and to the backing storage area. If the storage write fails (e.g. quota exceeded), the error is captured and retrievable via Err(); the in-memory state is still updated.

type PickedFile

type PickedFile struct {
	Name string
	Data []byte
}

PickedFile is one file chosen by the user.

type PointerHandlers

type PointerHandlers struct {
	OnPointerDown   func(Event)
	OnPointerMove   func(Event)
	OnPointerUp     func(Event)
	OnPointerCancel func(Event)
}

PointerHandlers groups the pointer callbacks for UsePointerEvents. Any nil field is skipped. Each receives the raw pointer Event (call JSValue() for clientX/clientY/pointerId, etc.).

type PortalProps

type PortalProps struct {
	Target   PortalTarget
	Child    Node
	Children []Node
}

PortalProps configures a portal target and its children.

type PortalTarget

type PortalTarget struct {
	Selector string
	Node     any
}

PortalTarget describes where a portal subtree should render.

type Previous

type Previous[T any] struct {
	// contains filtered or unexported fields
}

Previous exposes the previous committed value for a hook call.

func UsePrevious

func UsePrevious[T any](parseValue T) Previous[T]

UsePrevious reports no previous value on non-browser targets.

func (Previous[T]) Get

func (parseP Previous[T]) Get() T

Get returns the previous committed value or the zero value when unavailable.

func (Previous[T]) Ok

func (parseP Previous[T]) Ok() bool

Ok reports whether a previous committed value is available.

type ReactiveSource

type ReactiveSource interface {
	ReactiveRegionSourceIDs() []string
}

ReactiveSource identifies shared values that a ReactiveRegion can subscribe to explicitly.

type Reducer

type Reducer[S any, A any] struct {
	// contains filtered or unexported fields
}

Reducer provides access to reducer-style local state transitions.

func UseReducer

func UseReducer[S any, A any](parseReducer func(S, A) S, parseInitialState S) Reducer[S, A]

UseReducer returns a lightweight reducer-backed handle on non-browser targets.

func (Reducer[S, A]) Dispatch

func (parseR Reducer[S, A]) Dispatch(parseAction A)

Dispatch applies an action to the reducer state.

func (Reducer[S, A]) Get

func (parseR Reducer[S, A]) Get() S

Get returns the current reducer state.

type Ref

type Ref[T any] struct {
	// contains filtered or unexported fields
}

Ref stores a stable mutable reference across renders.

func UseRef

func UseRef[T any](parseInitialValue T) Ref[T]

UseRef creates a stable mutable reference across renders.

func (Ref[T]) Get

func (parseR Ref[T]) Get() T

Get returns the current ref value.

func (Ref[T]) Set

func (parseR Ref[T]) Set(parseValue T)

Set updates the current ref value.

type SSRBootstrap

type SSRBootstrap struct {
	Version       int               `json:"version,omitempty"`
	CorrelationID string            `json:"correlationId,omitempty"`
	Route         SSRRouteBootstrap `json:"route"`
	Atoms         map[string]any    `json:"atoms,omitempty"`
	Data          map[string]any    `json:"data,omitempty"`
	I18n          SSRI18nBootstrap  `json:"i18n"`
	IDSeed        int               `json:"idSeed,omitempty"`
}

SSRBootstrap captures the server-provided state needed to resume a route on the client.

func Hydrate

func Hydrate(parseRoot Node, parseSelector string, parseOptions ...HydrationOptions) (SSRBootstrap, error)

Hydrate is a non-browser stub that returns an UnsupportedOnServer error.

func HydrateInto

func HydrateInto(parseRoot Node, parseTarget any, parseOptions ...HydrationOptions) (SSRBootstrap, error)

HydrateInto is a non-browser stub that returns an UnsupportedOnServer error.

func ReadBootstrapReference

func ReadBootstrapReference(parseRef SSRBootstrapReference) (SSRBootstrap, error)

ReadBootstrapReference is a non-browser stub that returns an UnsupportedOnServer error.

func ReadBootstrapScript

func ReadBootstrapScript(parseScriptID string) (SSRBootstrap, error)

ReadBootstrapScript is a non-browser stub that returns an UnsupportedOnServer error.

func UnmarshalSSRBootstrap

func UnmarshalSSRBootstrap(parseData []byte) (SSRBootstrap, error)

UnmarshalSSRBootstrap deserializes a JSON bootstrap payload.

func UnmarshalSSRBootstrapBinary

func UnmarshalSSRBootstrapBinary(parseData []byte) (SSRBootstrap, error)

UnmarshalSSRBootstrapBinary deserializes a CBOR bootstrap payload.

type SSRBootstrapBudget

type SSRBootstrapBudget struct {
	InlineWarnBytes   int
	InlineErrorBytes  int
	SidecarWarnBytes  int
	SidecarErrorBytes int
	BinaryWarnBytes   int
	BinaryErrorBytes  int
}

SSRBootstrapBudget defines threshold bands for inline, sidecar, and binary payloads.

func NewSSRBootstrapBudget

func NewSSRBootstrapBudget() SSRBootstrapBudget

NewSSRBootstrapBudget returns the default bootstrap size thresholds.

type SSRBootstrapMetrics

type SSRBootstrapMetrics struct {
	Format       string
	PayloadBytes int
	ScriptBytes  int
}

SSRBootstrapMetrics captures one bootstrap serialization size sample.

type SSRBootstrapReference

type SSRBootstrapReference struct {
	Version int    `json:"version,omitempty"`
	URL     string `json:"url,omitempty"`
	Format  string `json:"format,omitempty"`
}

SSRBootstrapReference points the client at an external bootstrap payload.

func ReadBootstrapReferenceScript

func ReadBootstrapReferenceScript(parseScriptID string) (SSRBootstrapReference, error)

ReadBootstrapReferenceScript is a non-browser stub that returns an UnsupportedOnServer error.

func UnmarshalSSRBootstrapReference

func UnmarshalSSRBootstrapReference(parseData []byte) (SSRBootstrapReference, error)

UnmarshalSSRBootstrapReference deserializes a bootstrap reference payload.

type SSRBootstrapSizeReport

type SSRBootstrapSizeReport struct {
	Version            int
	JSONPayloadBytes   int
	InlineScriptBytes  int
	BinaryPayloadBytes int
	Recommendation     string
	Warnings           []string
	Errors             []string
	Payloads           []SSRPayloadMetadata
}

SSRBootstrapSizeReport summarizes payload sizes, warnings, and the recommended transport mode.

func InspectSSRBootstrapSize

func InspectSSRBootstrapSize(parsePayload SSRBootstrap, parseBudget SSRBootstrapBudget) (SSRBootstrapSizeReport, error)

InspectSSRBootstrapSize measures payload sizes, budget bands, and the recommended transport mode.

type SSRHydrationMetrics

type SSRHydrationMetrics struct {
	StartedAt            time.Time
	FinishedAt           time.Time
	Duration             time.Duration
	DurationNs           int64
	ExistingDOMNodeCount int
	FallbackCount        int
	MismatchCount        int
	DiscardedNodeCount   int
	Strict               bool
	Failed               bool
	Failure              string
}

SSRHydrationMetrics captures one client hydration pass summary.

type SSRI18nBootstrap

type SSRI18nBootstrap struct {
	Locale         string                               `json:"locale,omitempty"`
	FallbackLocale string                               `json:"fallbackLocale,omitempty"`
	Direction      string                               `json:"direction,omitempty"`
	Messages       map[string]map[string]SSRI18nMessage `json:"messages,omitempty"`
}

type SSRI18nMessage

type SSRI18nMessage struct {
	Text      string            `json:"text,omitempty"`
	PluralArg string            `json:"pluralArg,omitempty"`
	Plural    map[string]string `json:"plural,omitempty"`
	SelectArg string            `json:"selectArg,omitempty"`
	Select    map[string]string `json:"select,omitempty"`
	Default   string            `json:"default,omitempty"`
}

type SSRObservabilityOptions

type SSRObservabilityOptions struct {
	CorrelationID string
	OnEvent       func(SSRObservation)
}

SSRObservabilityOptions configures per-operation SSR observability metadata.

func SSRObservabilityOptionsFromContext

func SSRObservabilityOptionsFromContext(parseCtx context.Context) SSRObservabilityOptions

SSRObservabilityOptionsFromContext builds SSRObservabilityOptions using the correlation ID stored in ctx by WrapSSRCorrelation or WithCorrelationID.

opts := ui.SSRObservabilityOptionsFromContext(r.Context())
markup, err := ui.RenderToStringObserved(root, opts)

type SSRObservation

type SSRObservation struct {
	Name          string
	Domain        string
	Phase         string
	Timestamp     time.Time
	CorrelationID string
	Render        *SSRRenderMetrics
	Bootstrap     *SSRBootstrapMetrics
	Hydration     *SSRHydrationMetrics
}

SSRObservation describes one SSR or hydration observability event.

type SSRObserverSubscription

type SSRObserverSubscription struct {
	// contains filtered or unexported fields
}

SSRObserverSubscription is the cleanup handle returned by RegisterSSRObserver.

func RegisterSSRObserver

func RegisterSSRObserver(parseNotify func(SSRObservation)) SSRObserverSubscription

RegisterSSRObserver subscribes to framework-owned SSR and hydration observability events. Call Cancel on the returned subscription to unsubscribe.

func (SSRObserverSubscription) Cancel

func (parseS SSRObserverSubscription) Cancel()

Cancel unregisters the SSR observer installed by RegisterSSRObserver.

type SSRPayloadEncoding

type SSRPayloadEncoding string
const (
	SSRPayloadEncodingJSON         SSRPayloadEncoding = "json"
	SSRPayloadEncodingText         SSRPayloadEncoding = "text"
	SSRPayloadEncodingBinary       SSRPayloadEncoding = "binary"
	SSRPayloadEncodingTimeRFC3339  SSRPayloadEncoding = "time-rfc3339"
	SSRPayloadEncodingTimeUnixNano SSRPayloadEncoding = "time-unix-nano"
	SSRPayloadEncodingCBOR         SSRPayloadEncoding = "cbor"
)

type SSRPayloadEnvelope

type SSRPayloadEnvelope struct {
	Version     int                   `json:"version,omitempty"`
	Kind        SSRPayloadKind        `json:"kind,omitempty"`
	Scope       SSRPayloadScope       `json:"scope,omitempty"`
	Target      string                `json:"target,omitempty"`
	ReusePolicy SSRPayloadReusePolicy `json:"reusePolicy,omitempty"`
	Revision    string                `json:"revision,omitempty"`
	Encoding    SSRPayloadEncoding    `json:"encoding,omitempty"`
	JSON        json.RawMessage       `json:"json,omitempty"`
	Text        string                `json:"text,omitempty"`
	Binary      []byte                `json:"binary,omitempty"`
}

SSRPayloadEnvelope stores one typed bootstrap payload entry inside SSRBootstrap.Data.

type SSRPayloadFilter

type SSRPayloadFilter struct {
	Kind   SSRPayloadKind
	Scope  SSRPayloadScope
	Target string
}

SSRPayloadFilter filters payload inspection output by kind, scope, or target.

type SSRPayloadKind

type SSRPayloadKind string
const (
	SSRPayloadKindData         SSRPayloadKind = "data"
	SSRPayloadKindRouteData    SSRPayloadKind = "route-data"
	SSRPayloadKindFormDefaults SSRPayloadKind = "form-defaults"
	SSRPayloadKindCacheSeed    SSRPayloadKind = "cache-seed"
	SSRPayloadKindSessionHint  SSRPayloadKind = "session-hint"
)

type SSRPayloadMetadata

type SSRPayloadMetadata struct {
	Key         string
	Version     int
	Kind        SSRPayloadKind
	Scope       SSRPayloadScope
	Target      string
	ReusePolicy SSRPayloadReusePolicy
	Revision    string
	Encoding    SSRPayloadEncoding
	Legacy      bool
}

SSRPayloadMetadata summarizes one payload registration for diagnostics and scoping.

func InspectBootstrapPayloads

func InspectBootstrapPayloads(parseBootstrap SSRBootstrap, filter SSRPayloadFilter) ([]SSRPayloadMetadata, error)

InspectBootstrapPayloads lists typed payload registrations and legacy payloads, optionally filtered by kind, scope, or target.

type SSRPayloadOptions

type SSRPayloadOptions struct {
	Kind        SSRPayloadKind
	Scope       SSRPayloadScope
	Target      string
	ReusePolicy SSRPayloadReusePolicy
	Revision    string
	Encoding    SSRPayloadEncoding
}

SSRPayloadOptions configures one typed bootstrap payload registration.

type SSRPayloadReusePolicy

type SSRPayloadReusePolicy string
const (
	SSRPayloadReuseTrustOnFirstResume    SSRPayloadReusePolicy = "trust-once"
	SSRPayloadReuseRevalidateAfterResume SSRPayloadReusePolicy = "revalidate-after-resume"
	SSRPayloadReuseClientOwned           SSRPayloadReusePolicy = "client-owned"
)

type SSRPayloadScope

type SSRPayloadScope string
const (
	SSRPayloadScopeApp     SSRPayloadScope = "app"
	SSRPayloadScopeRoute   SSRPayloadScope = "route"
	SSRPayloadScopeSubtree SSRPayloadScope = "subtree"
)

type SSRPayloadValue

type SSRPayloadValue[T any] struct {
	Key         string
	Kind        SSRPayloadKind
	Scope       SSRPayloadScope
	Target      string
	ReusePolicy SSRPayloadReusePolicy
	Revision    string
	Encoding    SSRPayloadEncoding
	Value       T
}

SSRPayloadValue is the typed result of reading a bootstrap payload entry.

func ReadBootstrapPayload

func ReadBootstrapPayload[T any](parseBootstrap SSRBootstrap, parseKey string) (SSRPayloadValue[T], bool, error)

ReadBootstrapPayload reads one typed payload entry from SSRBootstrap.Data.

func ReadCacheBootstrapSeed

func ReadCacheBootstrapSeed[T any](parseBootstrap SSRBootstrap, cacheKey string) (SSRPayloadValue[T], bool, error)

ReadCacheBootstrapSeed reads a typed cache seed from a cache-scoped payload key.

func ReadFormBootstrapDefaults

func ReadFormBootstrapDefaults[T any](parseBootstrap SSRBootstrap, parseFormID string) (SSRPayloadValue[T], bool, error)

ReadFormBootstrapDefaults reads typed form defaults from a form-scoped payload key.

func ReadRouteBootstrapData

func ReadRouteBootstrapData[T any](parseBootstrap SSRBootstrap, parseKey string, parseRoutePath string) (SSRPayloadValue[T], bool, error)

ReadRouteBootstrapData reads typed route data from a route-scoped payload key.

func ReadSessionBootstrapHint

func ReadSessionBootstrapHint[T any](parseBootstrap SSRBootstrap, parseHintKey string) (SSRPayloadValue[T], bool, error)

ReadSessionBootstrapHint reads a typed session hint from an app-scoped payload key.

type SSRRenderMetrics

type SSRRenderMetrics struct {
	Duration   time.Duration
	DurationNs int64
}

SSRRenderMetrics captures one server render duration sample.

type SSRRouteBootstrap

type SSRRouteBootstrap struct {
	Path   string              `json:"path,omitempty"`
	Query  map[string][]string `json:"query,omitempty"`
	Params map[string]string   `json:"params,omitempty"`
}

SSRRouteBootstrap captures the routed path, query, and params transferred from server to client.

type SSRScriptOptions

type SSRScriptOptions struct {
	Nonce string
}

type SSRStateUpdate

type SSRStateUpdate struct {
	Version       int                           `json:"version,omitempty"`
	CorrelationID string                        `json:"correlationId,omitempty"`
	Scope         SSRPayloadScope               `json:"scope,omitempty"`
	Target        string                        `json:"target,omitempty"`
	Upserts       map[string]SSRPayloadEnvelope `json:"upserts,omitempty"`
	Deletes       []string                      `json:"deletes,omitempty"`
}

SSRStateUpdate is a versioned text or binary update envelope for post-hydration payload refreshes.

func UnmarshalSSRStateUpdateBinary

func UnmarshalSSRStateUpdateBinary(parseData []byte) (SSRStateUpdate, error)

UnmarshalSSRStateUpdateBinary decodes a CBOR state-update envelope.

func UnmarshalSSRStateUpdateText

func UnmarshalSSRStateUpdateText(parseData []byte) (SSRStateUpdate, error)

UnmarshalSSRStateUpdateText decodes a JSON text state-update envelope.

type SSRStreamChunk

type SSRStreamChunk = runtime.SSRStreamChunk

SSRStreamChunk describes one emitted streaming SSR chunk.

type SSRStreamOptions

type SSRStreamOptions = runtime.SSRStreamOptions

SSRStreamOptions configures streaming SSR output.

type ServerActionFlash

type ServerActionFlash struct {
	Kind    string `json:"kind,omitempty"`
	Title   string `json:"title,omitempty"`
	Message string `json:"message,omitempty"`
}

type ServerActionOutcome

type ServerActionOutcome string
const (
	ServerActionOutcomeSuccess         ServerActionOutcome = "success"
	ServerActionOutcomeRedirect        ServerActionOutcome = "redirect"
	ServerActionOutcomeValidationError ServerActionOutcome = "validation_error"
	ServerActionOutcomeAuthError       ServerActionOutcome = "auth_error"
	ServerActionOutcomeRetryableError  ServerActionOutcome = "retryable_error"
)

type ServerActionRedirect

type ServerActionRedirect struct {
	Location string `json:"location,omitempty"`
	Replace  bool   `json:"replace,omitempty"`
}

type ServerActionRefresh

type ServerActionRefresh struct {
	Revalidate bool     `json:"revalidate,omitempty"`
	CacheKeys  []string `json:"cacheKeys,omitempty"`
}

type ServerActionResult

type ServerActionResult struct {
	Outcome  ServerActionOutcome   `json:"outcome,omitempty"`
	Error    string                `json:"error,omitempty"`
	Message  string                `json:"message,omitempty"`
	Fields   FieldErrors           `json:"fields,omitempty"`
	Redirect *ServerActionRedirect `json:"redirect,omitempty"`
	Flash    *ServerActionFlash    `json:"flash,omitempty"`
	Refresh  *ServerActionRefresh  `json:"refresh,omitempty"`
}

func (ServerActionResult) FormErrors

func (parseR ServerActionResult) FormErrors() ServerFormErrors

FormErrors is a core package helper.

func (ServerActionResult) HasRedirect

func (parseR ServerActionResult) HasRedirect() bool

HasRedirect is a core package helper.

func (ServerActionResult) HasRefresh

func (parseR ServerActionResult) HasRefresh() bool

HasRefresh is a core package helper.

func (ServerActionResult) RedirectLocation

func (parseR ServerActionResult) RedirectLocation() string

RedirectLocation is a core package helper.

type ServerFormErrors

type ServerFormErrors struct {
	Error   string      `json:"error,omitempty"`
	Message string      `json:"message,omitempty"`
	Fields  FieldErrors `json:"fields,omitempty"`
}

func (ServerFormErrors) FormMessage

func (parseE ServerFormErrors) FormMessage() string

FormMessage is a core package helper.

type State

type State[T any] struct {
	// contains filtered or unexported fields
}

State provides access to hook-managed local state.

func UseState

func UseState[T any](parseInitialValue T) State[T]

UseState creates local component state on non-browser targets.

Example

ExampleUseState shows local component state: a counter component reads and updates its own state with the State handle returned by UseState.

package main

import (
	"fmt"

	"github.com/monstercameron/GoWebComponents/v4/html"
	"github.com/monstercameron/GoWebComponents/v4/ui"
)

// exampleCounter reads and updates its own state with the State handle
// returned by UseState. Hooks belong at the top level of a component function.
func exampleCounter(_ struct{}) ui.Node {
	parseCount := ui.UseState(0)
	return html.Div(html.Props{},
		html.Button(html.Props{}, html.Text(fmt.Sprintf("count: %d", parseCount.Get()))),
	)
}

// ExampleUseState shows local component state: a counter component reads and
// updates its own state with the State handle returned by UseState.
func main() {
	// Mount with ui.Render(ui.CreateElement(exampleCounter, struct{}{}), "#app")
	// in a browser; here we just build the element tree.
	_ = ui.CreateElement(exampleCounter, struct{}{})
}

func (State[T]) Get

func (parseS State[T]) Get() T

Get returns the current state value.

func (State[T]) Set

func (parseS State[T]) Set(parseValue T)

Set replaces the current state value.

func (State[T]) Update

func (parseS State[T]) Update(parseFn func(T) T)

Update replaces the state value using the previous value.

type SuspenseValue

type SuspenseValue[T any] struct {
	Value  T
	Ready  bool
	Error  error
	Done   <-chan struct{}
	Reason string
}

SuspenseValue describes a render-time value that may not be ready yet.

type Throttled

type Throttled[T any] struct {
	// contains filtered or unexported fields
}

Throttled returns a trailing-throttled view of a value on browser builds; on native builds it is immediate.

func UseThrottled

func UseThrottled[T any](parseValue T, parseInterval time.Duration) Throttled[T]

UseThrottled returns the current value unchanged on non-browser targets.

func (Throttled[T]) Get

func (parseT Throttled[T]) Get() T

Get returns the current throttled value.

func (Throttled[T]) Pending

func (parseT Throttled[T]) Pending() bool

Pending reports whether a throttled update is pending.

type Transition

type Transition struct {
	// contains filtered or unexported fields
}

Transition exposes transition-pending state and a transition starter.

func UseTransition

func UseTransition() Transition

UseTransition returns a no-op transition helper on non-browser targets.

func (Transition) Pending

func (parseT Transition) Pending() bool

Pending reports whether a transition is currently pending.

func (Transition) Start

func (parseT Transition) Start(parseFn func())

Start runs fn inside a transition.

type W3CTraceContext

type W3CTraceContext struct {
	TraceID      string
	ParentSpanID string
	SpanID       string
	Flags        string
	TraceState   string
}

W3CTraceContext holds a parsed W3C Trace Context propagation envelope (https://www.w3.org/TR/trace-context/).

TraceID is the 128-bit trace identifier (32 lowercase hex chars). ParentSpanID is the 64-bit span identifier received from the upstream caller (16 hex chars). SpanID is the 64-bit span identifier for this server-side operation (16 hex chars, newly generated). Flags is the two-hex-char trace flags field ("01" = sampled, "00" = not sampled). TraceState is the raw, opaque tracestate header value forwarded without modification.

When stored by WrapSSRCorrelation, TraceID equals the value returned by CorrelationIDFromContext so the two surfaces remain consistent.

func TraceContextFromContext

func TraceContextFromContext(parseCtx context.Context) (W3CTraceContext, bool)

TraceContextFromContext returns the W3C trace context stored by WrapSSRCorrelation, and whether one was found.

func (W3CTraceContext) IsValid

func (parseTc W3CTraceContext) IsValid() bool

IsValid reports whether the trace context carries a usable 128-bit trace ID.

func (W3CTraceContext) Traceparent

func (parseTc W3CTraceContext) Traceparent() string

Traceparent formats the context as a W3C traceparent header value using SpanID as the current operation identifier so downstream callers can continue the trace.

type WASMStackFrame

type WASMStackFrame = runtime.WASMStackFrame

WASMStackFrame describes one wasm/browser panic frame (function, source file, line) for stack-correlation mapping. It is the public alias of the runtime frame type.

Directories

Path Synopsis
Package erroroverlay renders an Elm-grade, in-page error overlay as a GoWebComponents component (FB4).
Package erroroverlay renders an Elm-grade, in-page error overlay as a GoWebComponents component (FB4).

Jump to

Keyboard shortcuts

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