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 ¶
- Constants
- Variables
- func ApplySSRStateUpdate(parseBootstrap *SSRBootstrap, parseUpdate SSRStateUpdate) error
- func Await[T any](parseValue SuspenseValue[T]) T
- func BuildParallelRegionSourceIDs(parseSources ...ReactiveSource) ([]string, error)
- func CSSEscape(parseValue string) string
- func ConfigureBootstrapCorrelation(parseCtx context.Context, parseBootstrap *SSRBootstrap)
- func ConfigureHydrationIslandBudget(parseBudget HydrationIslandBudget)
- func CorrelationIDFromContext(parseCtx context.Context) string
- func CurrentTheme() string
- func Download(parseData []byte, parseName, parseMime string)
- func GetSSRObservationAttributes(parseObservation SSRObservation) map[string]string
- func HydrateIsland(parseRoot Node, parseOptions HydrationIslandOptions) (func(), error)
- func MarshalSSRBootstrap(parsePayload SSRBootstrap) ([]byte, error)
- func MarshalSSRBootstrapBinary(parsePayload SSRBootstrap) ([]byte, error)
- func MarshalSSRBootstrapBinaryObserved(parsePayload SSRBootstrap, parseOptions SSRObservabilityOptions) ([]byte, error)
- func MarshalSSRBootstrapObserved(parsePayload SSRBootstrap, parseOptions SSRObservabilityOptions) ([]byte, error)
- func MarshalSSRStateUpdateBinary(parseUpdate SSRStateUpdate) ([]byte, error)
- func MarshalSSRStateUpdateText(parseUpdate SSRStateUpdate) ([]byte, error)
- func OnReady(parseFn func())
- func PickFile(parseAccept string, parseOnPick func(PickedFile))
- func RegisterBootstrapPayload[T any](parseBootstrap *SSRBootstrap, parseKey string, parseValue T, ...) error
- func RegisterCacheBootstrapSeed[T any](parseBootstrap *SSRBootstrap, cacheKey string, parseValue T, ...) error
- func RegisterFormBootstrapDefaults[T any](parseBootstrap *SSRBootstrap, parseFormID string, parseValue T, ...) error
- func RegisterParallelRegion[Props any](parseRendererID string, parseRender func(Props) Node) error
- func RegisterRouteBootstrapData[T any](parseBootstrap *SSRBootstrap, parseKey string, parseRoutePath string, ...) error
- func RegisterSessionBootstrapHint[T any](parseBootstrap *SSRBootstrap, parseHintKey string, parseValue T, ...) error
- func RegisterStateUpdatePayload[T any](parseUpdate *SSRStateUpdate, parseKey string, parseValue T, ...) error
- func Render(parseRoot Node, parseSelector string)
- func RenderBootstrapReferenceScript(parseRef SSRBootstrapReference, parseScriptID string) (string, error)
- func RenderBootstrapReferenceScriptWithOptions(parseRef SSRBootstrapReference, parseScriptID string, ...) (string, error)
- func RenderBootstrapScript(parsePayload SSRBootstrap, parseScriptID string) (string, error)
- func RenderBootstrapScriptObserved(parsePayload SSRBootstrap, parseScriptID string, ...) (string, error)
- func RenderBootstrapScriptWithOptions(parsePayload SSRBootstrap, parseScriptID string, ...) (string, error)
- func RenderInto(parseRoot Node, parseTarget any) error
- func RenderToStream(parseCtx context.Context, parseWriter io.Writer, parseRoot Node, ...) error
- func RenderToStreamObserved(parseCtx context.Context, parseWriter io.Writer, parseRoot Node, ...) error
- func RenderToString(parseRoot Node) (string, error)
- func RenderToStringObserved(parseRoot Node, parseOptions SSRObservabilityOptions) (string, error)
- func ResetWASMStackFrameMapper()
- func Run(parseSelector string, parseComponent any, parseProps ...any)
- func SafeGo(parseSubject string, parseFn func())
- func SelectorID(parseID string) string
- func SetInspectSink(parseSink func(string)) func()
- func SetParallelRegionWorkerRenderer(parseRendererID string, parseRender runtime2.WorkerRegionRenderer) error
- func SetParallelRegionWorkerRendererWithConfig(parseRendererID string, parseRender runtime2.WorkerRegionRenderer, ...) error
- func SetTheme(parseName string)
- func SetWASMStackFrameMapper(parseMapper func(WASMStackFrame) (WASMStackFrame, bool))
- func StartTransition(parseFn func())
- func SuspendUntil(parseDone <-chan struct{}, parseReason ...string)
- func Typed[P any](parseComponent func(P) Node) func(P) Node
- func UnsupportedOnServer(parseName string) error
- func UseAction[T any](parseCache *query.Cache, parseKey string) (query.Result[T], func(parseOptimistic T, parseFn func() (T, error)))
- func UseAnimationRestart(parseRef DOMRef, parseClassName string, parseDeps ...any)
- func UseAsyncMutation[T any](parseCache *query.Cache, parseKey string) func(parseOptimistic T, parseFn func() (T, error))
- func UseAutoFocus(parseRef DOMRef, parseDeps ...any)
- func UseCallback[T any](parseFn T, parseDeps ...any) T
- func UseContext[T any](parseContext *Context[T]) T
- func UseDefer(parseTriggered bool) bool
- func UseDeferredValue[T any](parseValue T) T
- func UseDocumentEvent(eventType string, handler func(Event), deps ...any)
- func UseEffect(parseEffect func() func(), parseDeps ...any)
- func UseEffectOf[D comparable](parseEffect func() func(), parseDep D)
- func UseElementGeometry(parseRef DOMRef) interop.Rect
- func UseFocusTrap(parseOptions FocusTrapOptions)
- func UseForceUpdate() func()
- func UseGlobalKey(handler func(KeyboardEvent), deps ...any)
- func UseId() string
- func UseIdle() bool
- func UseInspect[T any](parseLabel string, parseValue T)
- func UseInteraction(parseRef DOMRef) bool
- func UseIntersection(parseRef DOMRef, parseOptions ...interop.IntersectionObserverOptions) bool
- func UseInterval(parseFn func(), parseInterval time.Duration, parseDeps ...any)
- func UseLayoutEffect(parseEffect func() func(), parseDeps ...any)
- func UseMediaQuery(parseQuery string) bool
- func UseMemo[T any](parseCompute func() T, parseDeps ...any) T
- func UseMemoOf[T any, D comparable](parseCompute func(D) T, parseDep D) T
- func UseMount(parseFn func() func())
- func UseMutation[T any](parseCache *query.Cache, parseKey string) func(parseOptimistic T, parseFn func() (T, error)) query.Result[T]
- func UseNetworkStatus() bool
- func UseOptimistic[T any](parseCache *query.Cache, parseKey string) (query.Result[T], func(T))
- func UsePointerEvents(parseRef DOMRef, parseHandlers PointerHandlers)
- func UsePrefersReducedMotion() bool
- func UseQuery[T any](parseCache *query.Cache, parseKey string, parseFetcher func() (T, error), ...) query.Result[T]
- func UseRevalidateOnFocus(parseCache *query.Cache)
- func UseSpring(parseTarget float64, parseConfig anim.SpringConfig) float64
- func UseSuspenseQuery[T any](parseCache *query.Cache, parseKey string, parseFetcher func() (T, error), ...) T
- func UseTheme(parseDefault string) (string, func(string))
- func UseTimeout(parseFn func(), parseDelay time.Duration, parseDeps ...any)
- func UseTimerTrigger(parseDelay time.Duration) bool
- func UseWheel(parseRef DOMRef, parseHandler func(Event))
- func UseWindowEvent(eventType string, handler func(Event), deps ...any)
- func ViewTransition(parseApply func())
- func WithCorrelationID(parseCtx context.Context, parseId string) context.Context
- func WithW3CTraceContext(parseCtx context.Context, parseTc W3CTraceContext) context.Context
- func WrapSSRCorrelation(parseNext http.Handler) http.Handler
- type AccessibleOverlayProps
- type AnnouncementMode
- type Announcer
- func (parseA Announcer) Announce(parseMode AnnouncementMode, parseMessage string)
- func (parseA Announcer) Assertive(parseMessage string)
- func (parseA Announcer) AssertiveID() string
- func (parseA Announcer) Clear()
- func (parseA Announcer) Polite(parseMessage string)
- func (parseA Announcer) PoliteID() string
- func (parseA Announcer) Region() Node
- type AsyncBoundaryProps
- type CSRFToken
- type ChangeEvent
- type ColorScheme
- type CompositeItem
- type CompositeNavigation
- func (parseN CompositeNavigation) ActiveDescendant() string
- func (parseN CompositeNavigation) ActiveID() string
- func (parseN CompositeNavigation) ActiveIndex() int
- func (parseN CompositeNavigation) IsActive(parseIndex int) bool
- func (parseN CompositeNavigation) MoveEnd()
- func (parseN CompositeNavigation) MoveHome()
- func (parseN CompositeNavigation) MoveNext()
- func (parseN CompositeNavigation) MovePrevious()
- func (parseN CompositeNavigation) OnKeyDown(parseEvent any)
- func (parseN CompositeNavigation) SetActive(parseIndex int)
- func (parseN CompositeNavigation) TabIndex(parseIndex int) int
- type CompositeNavigationOptions
- type Context
- type ContextProvider
- type ContextProviderProps
- type DOMRef
- type Debounced
- type DeferBlocks
- type DeferState
- type DeferStatus
- type Element
- type ErrorBoundaryProps
- type Event
- type FieldErrors
- type FieldStatus
- type File
- type FocusEvent
- type FocusManager
- func (parseM FocusManager) FocusByID(parseId string, parseOptions ...FocusOptions) bool
- func (parseM FocusManager) FocusFirst(parseContainerSelector string, parseOptions ...FocusOptions) bool
- func (parseM FocusManager) FocusFirstError(parseErrors FieldErrors, parseFieldIDs map[string]string, parseOrder ...string) bool
- func (parseM FocusManager) FocusSelector(parseSelector string, parseOptions ...FocusOptions) bool
- func (parseM FocusManager) RememberActive() bool
- func (parseM FocusManager) Restore(parseOptions ...FocusOptions) bool
- type FocusOptions
- type FocusTrapOptions
- type Form
- func (parseF Form[T]) ApplyServerActionResult(parseResult ServerActionResult) bool
- func (parseF Form[T]) ApplyServerErrors(parseResponse ServerFormErrors) bool
- func (parseF Form[T]) Dirty(parseName string) bool
- func (parseF Form[T]) DirtyAny() bool
- func (parseF Form[T]) Error(parseName string) string
- func (parseF Form[T]) Errors() FieldErrors
- func (parseF Form[T]) FieldMessage(parseName string) string
- func (parseF Form[T]) FieldStatus(parseName string) FieldStatus
- func (parseF Form[T]) FormError() string
- func (parseF Form[T]) Get() T
- func (parseF Form[T]) HasErrors() bool
- func (parseF Form[T]) HasField(parseName string) bool
- func (parseF Form[T]) HasFieldError(parseName string) bool
- func (parseF Form[T]) IntentPending(parseIntent string) bool
- func (parseF Form[T]) MustSetField(parseName string, parseValue any)
- func (parseF Form[T]) Reset(parseNext ...T)
- func (parseF Form[T]) Set(parseValue T)
- func (parseF Form[T]) SetErrors(parseErrors FieldErrors)
- func (parseF Form[T]) SetField(parseName string, parseValue any) bool
- func (parseF Form[T]) SetFormError(parseMessage string)
- func (parseF Form[T]) SetSubmitIntent(parseIntent string)
- func (parseF Form[T]) Submit(parseRun func(T) error)
- func (parseF Form[T]) SubmitError() error
- func (parseF Form[T]) SubmitIntent() string
- func (parseF Form[T]) SubmitWithIntent(parseIntent string, parseRun func(T, string) error)
- func (parseF Form[T]) Submitted() bool
- func (parseF Form[T]) Submitting() bool
- func (parseF Form[T]) Touch(parseName string)
- func (parseF Form[T]) Touched(parseName string) bool
- func (parseF Form[T]) TouchedAny() bool
- func (parseF Form[T]) Update(parseFn func(T) T)
- func (parseF Form[T]) Validate(parseValidate func(T) FieldErrors) bool
- func (parseF Form[T]) ValidateAsync(parseValidate func(T) (FieldErrors, string), parseOnComplete func(bool))
- func (parseF Form[T]) ValidateIntent(parseIntent string, parseValidate func(T, string) FieldErrors) bool
- func (parseF Form[T]) ValidateStruct() bool
- func (parseF Form[T]) Validated() bool
- func (parseF Form[T]) Validating() bool
- type FormEvent
- type Handler
- type HotReloadBoundaryProps
- type HydrationIslandBudget
- type HydrationIslandBudgetReport
- type HydrationIslandOptions
- type HydrationIslandPlan
- type HydrationOptions
- type HydrationStrategy
- type InputEvent
- type KeyboardEvent
- type LazyNode
- type LazyNodeState
- type LazyProps
- type MatchBuilder
- type MouseEvent
- type Node
- func AccessibleOverlay(parseProps AccessibleOverlayProps) Node
- func AsyncBoundary(parseProps AsyncBoundaryProps) Node
- func Component(parseComponentType any, parseComponentProps ...any) Node
- func CreateElement(parseComponent any, parseProps ...any) Node
- func Fragment(parseChildren ...Node) Node
- func HotReloadBoundary(parseBoundaryProps HotReloadBoundaryProps) Node
- func HydrationIsland(parseOptions HydrationIslandOptions, parseContent Node) Node
- func If(isCondition bool, parseBranchTrue NodeFactory, parseBranchFalse ...NodeFactory) Node
- func Lazy(parseProps LazyProps) Node
- func NewErrorBoundary(parseProps ErrorBoundaryProps) Node
- func Overlay(parseOverlayProps OverlayProps) Node
- func ParallelRegion[Props any](parseSpec ParallelRegionSpec[Props]) Node
- func Portal(parseProps PortalProps) Node
- func ReactiveRegion(render func() Node, parseSources ...ReactiveSource) Node
- func RenderDefer[T any](parseState DeferState[T], parseBlocks DeferBlocks[T]) Node
- func Text(parseContent string) Node
- type NodeFactory
- type OverlayKind
- type OverlayProps
- type OverlayStack
- type OverlayStackOptions
- type ParallelRegionSpec
- type ParallelRegionStatus
- type ParallelRegionWorkerRendererConfig
- type PersistStorageArea
- type PersistedState
- type PickedFile
- type PointerHandlers
- type PortalProps
- type PortalTarget
- type Previous
- type ReactiveSource
- type Reducer
- type Ref
- type SSRBootstrap
- func Hydrate(parseRoot Node, parseSelector string, parseOptions ...HydrationOptions) (SSRBootstrap, error)
- func HydrateInto(parseRoot Node, parseTarget any, parseOptions ...HydrationOptions) (SSRBootstrap, error)
- func ReadBootstrapReference(parseRef SSRBootstrapReference) (SSRBootstrap, error)
- func ReadBootstrapScript(parseScriptID string) (SSRBootstrap, error)
- func UnmarshalSSRBootstrap(parseData []byte) (SSRBootstrap, error)
- func UnmarshalSSRBootstrapBinary(parseData []byte) (SSRBootstrap, error)
- type SSRBootstrapBudget
- type SSRBootstrapMetrics
- type SSRBootstrapReference
- type SSRBootstrapSizeReport
- type SSRHydrationMetrics
- type SSRI18nBootstrap
- type SSRI18nMessage
- type SSRObservabilityOptions
- type SSRObservation
- type SSRObserverSubscription
- type SSRPayloadEncoding
- type SSRPayloadEnvelope
- type SSRPayloadFilter
- type SSRPayloadKind
- type SSRPayloadMetadata
- type SSRPayloadOptions
- type SSRPayloadReusePolicy
- type SSRPayloadScope
- type SSRPayloadValue
- func ReadBootstrapPayload[T any](parseBootstrap SSRBootstrap, parseKey string) (SSRPayloadValue[T], bool, error)
- func ReadCacheBootstrapSeed[T any](parseBootstrap SSRBootstrap, cacheKey string) (SSRPayloadValue[T], bool, error)
- func ReadFormBootstrapDefaults[T any](parseBootstrap SSRBootstrap, parseFormID string) (SSRPayloadValue[T], bool, error)
- func ReadRouteBootstrapData[T any](parseBootstrap SSRBootstrap, parseKey string, parseRoutePath string) (SSRPayloadValue[T], bool, error)
- func ReadSessionBootstrapHint[T any](parseBootstrap SSRBootstrap, parseHintKey string) (SSRPayloadValue[T], bool, error)
- type SSRRenderMetrics
- type SSRRouteBootstrap
- type SSRScriptOptions
- type SSRStateUpdate
- type SSRStreamChunk
- type SSRStreamOptions
- type ServerActionFlash
- type ServerActionOutcome
- type ServerActionRedirect
- type ServerActionRefresh
- type ServerActionResult
- type ServerFormErrors
- type State
- type SuspenseValue
- type Throttled
- type Transition
- type W3CTraceContext
- type WASMStackFrame
Examples ¶
Constants ¶
const ( SSRBootstrapFormatJSON = "json" SSRBootstrapFormatCBOR = "cbor" )
const ( // SSRStreamChunkShell identifies the initial streaming SSR shell chunk. SSRStreamChunkShell = runtime.SSRStreamChunkShell // SSRStreamChunkBoundary identifies an async boundary replacement chunk. SSRStreamChunkBoundary = runtime.SSRStreamChunkBoundary )
const CurrentSSRBootstrapVersion = 1
const CurrentSSRStateUpdateVersion = 1
const DefaultBootstrapReferenceScriptID = "__GWC_BOOTSTRAP_REF__"
const DefaultBootstrapScriptID = "__GWC_BOOTSTRAP__"
const DefaultCSRFFormFieldName = "csrf_token"
const DefaultCSRFHeaderName = "X-CSRF-Token"
const (
DefaultRouteBootstrapPayloadKey = "route:data"
)
Variables ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 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 ¶
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 ¶
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 ¶
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 ¶
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
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 ¶
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 ¶
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 ¶
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 ¶
UseCallback returns fn unchanged on non-browser targets.
func UseContext ¶
UseContext is a core package helper.
func UseDefer ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
UseTimerTrigger returns true once delay has elapsed since mount — the timer trigger for a deferred view (Angular `@defer (on timer(...))`).
func UseWindowEvent ¶
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 ¶
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 ¶
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:
- 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.
- X-Correlation-ID, X-Request-ID, X-Trace-ID — used as-is; a synthetic W3CTraceContext is generated using the value as the trace ID.
- 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) AssertiveID ¶
AssertiveID is a core package helper.
type AsyncBoundaryProps ¶
type CSRFToken ¶
func NewCSRFToken ¶
NewCSRFToken creates a CSRFToken with the given value and default header and form field names.
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 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 {
}
type Context ¶
type Context[T any] struct { Provider *ContextProvider[T] // contains filtered or unexported fields }
func CreateContext ¶
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 ¶
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) Node ¶
Node returns the live DOM node, or nil before mount / after unmount / on native.
func (DOMRef) ScrollIntoView ¶
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 ¶
UseDebounced returns the current value unchanged on non-browser targets.
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 ErrorBoundaryProps ¶
type Event ¶
type Event struct{}
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 FieldStatus ¶
type File ¶
type File struct{}
File is the native no-op counterpart of the browser File wrapper.
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 Form ¶
type Form[T any] struct { // contains filtered or unexported fields }
Form exposes local form state, validation helpers, and submission lifecycle state.
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]) Errors ¶
func (parseF Form[T]) Errors() FieldErrors
Errors returns a copy of the current field error map.
func (Form[T]) FieldMessage ¶
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]) HasErrors ¶
HasErrors reports whether the form currently has field or form-level errors.
func (Form[T]) HasField ¶
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 ¶
HasFieldError reports whether a field currently has an error message.
func (Form[T]) IntentPending ¶
IntentPending reports whether the given intent is the currently pending submit action.
func (Form[T]) MustSetField ¶
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]) SetErrors ¶
func (parseF Form[T]) SetErrors(parseErrors FieldErrors)
SetErrors replaces the current field error map.
func (Form[T]) SetFormError ¶
SetFormError sets the form-level error message.
func (Form[T]) SetSubmitIntent ¶
SetSubmitIntent records the current submit intent for intent-aware validation or submission flows.
func (Form[T]) Submit ¶
Submit runs the submit function in a goroutine and updates submission lifecycle state.
func (Form[T]) SubmitError ¶
SubmitError returns the last submission error.
func (Form[T]) SubmitIntent ¶
SubmitIntent returns the most recently selected submit intent.
func (Form[T]) SubmitWithIntent ¶
SubmitWithIntent runs the submit function with an explicit intent and tracks that intent while submission is pending.
func (Form[T]) Submitting ¶
Submitting reports whether a submission is in flight.
func (Form[T]) TouchedAny ¶
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 ¶
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]) Validating ¶
Validating reports whether async validation is in flight.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler stores an event handler value in a form the runtime can consume.
func WrapHandler ¶
WrapHandler wraps an already-prepared handler value.
type HotReloadBoundaryProps ¶
type HydrationIslandBudget ¶
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 ¶
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 ¶
UseLazyNode executes the loader synchronously on the server and returns the result as a LazyNode.
type MatchBuilder ¶
type MatchBuilder struct {
// contains filtered or unexported fields
}
MatchBuilder lazily resolves the first matching branch and a default.
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 ¶
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 CreateElement ¶
CreateElement creates a UI node from a component function, provider, boundary, or existing node.
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 ¶
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())) },
})
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 ¶
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 ¶
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 ¶
UsePrevious reports no previous value on non-browser targets.
type ReactiveSource ¶
type ReactiveSource interface {
ReactiveRegionSourceIDs() []string
}
ReactiveSource identifies shared values that a ReactiveRegion can subscribe to explicitly.
type Reducer ¶
Reducer provides access to reducer-style local state transitions.
func UseReducer ¶
UseReducer returns a lightweight reducer-backed handle on non-browser targets.
type Ref ¶
type Ref[T any] struct { // contains filtered or unexported fields }
Ref stores a stable mutable reference across renders.
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 ¶
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 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 ¶
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 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 ServerActionRefresh ¶
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 ¶
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{}{})
}
Output:
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 ¶
UseThrottled returns the current value unchanged on non-browser targets.
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.
Source Files
¶
- accessibility_native.go
- autofocus.go
- branching.go
- children_shared.go
- component_handle_shared.go
- context_shared.go
- correlation_native.go
- css_escape.go
- defer.go
- defer_blocks.go
- defer_triggers.go
- doc.go
- dom_ref.go
- element_hooks.go
- element_hooks_native.go
- error_boundary_shared.go
- file_native.go
- files.go
- files_native.go
- force_update.go
- form_native.go
- form_validate.go
- global_events.go
- global_events_native.go
- hooks_lifecycle.go
- hot_reload_boundary.go
- hot_reload_boundary_shared.go
- hydration.go
- hydration_island.go
- hydration_island_native.go
- inspect.go
- network_status.go
- network_status_native.go
- optimistic_hook.go
- overlay.go
- overlay_native.go
- panic_logging.go
- panic_logging_native.go
- parallel_region.go
- parallel_region_event_bridge_native.go
- parallel_region_event_bridge_shared.go
- parallel_region_runtime_bridge_shared.go
- parallel_region_runtime_native.go
- parallel_region_worker_bridge.go
- persisted_state.go
- plugininterposer_runtime2.go
- preference_hooks.go
- query_hook.go
- ready.go
- revalidate_focus_hook.go
- safego.go
- ssr_bootstrap.go
- ssr_observability.go
- ssr_stream.go
- ssr_transfer.go
- stack_frame_mapper.go
- suspense_shared.go
- theme_hook.go
- theme_hook_native.go
- timers.go
- timers_native.go
- typed.go
- ui_native.go
- use_spring.go
- view_transition_native.go
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). |