doors

package module
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: Apache-2.0 Imports: 33 Imported by: 0

README

Doors

codecov Go Reference Mentioned in Awesome Go

https://doors.dev

Doors is a server-driven UI framework + runtime for building stateful, reactive web applications in Go.

Your Go server is a UI runtime: the web application runs on a stateful server, while the browser acts as a remote renderer and input layer. No endpoints to design, no JSON contracts, no client bundle — go build produces the web application as one binary.

Example

Templates are GoX — a typed Go superset with its own parser, LSP, and editor plugins.

Live search:

type Search struct {
    db    *DB                  // your data layer
    query doors.Source[string] // reactive state
}

elem (s *Search) Main() {
    <input
        (doors.AInput{
            Scope: &doors.ScopeDebounce{Duration: 300 * time.Millisecond}, // debounce requests
            On: func(ctx context.Context, r doors.RequestInput) bool {
                s.query.Update(ctx, r.Event().Value) // update state
                return false
            },
        })
        type="search"
        placeholder="search">

    ~(s.query.Bind(s.results)) ~// re-renders on query changes
}

elem (s *Search) results(query string) {
    ~~
    users := s.db.SearchUsers(ctx, query) // hit the DB mid-render
    ~~
    <ul>
        ~(for _, u := range users {
            <li>~(u.Name)</li>
        })
    </ul>
}

This is the whole feature — no endpoint, no JSON contract, no fetch call, no client-side state, no JS build step. Debounce is one attribute, and the permission check happens where you render.

How it works

  • A page is a live instance. Each open tab holds its render tree, reactive state, and handlers as Go values on the server. A production page with 500+ interactive elements costs ~300 KB of server memory per open tab.
  • No virtual DOM. Re-rendering is explicit and targeted: state derivation replaces diffing, and only fragments bound to changed values re-render.
  • Rendering is authorization. Every user can interact only with what you rendered to them. You check permissions when you render the button, and that is enough to guarantee the related action won't be triggered by anyone else.
  • Go concurrency is the web architecture. Handlers can block on channels, start goroutines scoped to rendered content, and receive cancellation through ctx.Done() when their subtree leaves the page. External systems integrate directly into the stateful session process — no wrapping stateful work into stateless logic.
  • The UI is awaitable. Every mutating operation — source updates, door updates, calls into the browser, server-emitted DOM events — returns a plain <-chan error.
  • Typed routing. URLs are Go structs, decoded from and encoded back to the address bar. Renaming a route field is a build error, not a 404.
  • Plain-HTTP sync. A rolling-request and streaming protocol over regular HTTP — no WebSockets, no SSE, HTTP/3-ready.
  • Integrated web stack. Bundle assets, build scripts, serve private files, automate CSP — the whole stack ships in the binary.
  • Stateful deployments, answered. The doors-caddy plugin provides seamless rollouts and sticky balancing for production clusters.

Comparisons

Doors vs HTMX, Datastar (+ templ)

HTMX and Datastar enhance HTML by coordinating behavior through attributes and endpoints; templ adds typed HTML rendering in Go on top. Interaction still flows through endpoints you design, wire up, and authorize. Doors is a UI runtime: you write the interaction flow directly in Go, handlers attach to elements, state lives on the live page instance, and the endpoint layer disappears.

Doors vs Phoenix LiveView, Blazor Server

The same family: the server owns UI state. Doors does it in pure Go — no BEAM or .NET runtime, typed URL structs instead of string routes, plain-HTTP sync instead of WebSockets, one static binary. And the main thing: Doors UI is non-blocking. LiveView and Blazor serialize interactions through one process per client; Doors handles events concurrently, so interactivity behaves like a JavaScript SPA.

Doors vs Livewire, Hotwire

Livewire and Hotwire are stateless: every interaction is a plain HTTP request you must authorize. Doors runs the UI as a stateful process — multi-stage flows and server-triggered updates are natural, and there is no public action surface to authorize: each handler exists only for the user it was rendered to.

Doors vs React, Next.js, and similar stacks

Typical JavaScript stacks place the interaction model in the browser and use the server as a data service — every feature needs an API surface, client state, and synchronization between the two. Doors keeps the flow on the server in Go, with the browser focused on display and input — as if your API had exactly one consumer: the framework.

Start a new project

For new applications, use doors-dev/doors-starter, the recommended ready-to-run Doors project skeleton.

The Get Started guide walks through a minimal hello-world app by hand, useful for understanding the basic pieces.

For AI-assisted development, install the Doors Skill for Claude Code, Codex, or OpenCode.

Where Doors fits best

  • SaaS products
  • Business systems
  • Customer portals
  • Admin panels
  • Internal tools
  • Real-time apps with meaningful server-side workflows

Where it is not the right fit

  • Static or mostly non-interactive sites
  • Client-first apps with minimal server behavior and simple routing
  • Offline-first PWAs where the browser must be the primary runtime

The trade: server memory per open page (~300 KB for a heavy production page) and interaction latency bounded by the network round trip.

Status

Doors is used in production. Breaking changes are still happening, but they make life easier and are straightforward to migrate — each is documented in RELEASE_NOTES.md.

Learn more

License

Doors is licensed under the Apache License 2.0.

Documentation

Overview

Package doors builds server-rendered web apps with typed routing, reactive values, and server-handled browser interactions.

Most apps start with NewApp, route the current Location with Route, and render dynamic fragments with Door, Source, and Beam. Event attrs such as AClick, ASubmit, and ALink connect DOM events, forms, and navigation to Go handlers while still producing regular HTML.

Index

Examples

Constants

View Source
const (
	// CacheControlImmutable caches for a year and never revalidates. Use for
	// hash-named URLs.
	CacheControlImmutable = "public, max-age=31536000, immutable"

	// CacheControlStatic caches for an hour, then revalidates.
	CacheControlStatic = "public, max-age=3600, must-revalidate"

	// CacheControlStaticShort caches for five minutes, then revalidates.
	CacheControlStaticShort = "public, max-age=300, must-revalidate"

	// CacheControlHTML lets shared caches store the response but always
	// revalidates it.
	CacheControlHTML = "public, max-age=0, must-revalidate"

	// CacheControlCDN caches for an hour in browsers, a day in shared caches.
	CacheControlCDN = "public, max-age=3600, s-maxage=86400"

	// CacheControlPrivate keeps the response out of shared caches and always
	// revalidates it.
	CacheControlPrivate = "private, max-age=0, must-revalidate"

	// CacheControlNoCache stores the response but always revalidates it.
	CacheControlNoCache = "no-cache"

	// CacheControlNoStore forbids storing the response anywhere.
	CacheControlNoStore = "no-store"

	// CacheControlAPI is CacheControlNoCache restricted to private caches.
	CacheControlAPI = "private, no-cache"
)

Cache-Control presets for UseFS, UseDir, and UseFile.

View Source
const (
	// RaceSerial runs calls one at a time, in order of arrival.
	RaceSerial = core.RaceSerial
	// RaceParallel lets calls run concurrently.
	RaceParallel = core.RaceParallel
	// RaceStrict runs calls one at a time and cancels out-of-order calls.
	RaceStrict = core.RaceStrict
)

Race modes for event attrs and hooks.

Variables

View Source
var DocsFS embed.FS

DocsFS is the embedded documentation tree. Guide paths are rooted at docs, such as docs/01-get-started.md.

View Source
var ErrExecution = common.ErrExecution

ErrExecution reports an action that reached the browser and failed there. Delivered on completion channels of Call and door operations, matched with errors.Is.

View Source
var ErrPathEncode = common.ErrPathEncode

ErrPathEncode reports a model that failed to encode into a location: no variant selected or an empty required capture. Returned by NewLocation and location actions, matched with errors.Is.

View Source
var ErrPathModel = common.ErrPathModel

ErrPathModel reports an invalid path model definition: bad tags, wrong field types, or unexported fields. Returned by NewLocation and matched with errors.Is.

View Source
var ErrTerminated = common.ErrTerminated

ErrTerminated reports an instance that ended before the operation could complete. Delivered on completion channels, matched with errors.Is.

Functions

func Call

func Call(ctx context.Context, a Action) <-chan error

Call dispatches action to the client.

The returned channel is optional to use. It sends nil once the call is scheduled, or an error if the action cannot be built. On a detached context (DetachedContext, Go) a second value reports the result: nil, or an error if the client fails or the result cannot be decoded; otherwise the channel closes once the call is scheduled. If you need the result, wait for the second value; it only arrives on a detached context. If the call is canceled, the channel sends context.Canceled and closes. Canceling ctx requests best-effort cancellation. Never wait on the channel during rendering or in a subscription.

To capture the client result, arm the action with its Into method before dispatch; see ActionInto. dst is written only on a detached context, before the second value.

ctx must belong to a Doors render or handler; otherwise Call panics.

func Ctx added in v0.15.0

func Ctx(ctx context.Context) gox.Proxy

Ctx renders the following element with the values of ctx.

Only value lookups are served from ctx; cancellation and Doors ownership stay with the enclosing render.

func DeferredInner added in v0.17.0

func DeferredInner(ctx context.Context, content any) <-chan error

DeferredInner replaces the children of the closest dynamic parent with content, but waits until the current content is rendered and scheduled for delivery. Use it to show a placeholder first and replace it with content that is slow to render.

It is the same as [Door.DeferredInner] on that parent, but bound to the content ctx belongs to: if a newer operation has already replaced that content, it does nothing and reports context.Canceled.

ctx must belong to a Doors render or handler; otherwise DeferredInner panics. If ctx belongs to the root page render, it sends an error and closes.

func DeferredOuter added in v0.17.0

func DeferredOuter(ctx context.Context, content any) <-chan error

DeferredOuter replaces the container and children of the closest dynamic parent with content, but waits until the current content is rendered and scheduled for delivery. Use it to show a placeholder first and replace it with content that is slow to render.

It is the same as [Door.DeferredOuter] on that parent, but bound to the content ctx belongs to: if a newer operation has already replaced that content, it does nothing and reports context.Canceled.

ctx must belong to a Doors render or handler; otherwise DeferredOuter panics. If ctx belongs to the root page render, it sends an error and closes.

func DeferredStatic added in v0.17.0

func DeferredStatic(ctx context.Context, content any) <-chan error

DeferredStatic removes the container of the closest dynamic parent and renders content in its place, but waits until the current content is rendered and scheduled for delivery. Use it to show a placeholder first and replace it with content that is slow to render.

It is the same as [Door.DeferredStatic] on that parent, but bound to the content ctx belongs to: if a newer operation has already replaced that content, it does nothing and reports context.Canceled.

ctx must belong to a Doors render or handler; otherwise DeferredStatic panics. If ctx belongs to the root page render, it sends an error and closes.

func DetachedContext added in v0.12.15

func DetachedContext(ctx context.Context) context.Context

DetachedContext returns a context that is detached from the current render/update cycle and bounded by the lifetime of ctx.

It keeps the values of ctx and the current Doors ownership. Completion channels of operations made with it report the result as a second value.

Operations made with it are not part of the current handler's work: not its batch, its indicator, or OnSettle. Wait on their channels only in goroutines of your own, never during rendering, in a handler, or in a subscription: that can block the page.

Unlike InstanceContext, work started with it is cleaned up with the current dynamic owner.

func Go

func Go(f func(ctx context.Context)) gox.Elem

Go runs f in a goroutine, meant for background work that updates the page through Door methods. f starts only after the render cycle producing the surrounding content completes and is enqueued for delivery, so updates made by f always land after the markup that hosts them. It is best-effort: if the render cycle fails or is superseded, f never runs. In content rendered by [Door.Static], [Door.DeferredStatic] or DeferredStatic, f belongs to the parent Door, so a failed render does not drop it.

The context passed to f is equivalent to DetachedContext of the render context: it is canceled when the surrounding content is released (replaced or unmounted) and keeps the current dynamic ownership. Waiting on completion channels inside f is safe.

Example:

~(doors.Go(func(ctx context.Context) {
    <-time.After(time.Second)
    d.Inner(ctx, currentTime())
}))

func HasInstance added in v0.15.0

func HasInstance(ctx context.Context) bool

HasInstance reports whether ctx belongs to a Doors render or handler, meaning instance- and door-scoped helpers accept it. Implies HasSession.

func HasSession added in v0.15.0

func HasSession(ctx context.Context) bool

HasSession reports whether ctx carries a Doors session, meaning session-scoped helpers like SessionID and SessionStore accept it.

func HistoryReplaceContext added in v0.14.2

func HistoryReplaceContext(ctx context.Context) context.Context

HistoryReplaceContext marks ctx so that a URL update made with it replaces the current browser history entry instead of pushing a new one.

Source.Update and Source.Mutate honor the mark on the Router source and on any source derived from it, such as a RouteModel source. Passing it to an update of a source not backed by the URL has no effect.

func HoldSettle added in v0.15.0

func HoldSettle(ctx context.Context) (release func())

HoldSettle keeps the handler's work open after the handler returns, until release is called. While held, it does not settle: OnSettle callbacks wait, and in a hook the client keeps the indicator, the scope, and the $hook promise pending; in a handler with Batch set, the updates stay unapplied until release. Use it to hand the work over to a goroutine.

Call it synchronously in the handler; release is idempotent and may run settle callbacks inline. Operations started with the handler ctx join the work, operations started with DetachedContext do not. Always call release, typically deferred in the goroutine; held work settles otherwise only when the instance ends.

Outside a handler or the ops of OnSettle and OnBatch, for example in an OnSettle callback, release is a no-op.

func IDBytes

func IDBytes(b []byte) string

IDBytes returns a URL-safe identifier derived from b. Equal inputs always produce the same identifier.

WARNING: it is not a cryptographic hash; do not use it to hide the input.

func IDNumber added in v0.15.0

func IDNumber(ctx context.Context) uint64

IDNumber returns a number unique within the current instance. Every call returns a new one, and the values are not sequential.

ctx must belong to a Doors render or handler; otherwise IDNumber panics.

func IDRand

func IDRand() string

IDRand returns a cryptographically random, URL-safe identifier.

Unlike IDString and IDBytes, every call returns a new value.

func IDString

func IDString(string string) string

IDString returns a URL-safe identifier derived from the given string. Equal inputs always produce the same identifier.

WARNING: it is not a cryptographic hash; do not use it to hide the input.

func InstanceContext added in v0.12.15

func InstanceContext(ctx context.Context) context.Context

InstanceContext returns a context that is detached from the current dynamic owner and bounded by the current instance lifetime.

It keeps the values of ctx and moves Doors ownership to the root of the current instance, so subscriptions and hooks made with it survive rerenders of the caller. Completion channels of operations made with it report the result as a second value.

Operations made with it are not part of the current handler's work: not its batch, its indicator, or OnSettle. Wait on their channels only in goroutines of your own, never during rendering, in a handler, or in a subscription: that can block the page.

Unlike DetachedContext, it outlives the current dynamic owner.

func InstanceEnd

func InstanceEnd(ctx context.Context)

InstanceEnd ends the current instance immediately.

Unlike SessionEnd, the session and its other instances stay live.

ctx must belong to a Doors render or handler; otherwise InstanceEnd panics.

func InstanceID added in v0.15.0

func InstanceID(ctx context.Context) string

InstanceID returns the ID of the current instance.

ctx must belong to a Doors render or handler; otherwise InstanceID panics.

func InstanceLastSeen added in v0.14.2

func InstanceLastSeen(ctx context.Context) time.Time

InstanceLastSeen returns the time the current instance last saw its client on the live connection.

Event and hook requests do not advance it, and it is the zero time during the initial page render.

ctx must belong to a Doors render or handler; otherwise InstanceLastSeen panics.

func IsDocument added in v0.17.0

func IsDocument(ctx context.Context) bool

IsDocument reports whether ctx renders the page response: the initial page render and every Door placed during it. Use it to send slow content complete with the page and defer it on later renders.

func Join added in v0.12.1

func Join[T Joiner[T]](values ...T) T

Join combines values that support Joiner.And into one value, in argument order.

It returns the zero value when called without arguments.

func Logger added in v0.15.0

func Logger(ctx context.Context) *slog.Logger

Logger returns the Doors logger for ctx.

Any context is allowed; one that carries no Doors session falls back to slog.Default.

func NewHook added in v0.12.35

func NewHook(ctx context.Context, r Resource) (string, bool)

NewHook registers r on the closest dynamic parent and returns the URL path that serves it. The path stops working once the current content is cleared.

Appending a slash and a file name to the returned path is safe. The handler sees the part after the returned path as r.URL.Path, starting with /, so a router such as http.ServeMux can serve sub-paths of the hook. The Doors-Hook-Prefix request header holds the returned path, for building redirects. Requests are handled concurrently.

It returns false if the closest dynamic parent has already been cleared.

ctx must belong to a Doors render or handler; otherwise NewHook panics.

WARNING: the request body is not limited by the ServerRequestBodyLimit of Conf.

func NewResource added in v0.18.0

func NewResource(ctx context.Context, r ResourceStatic, contentType string) (string, error)

NewResource keeps r in RAM and returns the cached URL path that serves it, the same one the cache attribute produces. The path does not depend on the current content and is served with the ServerCacheControl of Conf.

contentType is sent as the Content-Type; empty lets the server detect it, which gives text/plain for JavaScript and CSS. A file name can be appended after a dot: path + ".app.js".

It returns an error if r cannot be read.

ctx must belong to a Doors render or handler; otherwise NewResource panics.

func OnBatch added in v0.18.0

func OnBatch(ctx context.Context, on func(ctx context.Context), ops ...func(ctx context.Context))

OnBatch batches updates yourself, anywhere: the updates made in ops are applied at once, and on runs when the browser has applied them. In a handler with Batch set, or in ops of another OnBatch, OnBatch joins that batch; otherwise it opens one.

In a handler the batch closes when the handler settles, not when ops return; use DetachedContext of ctx to batch on its own. In an OnSettle callback of a handler, the handler's completion waits for the batch.

Where OnSettle reports that the updates are queued for delivery, OnBatch reports that the browser applied them.

on runs exactly once, also if the instance ends first; the provided context reports such states. It runs with a context equivalent to DetachedContext of ctx and must not block.

on may be nil.

ctx must belong to a Doors render or handler; otherwise OnBatch panics.

func OnClean added in v0.15.0

func OnClean(ctx context.Context, f func())

OnClean registers f to run when the current content is cleared: the enclosing Door is updated, removed, rerendered by an ancestor, fails to render, or the instance ends. Exactly one of these eventually happens to every rendered piece of content, so f runs exactly once per registration. Content rendered by [Door.Static], [Door.DeferredStatic] or DeferredStatic belongs to the parent Door, so f runs when the parent's content is cleared, even if that render fails.

f runs inline on the framework goroutine performing the clean — on the calling goroutine when the content is already cleaned — and receives no context; the registering context is already canceled by then. It must not block; fire-and-forget Doors calls with a context captured beforehand, for example from InstanceContext, are safe.

ctx must belong to a Doors render or handler; otherwise OnClean panics.

func OnReady added in v0.15.0

func OnReady(ctx context.Context, on func(ctx context.Context))

OnReady registers on to run when the render cycle producing the current content completes and the resulting page or update is enqueued for delivery to the client. If that content is already on the page, for example in an event handler, on fires promptly.

OnReady is best-effort and fires at most once: if the render cycle fails or is superseded by a newer operation, on never runs. Content rendered by [Door.Static], [Door.DeferredStatic] or DeferredStatic is the exception: it belongs to the parent Door, so on still runs if that render fails. Tie cleanup to OnClean.

on runs inline on the framework goroutine completing the cycle — on the calling goroutine when the content is already on the page — with a context equivalent to DetachedContext of ctx. It must not block; if you need to wait, start a goroutine with the provided ctx.

ctx must belong to a Doors render or handler; otherwise OnReady panics.

func OnSettle added in v0.15.0

func OnSettle(ctx context.Context, on func(ctx context.Context), ops ...func(ctx context.Context))

OnSettle runs ops as part of the work ctx belongs to and registers on to run once that work settles: every Doors operation started from it is processed and its updates are enqueued for delivery to the client. The content of a deferred operation is not awaited. In a handler or in the ops of OnSettle and OnBatch, OnSettle joins that work; otherwise it starts new work spanning the ops calls. on never runs before the content that produced ctx is ready itself.

Where OnReady tracks one render cycle, OnSettle tracks everything the work started, including the Door updates and beam propagation it triggered. Settling is server-side: the updates are queued, not yet written to the connection or acknowledged by the browser.

on runs exactly once, even if the owner is canceled, the producing render fails, or the instance is shutting down; the provided context reports such states. It runs inline on the goroutine that settles the work — on the calling goroutine when everything already settled — with a context equivalent to DetachedContext of ctx, except that calls issued while on runs keep their place with the handler's updates and their completion channels close once the calls are scheduled. It must not block.

Using a handler ctx after the handler returned is misuse; use DetachedContext or HoldSettle.

on may be nil.

ctx must belong to a Doors render or handler; otherwise OnSettle panics.

func Once added in v0.16.0

func Once(v any) gox.Elem

Once renders v on the first render only and drops its reference to v. Later renders produce nothing.

A Door stores its content until replaced. Wrapped in Once, that content can be garbage collected after it is rendered; a Door rendered again is then empty.

Hooks keep what their handlers capture: a component whose methods serve as handlers stays in memory until its hooks are removed.

Example:

door.Outer(ctx, doors.Once(&UserList{users: users}))

func Parallel added in v0.9.3

func Parallel() gox.Proxy

Parallel renders the following element on the instance goroutine pool.

Use it for fragments that wait on a database query or an external API call.

func ProxyMod added in v0.9.7

func ProxyMod(mod gox.Modify) gox.Proxy

ProxyMod returns a proxy that applies mod to the first element in the wrapped subtree.

It looks through components, containers, and Parallel markers to reach that element and leaves later siblings unchanged. It does not work in front of a Door: a Door, text, or other non-element output where that element is expected is an error. A nil mod renders the subtree unchanged.

func Reload added in v0.9.0

func Reload(ctx context.Context) <-chan error

Reload rerenders the closest dynamic parent.

The returned channel is optional to use. It sends nil once the rerender is scheduled, or an error if it fails before that, for example when ctx belongs to the root page render. On a detached context (DetachedContext, Go) a second value reports the result: nil once applied to the page, or an error; otherwise the channel closes once the rerender is scheduled. If you need the result, wait for the second value; it only arrives on a detached context. Never wait on the channel during rendering or in a subscription.

ctx must belong to a Doors render or handler; otherwise Reload panics.

func Route

func Route(routes ...SourceRoute[Location]) gox.Elem

Route renders the first route that matches the current URL and switches branches as the URL changes. Routes are tried in order: use RouteModel to match path models and a leaf such as RouteComp last as the fallback.

func SessionContext added in v0.12.12

func SessionContext(ctx context.Context) context.Context

SessionContext returns a context that is canceled when the current session ends.

It carries the session and nothing else: values of ctx are dropped, and it is tied to no instance or dynamic owner. Session-scoped helpers, Door methods, and Source or Beam reads, subscriptions, and updates accept it; a subscription made with it lives until the session ends. Reload, DeferredInner, DeferredOuter, DeferredStatic, and instance-scoped helpers panic on it.

ctx must carry a Doors session; otherwise SessionContext panics.

func SessionEnd

func SessionEnd(ctx context.Context)

SessionEnd ends the current session and every instance in it immediately.

Use it for a hard logout that must close every open page.

ctx must carry a Doors session; otherwise SessionEnd panics.

func SessionExpire

func SessionExpire(ctx context.Context, d time.Duration)

SessionExpire caps the remaining lifetime of the current session at d.

It is a cap, not a keep-alive: the session still ends earlier if SessionTTL runs out first. Passing zero removes the cap.

ctx must carry a Doors session; otherwise SessionExpire panics.

func SessionID added in v0.15.0

func SessionID(ctx context.Context) string

SessionID returns the ID of the current session.

Every instance in the same browser shares it, and it is the value of the session cookie.

ctx must carry a Doors session; otherwise SessionID panics.

func SessionLastSeen added in v0.14.2

func SessionLastSeen(ctx context.Context) time.Time

SessionLastSeen returns the time of the most recent renewal of the current session.

Renewals are throttled, so the value can lag behind the last request.

ctx must carry a Doors session; otherwise SessionLastSeen panics.

func Status

func Status(statusCode int) gox.Elem

Status sets the HTTP status code of the initial page response, replacing the default 200. Calling it after that response is sent has no effect.

Example:

~(doors.Status(http.StatusNotFound))

Types

type ABlur

type ABlur struct {
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestFocus) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

ABlur handles the browser blur event on the element it is attached to. Fields and handler contract follow AFocus.

func (ABlur) Modify

func (b ABlur) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (ABlur) Proxy

func (b ABlur) Proxy(cur gox.Cursor, elem gox.Elem) error

type AChange

type AChange struct {
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestChange) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

AChange handles the browser change event on the element it is attached to, which fires on a committed value: on blur for text inputs, immediately for checkboxes and selects.

Attach it as an attribute to one or more elements. Each event sends one request carrying the target's current value, subject to Scope. Return false from On to keep the handler active, true to remove it. A nil On still installs the hook and still sends the request, so omit the attr rather than nil-ing On.

func (AChange) Modify

func (p AChange) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (AChange) Proxy

func (p AChange) Proxy(cur gox.Cursor, elem gox.Elem) error

type AClick

type AClick struct {
	// StopPropagation stops the event from bubbling up the DOM. Optional.
	StopPropagation bool
	// PreventDefault suppresses the browser's default action. Optional.
	PreventDefault bool
	// ExactTarget limits the handler to events whose target is the element
	// itself. Optional.
	ExactTarget bool
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestPointer) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

AClick handles the browser click event on the element it is attached to.

Attach it as an attribute to one or more elements. Each event sends one request, subject to Scope. Return false from On to keep the handler active, true to remove it. A nil On still installs the hook and still sends the request, so omit the attr rather than nil-ing On.

func (AClick) Modify

func (p AClick) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (AClick) Proxy

func (p AClick) Proxy(cur gox.Cursor, elem gox.Elem) error

type AData

type AData struct {
	// Name is the entry name used from JavaScript as $data(name). Required.
	Name string
	// Value is the exposed value: a string is sent as text, []byte as binary,
	// anything else as JSON. Required.
	Value any
}

AData exposes a value to browser code as $data(name).

Attach it to the script element that reads the value. A []byte value arrives as a promise resolving to an ArrayBuffer; other values arrive directly.

func (AData) Modify

func (a AData) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (AData) Proxy

func (a AData) Proxy(cur gox.Cursor, elem gox.Elem) error

type AFocus

type AFocus struct {
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestFocus) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

AFocus handles the browser focus event on the element it is attached to.

Attach it as an attribute to one or more elements. Each event sends one request, subject to Scope. Return false from On to keep the handler active, true to remove it. A nil On still installs the hook and still sends the request, so omit the attr rather than nil-ing On.

Unlike AFocusIn, the focus event does not bubble, so there are no propagation fields.

func (AFocus) Modify

func (f AFocus) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (AFocus) Proxy

func (f AFocus) Proxy(cur gox.Cursor, elem gox.Elem) error

type AFocusIn

type AFocusIn struct {
	// StopPropagation stops the event from bubbling up the DOM. Optional.
	StopPropagation bool
	// ExactTarget limits the handler to events whose target is the element
	// itself. Optional.
	ExactTarget bool
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestFocus) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

AFocusIn handles the browser focusin event on the element it is attached to. Unlike focus, focusin bubbles; handler contract follows AFocus.

func (AFocusIn) Modify

func (f AFocusIn) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (AFocusIn) Proxy

func (f AFocusIn) Proxy(cur gox.Cursor, elem gox.Elem) error

type AFocusOut

type AFocusOut struct {
	// StopPropagation stops the event from bubbling up the DOM. Optional.
	StopPropagation bool
	// ExactTarget limits the handler to events whose target is the element
	// itself. Optional.
	ExactTarget bool
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestFocus) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

AFocusOut handles the browser focusout event on the element it is attached to. Unlike blur, focusout bubbles; handler contract follows AFocus.

func (AFocusOut) Modify

func (f AFocusOut) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (AFocusOut) Proxy

func (f AFocusOut) Proxy(cur gox.Cursor, elem gox.Elem) error

type AGotPointerCapture

type AGotPointerCapture struct {
	// StopPropagation stops the event from bubbling up the DOM. Optional.
	StopPropagation bool
	// PreventDefault suppresses the browser's default action. Optional.
	PreventDefault bool
	// ExactTarget limits the handler to events whose target is the element
	// itself. Optional.
	ExactTarget bool
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestPointer) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

AGotPointerCapture handles the browser gotpointercapture event on the element it is attached to. Fields and handler contract follow AClick.

func (AGotPointerCapture) Modify

func (p AGotPointerCapture) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (AGotPointerCapture) Proxy

func (p AGotPointerCapture) Proxy(cur gox.Cursor, elem gox.Elem) error

type AHook

type AHook[T any] struct {
	// Name is the hook name used from JavaScript as $hook(name, ...). Required.
	Name string
	// Scope controls how calls to this hook are scheduled on the client.
	// Optional; without it every call is sent immediately.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while a call is in flight.
	// A hook call has no event element, so only the Query and QueryAll variants
	// apply. Optional.
	Indicator Indicators
	// RequestTimeout overrides [Conf].RequestTimeout for calls to this hook.
	// Optional.
	RequestTimeout time.Duration
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// On handles the call and returns the value sent back to the caller. Return
	// false to keep the hook active, true to remove it. Optional; a nil On
	// answers with null.
	On func(ctx context.Context, r RequestHook[T]) (any, bool)
}

AHook exposes a Go handler to browser code as $hook(name, ...).

Attach it to the script element that calls $hook or $fetch. Input is decoded from JSON into T, and the value On returns is encoded back to JSON as the call result.

Prefer ARawHook when the handler needs the raw body, multipart parsing, or control over the response.

func (AHook[T]) Modify

func (h AHook[T]) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (AHook[T]) Proxy

func (h AHook[T]) Proxy(cur gox.Cursor, elem gox.Elem) error

type AInput

type AInput struct {
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestInput) bool
	// ExcludeValue omits the input value from the payload, leaving Name,
	// Value, Number, Date, Selected, and Checked unset. Optional.
	ExcludeValue bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

AInput handles the browser input event on the element it is attached to. Unlike AChange, it fires on every edit rather than on the committed value. The handler contract follows AChange.

func (AInput) Modify

func (p AInput) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (AInput) Proxy

func (p AInput) Proxy(cur gox.Cursor, elem gox.Elem) error

type AKeyDown

type AKeyDown struct {
	// StopPropagation stops the event from bubbling up the DOM. Optional.
	StopPropagation bool
	// PreventDefault suppresses the browser's default action. Optional.
	PreventDefault bool
	// ExactTarget limits the handler to events whose target is the element
	// itself. Optional.
	ExactTarget bool
	// Key limits the handler to events matching at least one key.
	// PreventDefault and StopPropagation apply only to matching
	// events. Optional; without keys every keydown fires.
	Key Keys
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestKeyboard) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
}

AKeyDown handles the browser keydown event on the element it is attached to.

Attach it as an attribute to one or more elements. Each matching event sends one request, subject to Scope. Return false from On to keep the handler active, true to remove it. A nil On still installs the hook and still sends the request, so omit the attr rather than nil-ing On.

func (AKeyDown) Modify

func (k AKeyDown) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (AKeyDown) Proxy

func (k AKeyDown) Proxy(cur gox.Cursor, elem gox.Elem) error

type AKeyUp

type AKeyUp struct {
	// StopPropagation stops the event from bubbling up the DOM. Optional.
	StopPropagation bool
	// PreventDefault suppresses the browser's default action. Optional.
	PreventDefault bool
	// ExactTarget limits the handler to events whose target is the element
	// itself. Optional.
	ExactTarget bool
	// Key limits the handler to events matching at least one key.
	// PreventDefault and StopPropagation apply only to matching
	// events. Optional; without keys every keyup fires.
	Key Keys
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestKeyboard) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
}

AKeyUp handles the browser keyup event on the element it is attached to. Fields and handler contract follow AKeyDown.

func (AKeyUp) Modify

func (k AKeyUp) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (AKeyUp) Proxy

func (k AKeyUp) Proxy(cur gox.Cursor, elem gox.Elem) error
type ALink struct {
	// Model is the target path model value, a [Location], or a
	// [LocationEncoder]. Required; a value that cannot be encoded logs an
	// error and leaves the element without href or navigation.
	Model any
	// Fragment is appended to href and scrolled into view once the
	// navigation succeeds. Optional.
	Fragment string
	// Active marks the link while it matches the current location. Optional;
	// it does nothing unless its Indicator is set.
	Active Active
	// StopPropagation stops the click from bubbling up the DOM. Optional.
	StopPropagation bool
	// HistoryReplace replaces the current history entry instead of pushing a
	// new one, so Back skips this navigation. Optional.
	HistoryReplace bool
	// Batch applies the page updates of this navigation together, once all
	// of them are ready, so the current view stays intact until the new one
	// can replace it at once. Default: false.
	Batch bool
	// Scope controls how the request is scheduled. Optional; all links share a
	// built-in scope, so a new click cancels a pending navigation.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// After lists client-side actions to run once the navigation
	// succeeds. Optional.
	After Actions
	// OnError lists client-side actions to run when the request fails.
	// Optional; a canceled navigation reverts the URL without running it.
	OnError Actions
}

ALink turns the element it is attached to into an in-app navigation link.

It sets href from Model and intercepts the click: the click updates the instance location and the page reroutes in place. The href stays a real URL, so it can be copied, opened in another tab, or loaded directly. A click that changes neither path nor query sends no request.

Unlike ActionLocationAssign, the page is not loaded again and the current instance stays alive.

Example:

~>doors.ALink{
	Model: Path{Section: SectionHome},
} <a>Home</a>

func (ALink) Modify

func (h ALink) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (ALink) Proxy

func (h ALink) Proxy(cur gox.Cursor, elem gox.Elem) error

type ALostPointerCapture

type ALostPointerCapture struct {
	// StopPropagation stops the event from bubbling up the DOM. Optional.
	StopPropagation bool
	// PreventDefault suppresses the browser's default action. Optional.
	PreventDefault bool
	// ExactTarget limits the handler to events whose target is the element
	// itself. Optional.
	ExactTarget bool
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestPointer) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

ALostPointerCapture handles the browser lostpointercapture event on the element it is attached to. Fields and handler contract follow AClick.

func (ALostPointerCapture) Modify

func (p ALostPointerCapture) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (ALostPointerCapture) Proxy

func (p ALostPointerCapture) Proxy(cur gox.Cursor, elem gox.Elem) error

type APointerCancel

type APointerCancel struct {
	// StopPropagation stops the event from bubbling up the DOM. Optional.
	StopPropagation bool
	// PreventDefault suppresses the browser's default action. Optional.
	PreventDefault bool
	// ExactTarget limits the handler to events whose target is the element
	// itself. Optional.
	ExactTarget bool
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestPointer) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

APointerCancel handles the browser pointercancel event on the element it is attached to. Fields and handler contract follow AClick.

func (APointerCancel) Modify

func (p APointerCancel) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (APointerCancel) Proxy

func (p APointerCancel) Proxy(cur gox.Cursor, elem gox.Elem) error

type APointerDown

type APointerDown struct {
	// StopPropagation stops the event from bubbling up the DOM. Optional.
	StopPropagation bool
	// PreventDefault suppresses the browser's default action. Optional.
	PreventDefault bool
	// ExactTarget limits the handler to events whose target is the element
	// itself. Optional.
	ExactTarget bool
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestPointer) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

APointerDown handles the browser pointerdown event on the element it is attached to. Fields and handler contract follow AClick.

func (APointerDown) Modify

func (p APointerDown) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (APointerDown) Proxy

func (p APointerDown) Proxy(cur gox.Cursor, elem gox.Elem) error

type APointerEnter

type APointerEnter struct {
	// StopPropagation stops the event from bubbling up the DOM. Optional.
	StopPropagation bool
	// PreventDefault suppresses the browser's default action. Optional.
	PreventDefault bool
	// ExactTarget limits the handler to events whose target is the element
	// itself. Optional.
	ExactTarget bool
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestPointer) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

APointerEnter handles the browser pointerenter event on the element it is attached to. Unlike APointerOver, pointerenter does not bubble. Fields and handler contract follow AClick.

func (APointerEnter) Modify

func (p APointerEnter) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (APointerEnter) Proxy

func (p APointerEnter) Proxy(cur gox.Cursor, elem gox.Elem) error

type APointerLeave

type APointerLeave struct {
	// StopPropagation stops the event from bubbling up the DOM. Optional.
	StopPropagation bool
	// PreventDefault suppresses the browser's default action. Optional.
	PreventDefault bool
	// ExactTarget limits the handler to events whose target is the element
	// itself. Optional.
	ExactTarget bool
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestPointer) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

APointerLeave handles the browser pointerleave event on the element it is attached to. Unlike APointerOut, pointerleave does not bubble. Fields and handler contract follow AClick.

func (APointerLeave) Modify

func (p APointerLeave) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (APointerLeave) Proxy

func (p APointerLeave) Proxy(cur gox.Cursor, elem gox.Elem) error

type APointerMove

type APointerMove struct {
	// StopPropagation stops the event from bubbling up the DOM. Optional.
	StopPropagation bool
	// PreventDefault suppresses the browser's default action. Optional.
	PreventDefault bool
	// ExactTarget limits the handler to events whose target is the element
	// itself. Optional.
	ExactTarget bool
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestPointer) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

APointerMove handles the browser pointermove event on the element it is attached to. Fields and handler contract follow AClick.

func (APointerMove) Modify

func (p APointerMove) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (APointerMove) Proxy

func (p APointerMove) Proxy(cur gox.Cursor, elem gox.Elem) error

type APointerOut

type APointerOut struct {
	// StopPropagation stops the event from bubbling up the DOM. Optional.
	StopPropagation bool
	// PreventDefault suppresses the browser's default action. Optional.
	PreventDefault bool
	// ExactTarget limits the handler to events whose target is the element
	// itself. Optional.
	ExactTarget bool
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestPointer) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

APointerOut handles the browser pointerout event on the element it is attached to. Fields and handler contract follow AClick.

func (APointerOut) Modify

func (p APointerOut) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (APointerOut) Proxy

func (p APointerOut) Proxy(cur gox.Cursor, elem gox.Elem) error

type APointerOver

type APointerOver struct {
	// StopPropagation stops the event from bubbling up the DOM. Optional.
	StopPropagation bool
	// PreventDefault suppresses the browser's default action. Optional.
	PreventDefault bool
	// ExactTarget limits the handler to events whose target is the element
	// itself. Optional.
	ExactTarget bool
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestPointer) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

APointerOver handles the browser pointerover event on the element it is attached to. Fields and handler contract follow AClick.

func (APointerOver) Modify

func (p APointerOver) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (APointerOver) Proxy

func (p APointerOver) Proxy(cur gox.Cursor, elem gox.Elem) error

type APointerUp

type APointerUp struct {
	// StopPropagation stops the event from bubbling up the DOM. Optional.
	StopPropagation bool
	// PreventDefault suppresses the browser's default action. Optional.
	PreventDefault bool
	// ExactTarget limits the handler to events whose target is the element
	// itself. Optional.
	ExactTarget bool
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// On handles the event on the server. Return false to keep the handler
	// active, true to remove it. Optional.
	On func(context.Context, RequestPointer) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

APointerUp handles the browser pointerup event on the element it is attached to. Fields and handler contract follow AClick.

func (APointerUp) Modify

func (p APointerUp) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (APointerUp) Proxy

func (p APointerUp) Proxy(cur gox.Cursor, elem gox.Elem) error

type ARawHook

type ARawHook struct {
	// Name is the hook name used from JavaScript as $hook(name, ...). Required.
	Name string
	// Scope controls how calls to this hook are scheduled on the client.
	// Optional; without it every call is sent immediately.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while a call is in flight.
	// A hook call has no event element, so only the Query and QueryAll variants
	// apply. Optional.
	Indicator Indicators
	// RequestTimeout overrides [Conf].RequestTimeout for calls to this hook.
	// Optional.
	RequestTimeout time.Duration
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// On handles the call with raw access to the request body and the response.
	// Return false to keep the hook active, true to remove it. Optional; a nil
	// On answers with an empty response.
	On func(ctx context.Context, r RequestRawHook) bool
}

ARawHook exposes a Go handler to browser code as $hook(name, ...) without JSON decoding or encoding.

Attach it to the script element that calls $hook or $fetch. The handler owns the request body and the response, which suits streaming, uploads, and custom formats. Prefer AHook for plain JSON input and output.

func (ARawHook) Modify

func (h ARawHook) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (ARawHook) Proxy

func (h ARawHook) Proxy(cur gox.Cursor, elem gox.Elem) error

type ARawSubmit

type ARawSubmit struct {
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// RequestTimeout overrides [Conf].RequestTimeout for this form's
	// requests. Optional.
	RequestTimeout time.Duration
	// On handles the submitted form on the server. Return false to keep the
	// handler active, true to remove it. Optional.
	On func(context.Context, RequestRawForm) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

ARawSubmit handles the browser submit event on the form it is attached to and gives On raw multipart access.

The native submission is always prevented and the form is sent as multipart/form-data. Return false from On to keep the handler active, true to remove it. A nil On still installs the hook and still sends the request.

Prefer ASubmit when the form decodes into a Go type.

func (ARawSubmit) Modify

func (s ARawSubmit) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (ARawSubmit) Proxy

func (s ARawSubmit) Proxy(cur gox.Cursor, elem gox.Elem) error

type ASubmit

type ASubmit[T any] struct {
	// Scope controls how the request is scheduled. Optional; unscoped requests
	// are sent as soon as the event fires.
	Scope Scopes
	// Indicator lists temporary DOM changes applied while the request is
	// in flight. Optional.
	Indicator Indicators
	// Race sets how overlapping calls to this handler are handled. Default:
	// [RaceSerial].
	Race Race
	// Batch applies the page updates made by this handler together, once it
	// finishes. Do not wait in the handler for an update to be applied.
	// Default: false.
	Batch bool
	// Before lists client-side actions to run before the request is
	// sent. Optional.
	Before Actions
	// RequestTimeout overrides [Conf].RequestTimeout for this form's
	// requests. Optional.
	RequestTimeout time.Duration
	// On handles the decoded form on the server. Return false to keep the
	// handler active, true to remove it. Optional.
	On func(context.Context, RequestForm[T]) bool
	// OnError lists client-side actions to run when the request
	// fails. Optional.
	OnError Actions
}

ASubmit handles the browser submit event on the form it is attached to and decodes the submitted values into T.

The native submission is always prevented and the form is sent as multipart/form-data. Field names come from form struct tags, or the Go field name when the tag is absent. A parse or decode failure skips On and runs OnError. File parts are not decoded; use ARawSubmit for uploads.

Return false from On to keep the handler active, true to remove it. A nil On still installs the hook and still sends the request.

func (ASubmit[V]) Modify

func (s ASubmit[V]) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (ASubmit[V]) Proxy

func (s ASubmit[V]) Proxy(cur gox.Cursor, elem gox.Elem) error

type Action

type Action interface {
	// contains filtered or unexported methods
}

Action is a client-side effect triggered from Go. Only Doors implements it.

type ActionEmit

type ActionEmit[T any] struct {
	// Name is the handler name passed to $on. The action fails when no handler
	// with this name is reachable. Required.
	Name string
	// Arg is the value passed to the handler. A string arrives as a string,
	// []byte as an ArrayBuffer, anything else as decoded JSON. Optional; nil
	// arrives as null.
	Arg any
}

ActionEmit calls the JavaScript handler registered with $on(name, handler).

Lookup starts at the Door the action is dispatched from and walks out to the root, so the nearest matching handler wins. T is the handler's return type; capture it with ActionInto.Into, or use ActionEmit[any] to ignore it.

func (ActionEmit[T]) Actions added in v0.12.1

func (ae ActionEmit[T]) Actions() []Action

func (ActionEmit[T]) And added in v0.12.1

func (ae ActionEmit[T]) And(a Actions) Actions

func (ActionEmit[T]) Into added in v0.15.0

func (ae ActionEmit[T]) Into(dst *T) Action

Into returns an action for Call that decodes the handler result into dst. If you need the result, wait for the second value on the channel; it only arrives on a detached context, and dst is valid once it is nil. Otherwise dst is not written. See Call.

type ActionIndicate

type ActionIndicate struct {
	// Indicator lists the temporary DOM changes to apply. Required; without it
	// the action does nothing.
	Indicator Indicators
	// Duration is how long the changes stay applied, truncated to
	// milliseconds. Required; zero removes them immediately.
	Duration time.Duration
}

ActionIndicate applies Indicator for Duration, independent of any request.

Only the Query and QueryAll indicator variants apply without an event element, which exists only in event attr and ALink action lists.

func (ActionIndicate) Actions added in v0.12.1

func (ai ActionIndicate) Actions() []Action

func (ActionIndicate) And added in v0.12.1

func (ai ActionIndicate) And(a Actions) Actions

type ActionInto added in v0.15.0

type ActionInto[T any] interface {
	Action
	// Into returns an action for [Call] that decodes the client result into
	// dst. If you need the result, wait for the second value on the channel;
	// it only arrives on a detached context, and dst is valid once it is nil.
	// Otherwise dst is not written. See [Call].
	Into(dst *T) Action
}

ActionInto is an Action with a capturable client result.

type ActionLocationAssign

type ActionLocationAssign struct {
	// Model is the target path model value, a [Location], or a
	// [LocationEncoder]. Required.
	Model any
}

ActionLocationAssign navigates to a URL built from Model, pushing a new history entry.

It is a hard navigation. Unlike ALink, the page loads again instead of rerouting the current instance.

func (ActionLocationAssign) Actions added in v0.12.1

func (aa ActionLocationAssign) Actions() []Action

func (ActionLocationAssign) And added in v0.12.1

type ActionLocationRawAssign

type ActionLocationRawAssign struct {
	// URL is the target URL. Must be absolute. Required.
	URL string
}

ActionLocationRawAssign navigates to URL, pushing a new history entry.

Unlike ActionLocationAssign, the URL is taken as given, so it can point to another origin.

func (ActionLocationRawAssign) Actions added in v0.12.1

func (aa ActionLocationRawAssign) Actions() []Action

func (ActionLocationRawAssign) And added in v0.12.1

type ActionLocationRawReplace added in v0.15.0

type ActionLocationRawReplace struct {
	// URL is the target URL. Must be absolute. Required.
	URL string
}

ActionLocationRawReplace replaces the current history entry with URL.

Unlike ActionLocationRawAssign, the current page is dropped from history, so the user cannot navigate back to it.

func (ActionLocationRawReplace) Actions added in v0.15.0

func (aa ActionLocationRawReplace) Actions() []Action

func (ActionLocationRawReplace) And added in v0.15.0

type ActionLocationReload

type ActionLocationReload struct{}

ActionLocationReload reloads the current page.

It is a hard navigation: the page loads again and a fresh instance starts.

func (ActionLocationReload) Actions added in v0.12.1

func (ar ActionLocationReload) Actions() []Action

func (ActionLocationReload) And added in v0.12.1

type ActionLocationReplace

type ActionLocationReplace struct {
	// Model is the target path model value, a [Location], or a
	// [LocationEncoder]. Required.
	Model any
}

ActionLocationReplace replaces the current history entry with a URL built from Model.

It is a hard navigation. Unlike ALink, the page loads again instead of rerouting the current instance.

func (ActionLocationReplace) Actions added in v0.12.1

func (ar ActionLocationReplace) Actions() []Action

func (ActionLocationReplace) And added in v0.12.1

type ActionScroll

type ActionScroll struct {
	// Selector is a CSS selector matched against the whole document. Required.
	Selector string
	// Options is passed to Element.scrollIntoView. Optional; nil uses the
	// browser default.
	Options any
}

ActionScroll scrolls the first element matching Selector into view.

If no element matches, the action fails; dispatched with Call on a detached context, the error arrives on the completion channel.

func (ActionScroll) Actions added in v0.12.1

func (aa ActionScroll) Actions() []Action

func (ActionScroll) And added in v0.12.1

func (aa ActionScroll) And(a Actions) Actions

type ActionTime added in v0.16.0

type ActionTime struct{}

ActionTime reads the client clock. The reading keeps the client's UTC offset.

Example:

var now time.Time
ch := doors.Call(doors.DetachedContext(ctx), doors.ActionTime{}.Into(&now))
<-ch
err, ok := <-ch

func (ActionTime) Into added in v0.16.0

func (a ActionTime) Into(dst *time.Time) Action

Into returns an action for Call that stores the reading into dst. If you need the result, wait for the second value on the channel; it only arrives on a detached context, and dst is valid once it is nil. Otherwise dst is not written. See Call.

type Actions added in v0.12.1

type Actions interface {
	Actions() []Action
	Joiner[Actions]
}

Actions is a composable list of client-side actions.

func JoinActions added in v0.12.1

func JoinActions(values ...Actions) Actions

JoinActions returns one Actions value that runs every value in order. Without arguments it returns nil.

type Active

type Active struct {
	// PathMatcher compares the link path with the current path. Default:
	// [PathMatcherFull].
	PathMatcher PathMatcher
	// QueryMatcher compares query parameters step by step, then any parameter
	// left over must be equal. Optional; nil compares all of them.
	QueryMatcher QueryMatcher
	// FragmentMatch also requires the fragment to be equal. Optional; the
	// fragment is ignored by default.
	FragmentMatch bool
	// Indicator is applied to the link while it matches the current location.
	// Required; without it the link is never marked active.
	Indicator Indicators
}

Active is the rule that decides when an ALink counts as the current location.

type App added in v0.12.1

type App interface {
	// Use wraps the app handler in middleware. The first one registered is
	// the outermost.
	Use(middleware ...func(http.Handler) http.Handler)
	// InstanceCount returns the number of live page instances across all
	// sessions.
	InstanceCount() int
	// SessionCount returns the number of live sessions.
	SessionCount() int
	// Drain switches the app into drain mode. With migrate true, in-app
	// navigation ends the instance so the browser reloads, and the app id
	// cookie stops being refreshed; with migrate false, instances are left
	// to end naturally. callback runs at most once, on its own goroutine,
	// when the last live instance is gone or immediately if none are live.
	// Drain is one-way for the lifetime of the app.
	Drain(migrate bool, callback func())
	http.Handler
}

App is a Doors application and HTTP handler.

func NewApp added in v0.12.1

func NewApp[C gox.Comp](page func(ctx context.Context, r Request) C, options ...With) App

NewApp returns an App that serves page as its page factory.

page runs once per page instance, on the full page load that creates it. ctx is the render context of that instance and r carries the HTTP request.

type Attr

type Attr interface {
	gox.Modify
	gox.Proxy
}

Attr is an attribute modifier that can be attached to an element or applied to the next element as a proxy.

func A

func A(ctx context.Context, a ...Attr) Attr

A combines attrs into a single Attr, resolved once against ctx.

Call it during render, with the ctx of the surrounding component. Elements sharing the result also share its handlers, so calls to one handler run one at a time.

type Beam

type Beam[T any] interface {
	// Effect returns the current value and rerenders the closest dynamic parent
	// when the value changes. Prefer [Beam.Bind] when a smaller fragment should
	// rerender.
	//
	// It returns false if the context was canceled or does not belong to an
	// instance runtime.
	Effect(ctx context.Context) (T, bool)

	// Bind renders f with the current value and rerenders only that fragment
	// when the value changes. If f returns nil, the fragment renders nothing.
	Bind(func(T) gox.Elem) gox.Elem

	// RouteBeam renders the first route that matches the current value and
	// switches branches as the value changes. Routes are tried in order and can
	// be nested. They receive a read-only [Beam].
	RouteBeam(routes ...BeamRoute[T]) gox.Elem

	// Sub subscribes to the value stream. onValue is called immediately with the
	// current value on the calling goroutine, then again on every update.
	//
	// The subscription ends when onValue returns true or the content that
	// registered it is cleared. From a context outside an instance, for
	// example [SessionContext] or a background context, it ends when the
	// context is canceled.
	//
	// It returns false if the context was canceled or the instance is shut
	// down.
	Sub(ctx context.Context, onValue func(context.Context, T) bool) bool

	// Read returns the current value without subscribing to updates. Any
	// context is allowed.
	//
	// It returns false if the context was canceled or the instance is shut
	// down.
	Read(ctx context.Context) (T, bool)

	// ReadAndSub returns the current value and subscribes to later updates.
	// Unlike [Beam.Sub], onValue is called only on later updates, not with the
	// current value. If onValue is nil, no subscription is created.
	//
	// The subscription ends when onValue returns true or the content that
	// registered it is cleared. From a context outside an instance, for
	// example [SessionContext] or a background context, it ends when the
	// context is canceled.
	//
	// It returns false if the context was canceled or the instance is shut
	// down.
	ReadAndSub(ctx context.Context, onValue func(context.Context, T) bool) (T, bool)

	// Watch subscribes w to the value stream and returns a function that
	// cancels the subscription. It returns false if the context was canceled
	// or the instance is shut down.
	//
	// w receives the current value on the calling goroutine, then every update.
	// The subscription ends when w.Watch returns true, the returned function is
	// called, or the content that registered it is cleared. From a context
	// outside an instance, for example [SessionContext] or a background
	// context, it ends when the context is canceled. w.Cancel runs when the
	// subscription ends, unless w.Watch ended it by returning true.
	//
	// Prefer [Beam.Sub] or [Beam.ReadAndSub] unless you need to cancel the
	// subscription explicitly.
	Watch(ctx context.Context, w Watcher[T]) (context.CancelFunc, bool)

	// Get returns the latest stored value.
	//
	// Unlike [Beam.Read], Get needs no context and does not participate in
	// render cycle consistency. Use Read when the value must agree with the
	// rest of the render.
	Get() T
	// contains filtered or unexported methods
}

Beam is a read-only reactive value.

Use it to read, subscribe to, or derive a narrower view of the value. Within one render/update cycle, a Door subtree observes one consistent value for the same beam.

func DeriveBeam added in v0.12.1

func DeriveBeam[T1 any, T2 comparable](source Beam[T1], get func(v T1) T2) Beam[T2]

DeriveBeam returns a derived beam of source, computed with get. It uses == to suppress equal derived values.

Example:

fullName := doors.DeriveBeam(user, func(u User) string {
	return u.FirstName + " " + u.LastName
})

func DeriveBeamEqual added in v0.12.1

func DeriveBeamEqual[T1 any, T2 any](source Beam[T1], get func(v T1) T2, equal func(old T2, new T2) bool) Beam[T2]

DeriveBeamEqual returns a derived beam of source, computed with get. It calls equal to suppress equal derived values. If equal is nil, every derived value propagates.

equal runs while the derived beam's lock is held: it must not panic and must not call back into any source or beam.

type BeamRoute added in v0.18.0

type BeamRoute[T any] interface {
	SourceRoute[T]
	// contains filtered or unexported methods
}

func RouteBeam added in v0.12.1

func RouteBeam[T any](render func(b Beam[T]) gox.Elem) BeamRoute[T]

func RouteBeamDerive added in v0.18.0

func RouteBeamDerive[T1 any, T2 any](derive func(beam Beam[T1]) Beam[T2], routes ...BeamRoute[T2]) BeamRoute[T1]

func RouteBeamMatch added in v0.18.0

func RouteBeamMatch[T any](match func(v T) bool, routes ...BeamRoute[T]) BeamRoute[T]

func RouteBeamModel added in v0.18.0

func RouteBeamModel[M any](routes ...BeamRoute[M]) BeamRoute[Location]

func RouteBeamValue added in v0.18.0

func RouteBeamValue[T any](value T, routes ...BeamRoute[T]) BeamRoute[T]

func RouteBind added in v0.18.0

func RouteBind[T any](render func(v T) gox.Elem) BeamRoute[T]

func RouteComp added in v0.18.0

func RouteComp[T any](render gox.Comp) BeamRoute[T]

type CSP

type CSP = common.CSP

CSP is the Content-Security-Policy Doors sends on page responses.

A nil slice and an empty non-nil slice mean different things on several fields, as noted on each.

type ChangeEmit added in v0.15.0

type ChangeEmit struct{}

ChangeEmit is the event init for the synthetic change events Emitter dispatches. Values are read from the event target, so attach the Emitter to the input or select element.

type ChangeEvent

type ChangeEvent struct {
	// Type is the DOM event type: change.
	Type string `json:"type"`
	// Name is the name attribute of the target element, empty if it has none.
	Name string `json:"name"`
	// Value is the current value of the target element.
	Value string `json:"value"`
	// Number is the value as a number, nil when it is not numeric.
	Number *float64 `json:"number"`
	// Date is the value as a date in UTC, nil when it is not a date.
	Date *time.Time `json:"date"`
	// Selected lists the values of the selected options, empty when the target
	// is not a select.
	Selected []string `json:"selected"`
	// Checked is the checked state of a checkbox or radio, false otherwise.
	Checked bool `json:"checked"`
	// Timestamp is the client clock reading when the event was captured.
	Timestamp time.Time `json:"timestamp"`
}

ChangeEvent is the payload of a browser change event.

The value fields are read from the element the event targets: Value always, Number, Date, Selected, and Checked when that element provides them.

type Classes added in v0.9.7

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

Classes is an immutable list of class names, plus names to omit from output.

Use it as a class attribute value, as an attribute modifier, or as a proxy before an element or component. Every operation returns a new value and leaves the receiver unchanged.

func Class added in v0.9.7

func Class(classes ...string) Classes

Class returns a Classes value holding the given class names.

Each argument is split on whitespace, so Class("a", "b c") and Class("a b c") produce the same classes.

func (Classes) Add added in v0.9.7

func (c Classes) Add(classes ...string) Classes

Add returns a new value with classes appended, split like Class.

func (Classes) Clone added in v0.9.7

func (c Classes) Clone() Classes

Clone returns an independent copy.

func (Classes) Filter added in v0.9.7

func (c Classes) Filter(classes ...string) Classes

Filter returns a new value that omits matching classes from output.

Unlike Classes.Remove, the names stay omitted even when added later or joined in from another value.

func (Classes) Join added in v0.9.7

func (c Classes) Join(classes ...Classes) Classes

Join returns a new value that merges classes into the current one.

Names to omit are merged too, so a filter from any joined value applies to the whole result.

func (Classes) Modify added in v0.9.7

func (c Classes) Modify(ctx context.Context, tag string, atts gox.Attrs) error

func (Classes) Mutate added in v0.9.7

func (c Classes) Mutate(name string, prev any) any

func (Classes) Output added in v0.9.7

func (c Classes) Output(w io.Writer) error

func (Classes) Proxy added in v0.9.7

func (c Classes) Proxy(cur gox.Cursor, el gox.Elem) error

func (Classes) Remove added in v0.9.7

func (c Classes) Remove(classes ...string) Classes

Remove returns a new value without the listed classes.

Unlike Classes.Filter, the names are not remembered, so the same class can be added again afterwards.

func (Classes) String added in v0.9.7

func (c Classes) String() string

String returns the class list as it is rendered in a class attribute.

type Conf added in v0.12.1

type Conf = common.Conf

Conf tunes session and page instance lifetimes, request limits, resource serving, and the server-to-browser update stream.

Every field is optional: zero or invalid timeouts, limits, and sizes take the defaults documented on each field, and the flags default to off.

type Door

type Door = door.Door

Door is a dynamic part of the page that can be updated, replaced, or removed after render.

A Door is not mounted until it is rendered, and [Door.Unmount] or removal by an ancestor returns it to that state. While it is not mounted, operations change its stored state, which the next render puts on the page.

The context of content rendered inside a Door is canceled when that content leaves the page, which makes ctx.Done() usable in background work.

type ESProfile added in v0.12.1

type ESProfile struct {
	// External lists import paths esbuild leaves out of the bundle.
	External []string
	// Minify enables esbuild syntax, whitespace, and identifier minification.
	Minify bool
	// JSX configures the JSX transform.
	JSX JSX
}

ESProfile is a With option that applies one set of esbuild options to every script profile. Use WithESProfiles to vary options per profile.

func (ESProfile) Profile added in v0.12.1

func (opt ESProfile) Profile(string) api.BuildOptions

Profile returns the same esbuild options for every profile name.

type Emitter added in v0.15.0

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

Emitter dispatches synthetic DOM events to the elements it is attached to.

Attach it as an attribute to one or more elements, then dispatch an event method's action with Call. Unset event init fields use the browser defaults. The events bubble, so event attrs on ancestor elements run too.

Several emitters can share an element; each dispatches its own event.

Into captures the number of hook requests the emitted events triggered, not the number of elements reached; a failure in any of them fails the call (see ActionInto). The action completes only after every triggered hook request has finished.

func (*Emitter) Blur added in v0.15.0

func (e *Emitter) Blur(emit FocusEmit) ActionInto[int]

Blur returns an action emitting a blur event.

func (*Emitter) Change added in v0.15.0

func (e *Emitter) Change(emit ChangeEmit) ActionInto[int]

Change returns an action emitting a change event.

func (*Emitter) Click added in v0.15.0

func (e *Emitter) Click(emit PointerEmit) ActionInto[int]

Click returns an action emitting a click event.

func (*Emitter) Focus added in v0.15.0

func (e *Emitter) Focus(emit FocusEmit) ActionInto[int]

Focus returns an action emitting a focus event.

func (*Emitter) FocusIn added in v0.15.0

func (e *Emitter) FocusIn(emit FocusEmit) ActionInto[int]

FocusIn returns an action emitting a focusin event.

func (*Emitter) FocusOut added in v0.15.0

func (e *Emitter) FocusOut(emit FocusEmit) ActionInto[int]

FocusOut returns an action emitting a focusout event.

func (*Emitter) GotPointerCapture added in v0.15.0

func (e *Emitter) GotPointerCapture(emit PointerEmit) ActionInto[int]

GotPointerCapture returns an action emitting a gotpointercapture event.

func (*Emitter) Input added in v0.15.0

func (e *Emitter) Input(emit InputEmit) ActionInto[int]

Input returns an action emitting an input event.

func (*Emitter) KeyDown added in v0.15.0

func (e *Emitter) KeyDown(emit KeyboardEmit) ActionInto[int]

KeyDown returns an action emitting a keydown event.

func (*Emitter) KeyUp added in v0.15.0

func (e *Emitter) KeyUp(emit KeyboardEmit) ActionInto[int]

KeyUp returns an action emitting a keyup event.

func (*Emitter) LostPointerCapture added in v0.15.0

func (e *Emitter) LostPointerCapture(emit PointerEmit) ActionInto[int]

LostPointerCapture returns an action emitting a lostpointercapture event.

func (*Emitter) Modify added in v0.15.0

func (e *Emitter) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (*Emitter) PointerCancel added in v0.15.0

func (e *Emitter) PointerCancel(emit PointerEmit) ActionInto[int]

PointerCancel returns an action emitting a pointercancel event.

func (*Emitter) PointerDown added in v0.15.0

func (e *Emitter) PointerDown(emit PointerEmit) ActionInto[int]

PointerDown returns an action emitting a pointerdown event.

func (*Emitter) PointerEnter added in v0.15.0

func (e *Emitter) PointerEnter(emit PointerEmit) ActionInto[int]

PointerEnter returns an action emitting a pointerenter event.

func (*Emitter) PointerLeave added in v0.15.0

func (e *Emitter) PointerLeave(emit PointerEmit) ActionInto[int]

PointerLeave returns an action emitting a pointerleave event.

func (*Emitter) PointerMove added in v0.15.0

func (e *Emitter) PointerMove(emit PointerEmit) ActionInto[int]

PointerMove returns an action emitting a pointermove event.

func (*Emitter) PointerOut added in v0.15.0

func (e *Emitter) PointerOut(emit PointerEmit) ActionInto[int]

PointerOut returns an action emitting a pointerout event.

func (*Emitter) PointerOver added in v0.15.0

func (e *Emitter) PointerOver(emit PointerEmit) ActionInto[int]

PointerOver returns an action emitting a pointerover event.

func (*Emitter) PointerUp added in v0.15.0

func (e *Emitter) PointerUp(emit PointerEmit) ActionInto[int]

PointerUp returns an action emitting a pointerup event.

func (*Emitter) Proxy added in v0.15.0

func (e *Emitter) Proxy(cur gox.Cursor, elem gox.Elem) error

func (*Emitter) Submit added in v0.15.0

func (e *Emitter) Submit(emit SubmitEmit) ActionInto[int]

Submit returns an action emitting a submit event.

type ErrorPage added in v0.12.1

type ErrorPage = app.ErrorPage

ErrorPage renders the body of an app-level error response.

It runs when Doors cannot serve a page, with the failed request and the error. Doors has already written status 500, so the returned element cannot change it.

type FocusEmit added in v0.15.0

type FocusEmit struct{}

FocusEmit is the event init for the synthetic focus events Emitter dispatches. Dispatching one runs the handlers without moving focus.

type FocusEvent

type FocusEvent struct {
	// Type is the DOM event type: focus, blur, focusin, or focusout.
	Type string `json:"type"`
	// Timestamp is the client clock reading when the event was captured.
	Timestamp time.Time `json:"timestamp"`
}

FocusEvent is the payload of a browser focus event.

type Indicator

type Indicator = front.Indicator

Indicator is a single temporary DOM change, applied while a request is in flight or for a fixed duration, and reverted afterwards.

Overlapping indicators on the same element queue up.

type IndicatorAttr

type IndicatorAttr struct {
	// Selector picks the target elements. Optional; the zero value selects
	// the event element.
	Selector Selector
	// Name is the attribute to set. Required.
	Name string
	// Value is the attribute value; nil or false removes the attribute.
	Value any
}

IndicatorAttr temporarily sets an attribute on the selected elements.

Value follows template attribute semantics: nil and false remove the attribute, true sets it bare, gox.Output values serialize themselves, anything else is formatted with the fmt package. A gox.Mutate value or a failing gox.Output is logged and skipped.

func IndicateAttr added in v0.12.1

func IndicateAttr(name string, value any) IndicatorAttr

IndicateAttr builds an IndicatorAttr that targets the event element.

func IndicateAttrQuery added in v0.12.1

func IndicateAttrQuery(query, name string, value any) IndicatorAttr

IndicateAttrQuery builds an IndicatorAttr that targets the first element matching query.

func IndicateAttrQueryAll added in v0.12.1

func IndicateAttrQueryAll(query, name string, value any) IndicatorAttr

IndicateAttrQueryAll builds an IndicatorAttr that targets every element matching query.

func IndicateAttrQueryParent added in v0.12.1

func IndicateAttrQueryParent(query, name string, value any) IndicatorAttr

IndicateAttrQueryParent builds an IndicatorAttr that targets the closest ancestor matching query.

func (IndicatorAttr) And added in v0.12.1

func (IndicatorAttr) Indicators added in v0.12.1

func (ia IndicatorAttr) Indicators() []Indicator

type IndicatorClass

type IndicatorClass struct {
	// Selector picks the target elements. Optional; the zero value selects
	// the event element.
	Selector Selector
	// Class is one or more space-separated class names to add. Required.
	Class string
}

IndicatorClass temporarily adds CSS classes to the selected elements.

func IndicateClass added in v0.12.1

func IndicateClass(class string) IndicatorClass

IndicateClass builds an IndicatorClass that targets the event element.

func IndicateClassQuery added in v0.12.1

func IndicateClassQuery(query, class string) IndicatorClass

IndicateClassQuery builds an IndicatorClass that targets the first element matching query.

func IndicateClassQueryAll added in v0.12.1

func IndicateClassQueryAll(query, class string) IndicatorClass

IndicateClassQueryAll builds an IndicatorClass that targets every element matching query.

func IndicateClassQueryParent added in v0.12.1

func IndicateClassQueryParent(query, class string) IndicatorClass

IndicateClassQueryParent builds an IndicatorClass that targets the closest ancestor matching query.

func (IndicatorClass) And added in v0.12.1

func (IndicatorClass) Indicators added in v0.12.1

func (ic IndicatorClass) Indicators() []Indicator

type IndicatorClassRemove

type IndicatorClassRemove struct {
	// Selector picks the target elements. Optional; the zero value selects
	// the event element.
	Selector Selector
	// Class is one or more space-separated class names to remove. Required.
	Class string
}

IndicatorClassRemove temporarily removes CSS classes from the selected elements.

func IndicateClassRemove added in v0.12.1

func IndicateClassRemove(class string) IndicatorClassRemove

IndicateClassRemove builds an IndicatorClassRemove that targets the event element.

func IndicateClassRemoveQuery added in v0.12.1

func IndicateClassRemoveQuery(query, class string) IndicatorClassRemove

IndicateClassRemoveQuery builds an IndicatorClassRemove that targets the first element matching query.

func IndicateClassRemoveQueryAll added in v0.12.1

func IndicateClassRemoveQueryAll(query, class string) IndicatorClassRemove

IndicateClassRemoveQueryAll builds an IndicatorClassRemove that targets every element matching query.

func IndicateClassRemoveQueryParent added in v0.12.1

func IndicateClassRemoveQueryParent(query, class string) IndicatorClassRemove

IndicateClassRemoveQueryParent builds an IndicatorClassRemove that targets the closest ancestor matching query.

func (IndicatorClassRemove) And added in v0.12.1

func (IndicatorClassRemove) Indicators added in v0.12.1

func (irc IndicatorClassRemove) Indicators() []Indicator

type IndicatorContent

type IndicatorContent struct {
	// Selector picks the target elements. Optional; the zero value selects
	// the event element.
	Selector Selector
	// Content is the replacement HTML. Required. WARNING: escaping is not
	// applied.
	Content string
}

IndicatorContent temporarily replaces the content of the selected elements.

WARNING: escaping is not applied.

func IndicateContent added in v0.12.1

func IndicateContent(content string) IndicatorContent

IndicateContent builds an IndicatorContent that targets the event element. WARNING: escaping is not applied.

func IndicateContentQuery added in v0.12.1

func IndicateContentQuery(query, content string) IndicatorContent

IndicateContentQuery builds an IndicatorContent that targets the first element matching query. WARNING: escaping is not applied.

func IndicateContentQueryAll added in v0.12.1

func IndicateContentQueryAll(query, content string) IndicatorContent

IndicateContentQueryAll builds an IndicatorContent that targets every element matching query. WARNING: escaping is not applied.

func IndicateContentQueryParent added in v0.12.1

func IndicateContentQueryParent(query, content string) IndicatorContent

IndicateContentQueryParent builds an IndicatorContent that targets the closest ancestor matching query. WARNING: escaping is not applied.

func (IndicatorContent) And added in v0.12.1

func (IndicatorContent) Indicators added in v0.12.1

func (ic IndicatorContent) Indicators() []Indicator

type Indicators added in v0.12.1

type Indicators interface {
	Indicators() []Indicator
	Joiner[Indicators]
}

Indicators is a composable list of temporary DOM changes.

func JoinIndicators added in v0.12.1

func JoinIndicators(values ...Indicators) Indicators

JoinIndicators returns one Indicators value that applies every value in order. Without arguments it returns nil.

type InputEmit added in v0.15.0

type InputEmit struct {
	// Data is the inserted text to report. Optional.
	Data string `json:"data,omitempty"`
}

InputEmit is the event init for the synthetic input events Emitter dispatches. Values are read from the event target, so attach the Emitter to the input or select element.

type InputEvent

type InputEvent struct {
	// Type is the DOM event type: input.
	Type string `json:"type"`
	// Name is the name attribute of the target element, empty if it has none.
	Name string `json:"name"`
	// Data is the text inserted by the edit, empty when the edit inserts none.
	Data string `json:"data"`
	// Date is the value as a date in UTC, nil when it is not a date.
	Date *time.Time `json:"date"`
	// Value is the current value of the target element.
	Value string `json:"value"`
	// Number is the value as a number, nil when it is not numeric.
	Number *float64 `json:"number"`
	// Selected lists the values of the selected options, empty when the target
	// is not a select.
	Selected []string `json:"selected"`
	// Checked is the checked state of a checkbox or radio, false otherwise.
	Checked bool `json:"checked"`
	// Timestamp is the client clock reading when the event was captured.
	Timestamp time.Time `json:"timestamp"`
}

InputEvent is the payload of a browser input event.

The value fields are read from the element the event targets. When AInput.ExcludeValue is set, only Type, Data, and Timestamp are filled.

type JSX

type JSX struct {
	// JSX selects the esbuild JSX mode. Optional; the zero value is
	// [api.JSXTransform].
	JSX api.JSX
	// Factory is the function called for a JSX element outside the automatic
	// runtime. Optional; esbuild uses React.createElement.
	Factory string
	// ImportSource is the base package the automatic runtime imports from.
	// Optional; esbuild uses react.
	ImportSource string
	// Fragment is the expression used for a JSX fragment outside the automatic
	// runtime. Optional; esbuild uses React.Fragment.
	Fragment string
	// SideEffects tells esbuild that JSX elements may have side effects, so
	// unused ones are kept.
	SideEffects bool
	// Dev emits jsxDEV calls with source locations. Applies to the automatic
	// runtime only.
	Dev bool
}

JSX is the JSX transform configuration for ESProfile.

func JSXPreact

func JSXPreact() JSX

JSXPreact returns JSX settings that compile elements to h calls, with Fragment as the fragment expression.

func JSXReact

func JSXReact() JSX

JSXReact returns JSX settings that use the automatic runtime and import from react/jsx-runtime.

type Joiner added in v0.12.1

type Joiner[T any] interface {
	And(T) T
}

Joiner is implemented by values that combine with another value of the same type, applying the receiver first and then the argument.

type Key added in v0.14.2

type Key struct {
	// Key is the event.key value to match. An empty string matches any key.
	Key string
	// CtrlMod is the required ctrl state. Default: [ModAny].
	CtrlMod Mod
	// ShiftMod is the required shift state. Default: [ModAny].
	ShiftMod Mod
	// AltMod is the required alt state. Default: [ModAny].
	AltMod Mod
	// MetaMod is the required meta state. Default: [ModAny].
	MetaMod Mod
}

Key is one key and modifier combination matched against a keyboard event.

func (Key) And added in v0.16.0

func (k Key) And(keys Keys) Keys

func (Key) Keys added in v0.16.0

func (k Key) Keys() []Key

type KeyboardEmit added in v0.15.0

type KeyboardEmit struct {
	// Key is the key value to report. Optional.
	Key string `json:"key,omitempty"`
	// Code is the physical key code to report. Optional.
	Code string `json:"code,omitempty"`
	// Repeat reports the key as auto-repeating. Optional.
	Repeat bool `json:"repeat,omitempty"`
	// CtrlKey reports Control as held down. Optional.
	CtrlKey bool `json:"ctrlKey,omitempty"`
	// ShiftKey reports Shift as held down. Optional.
	ShiftKey bool `json:"shiftKey,omitempty"`
	// AltKey reports Alt as held down. Optional.
	AltKey bool `json:"altKey,omitempty"`
	// MetaKey reports Meta as held down. Optional.
	MetaKey bool `json:"metaKey,omitempty"`
}

KeyboardEmit is the event init for the synthetic keyboard events Emitter dispatches. An event that matches no entry of AKeyDown.Key or AKeyUp.Key on the target attr sends no request.

type KeyboardEvent

type KeyboardEvent struct {
	// Type is the DOM event type: keydown or keyup.
	Type string `json:"type"`
	// Key is the value of the key pressed, such as a or Enter.
	Key string `json:"key"`
	// Code is the physical key code, such as KeyA.
	Code string `json:"code"`
	// Repeat reports whether the key was already down and is auto-repeating.
	Repeat bool `json:"repeat"`
	// CtrlKey reports whether Control was held down.
	CtrlKey bool `json:"ctrlKey"`
	// ShiftKey reports whether Shift was held down.
	ShiftKey bool `json:"shiftKey"`
	// AltKey reports whether Alt was held down.
	AltKey bool `json:"altKey"`
	// MetaKey reports whether Meta was held down.
	MetaKey bool `json:"metaKey"`
	// Timestamp is the client clock reading when the event was captured.
	Timestamp time.Time `json:"timestamp"`
}

KeyboardEvent is the payload of a browser keyboard event.

type Keys added in v0.16.0

type Keys interface {
	Keys() []Key
	Joiner[Keys]
}

Keys is a composable list of key matches. An event passes when it matches any of them.

func JoinKeys added in v0.16.0

func JoinKeys(values ...Keys) Keys

JoinKeys returns one Keys value that matches any key of every value. Without arguments it returns nil.

type Location

type Location = path.Location

Location is a URL path plus query string, held in decoded form, as read from and written to Router.

Copies share Segments and Query, so use Clone before modifying a Location read from a source.

Example
loc := Location{
	Segments: []string{"posts", "42"},
	Query: url.Values{
		"tag":  []string{"go"},
		"page": []string{"2"},
	},
}

fmt.Println(loc.String())
Output:
/posts/42?page=2&tag=go

func NewLocation

func NewLocation(model any) (Location, error)

NewLocation encodes model into a Location.

model may be a Location, a path model struct, a pointer to a path model struct, or a value implementing LocationEncoder. It returns an error if model is none of these or cannot be encoded.

Example
loc, err := NewLocation(examplePath{Section: exampleSectionPost, ID: 42})
if err != nil {
	panic(err)
}

fmt.Println(loc.String())
Output:
/posts/42

type LocationEncoder added in v0.12.1

type LocationEncoder = path.Encoder

LocationEncoder is implemented by models that build their own Location instead of describing their path with tags.

type Mod added in v0.14.2

type Mod uint8

Mod is the required state of a keyboard modifier in a Key match.

const (
	// ModAny matches regardless of whether the modifier is held.
	ModAny Mod = iota
	// ModOn requires the modifier to be held.
	ModOn
	// ModOff requires the modifier to not be held.
	ModOff
)

Modifier states for Key.

type ParsedForm

type ParsedForm interface {
	// FormValues returns the form fields merged with the URL query values.
	FormValues() url.Values
	// FormValue returns the first value for key, empty if there is none.
	FormValue(key string) string
	// FormFile returns the first uploaded file for key, or an error if there
	// is none.
	FormFile(key string) (multipart.File, *multipart.FileHeader, error)
	// Form returns the parsed values and file headers.
	Form() *multipart.Form
}

ParsedForm is a parsed multipart form.

type PathMatcher

type PathMatcher interface {
	// contains filtered or unexported methods
}

PathMatcher is the path comparison rule of Active matching.

func PathMatcherFull

func PathMatcherFull() PathMatcher

PathMatcherFull returns a PathMatcher that matches when the whole path is equal, ignoring leading and trailing slashes.

func PathMatcherSegments

func PathMatcherSegments(i ...int) PathMatcher

PathMatcherSegments returns a PathMatcher that compares only the path segments at the given indexes, counted from zero. Without indexes it matches any path.

func PathMatcherStarts

func PathMatcherStarts() PathMatcher

PathMatcherStarts returns a PathMatcher that matches when the current path starts with the link path. The comparison is by string prefix, not by whole segments.

type PointerEmit added in v0.15.0

type PointerEmit struct {
	// PointerID is the pointer identifier to report. Optional.
	PointerID int `json:"pointerId,omitempty"`
	// Buttons is the bitmask of buttons to report as held down. Optional.
	Buttons int `json:"buttons,omitempty"`
	// Button is the button to report as changed. Optional.
	Button int `json:"button,omitempty"`
	// PointerType is the device kind to report, such as mouse or pen. Optional.
	PointerType string `json:"pointerType,omitempty"`
	// IsPrimary reports the pointer as the primary one of its type. Optional.
	IsPrimary bool `json:"isPrimary,omitempty"`
}

PointerEmit is the event init for the synthetic pointer events Emitter dispatches.

type PointerEvent

type PointerEvent struct {
	// Type is the DOM event type, such as click or pointerdown.
	Type string `json:"type"`
	// PointerID identifies the pointer that produced the event.
	PointerID int `json:"pointerId"`
	// Pressure is the normalized pointer pressure, from 0 to 1.
	Pressure float64 `json:"pressure"`
	// TangentialPressure is the normalized barrel pressure, from -1 to 1.
	TangentialPressure float64 `json:"tangentialPressure"`
	// TiltX is the pointer tilt along the X axis, in degrees from -90 to 90.
	TiltX float64 `json:"tiltX"`
	// TiltY is the pointer tilt along the Y axis, in degrees from -90 to 90.
	TiltY float64 `json:"tiltY"`
	// Twist is the clockwise rotation of the pointer, in degrees.
	Twist float64 `json:"twist"`
	// Buttons is the bitmask of the buttons currently held down.
	Buttons int `json:"buttons"`
	// Button is the button whose state changed, or -1 when none did.
	Button int `json:"button"`
	// PointerType is the device kind, such as mouse, pen, or touch.
	PointerType string `json:"pointerType"`
	// IsPrimary reports whether this is the primary pointer of its type.
	IsPrimary bool `json:"isPrimary"`
	// Pointer is the pointer offset inside the event target as X, Y and the
	// contact geometry as Width, Height.
	Pointer Rect `json:"pointer"`
	// Target is the viewport-relative bounding rectangle of the element the
	// attr is attached to.
	Target Rect `json:"target"`
	// Page is the document scroll offset as X, Y and the viewport size as
	// Width, Height.
	Page Rect `json:"page"`
	// Screen is the viewport offset on the screen as X, Y and the browser
	// window's outer size as Width, Height.
	Screen Rect `json:"screen"`
	// Timestamp is the client clock reading when the event was captured.
	Timestamp time.Time `json:"timestamp"`
}

PointerEvent is the payload of a browser pointer event.

Geometry arrives as rectangles; the OffsetX, ClientX, PageX and ScreenX methods and their Y counterparts derive coordinates from them.

func (PointerEvent) ClientX added in v0.12.33

func (e PointerEvent) ClientX() float64

ClientX returns the horizontal coordinate relative to the viewport.

func (PointerEvent) ClientY added in v0.12.33

func (e PointerEvent) ClientY() float64

ClientY returns the vertical coordinate relative to the viewport.

func (PointerEvent) OffsetX added in v0.12.33

func (e PointerEvent) OffsetX() float64

OffsetX returns the horizontal offset relative to the target element's padding edge.

func (PointerEvent) OffsetY added in v0.12.33

func (e PointerEvent) OffsetY() float64

OffsetY returns the vertical offset relative to the target element's padding edge.

func (PointerEvent) PageX added in v0.12.33

func (e PointerEvent) PageX() float64

PageX returns the horizontal coordinate relative to the document.

func (PointerEvent) PageY added in v0.12.33

func (e PointerEvent) PageY() float64

PageY returns the vertical coordinate relative to the document.

func (PointerEvent) ScreenX added in v0.12.33

func (e PointerEvent) ScreenX() float64

ScreenX returns the horizontal coordinate relative to the screen.

func (PointerEvent) ScreenY added in v0.12.33

func (e PointerEvent) ScreenY() float64

ScreenY returns the vertical coordinate relative to the screen.

type QueryMatcher

type QueryMatcher interface {
	Joiner[QueryMatcher]
	// contains filtered or unexported methods
}

QueryMatcher is a query-string comparison step of Active matching. Chain steps with Joiner.And.

func QueryMatcherIfPresent

func QueryMatcherIfPresent(params ...string) QueryMatcher

QueryMatcherIfPresent returns a QueryMatcher that compares params only when the current location carries them, and drops them from the comparison of later steps.

func QueryMatcherIgnoreAll

func QueryMatcherIgnoreAll() QueryMatcher

QueryMatcherIgnoreAll returns a QueryMatcher that ends the chain, leaving every remaining parameter out of the comparison.

func QueryMatcherIgnoreSome

func QueryMatcherIgnoreSome(params ...string) QueryMatcher

QueryMatcherIgnoreSome returns a QueryMatcher that drops params from the comparison and passes the remaining parameters to the next step.

func QueryMatcherSome

func QueryMatcherSome(params ...string) QueryMatcher

QueryMatcherSome returns a QueryMatcher that compares params at this step and drops them from the comparison of later steps.

type Race added in v0.16.0

type Race = core.Race

Race is how overlapping calls to one handler are handled on the server.

type Rect added in v0.12.33

type Rect struct {
	// X is the horizontal origin.
	X float64 `json:"x"`
	// Y is the vertical origin.
	Y float64 `json:"y"`
	// Width is the horizontal size.
	Width float64 `json:"width"`
	// Height is the vertical size.
	Height float64 `json:"height"`
}

Rect is a rectangle in CSS pixels: origin X, Y and size Width, Height.

type Request

type Request interface {
	RequestCommon
	// ResponseHeader returns the outgoing response headers.
	ResponseHeader() http.Header
}

Request is the request handle passed to the page factory, for cookies and request or response headers.

type RequestAfter

type RequestAfter interface {
	// After registers actions to run on the client once the response
	// succeeds. A second call replaces the actions of the first.
	After(a Actions) error
}

RequestAfter is the part of a request handle that runs client-side actions after a successful response.

type RequestChange

type RequestChange = RequestEvent[ChangeEvent]

RequestChange is the request handle passed to AChange handlers.

type RequestCommon added in v0.12.1

type RequestCommon interface {
	// SetCookie adds a cookie to the response.
	SetCookie(cookie *http.Cookie)
	// GetCookie returns the named request cookie, or [http.ErrNoCookie] if it
	// is not present.
	GetCookie(name string) (*http.Cookie, error)
	// Context returns the context of the underlying HTTP request. It is not
	// the Doors runtime context the handler receives.
	Context() context.Context
	// RequestHeader returns the incoming request headers.
	RequestHeader() http.Header
	// RemoteAddr returns the address of the direct peer as host:port. Proxy
	// headers are not applied.
	RemoteAddr() string
}

RequestCommon is the HTTP-level part of every request handle Doors passes to a handler.

type RequestEvent

type RequestEvent[E any] interface {
	RequestCommon
	RequestAfter
	// Event returns the decoded event payload.
	Event() E
}

RequestEvent is the request handle passed to event attr handlers.

type RequestFocus

type RequestFocus = RequestEvent[FocusEvent]

RequestFocus is the request handle passed to focus event attr handlers.

type RequestForm

type RequestForm[D any] interface {
	RequestCommon
	RequestAfter
	// Data returns the submitted form decoded into D.
	Data() D
}

RequestForm is the request handle passed to ASubmit handlers.

type RequestHook

type RequestHook[D any] interface {
	RequestCommon
	RequestAfter
	// Data returns the hook argument decoded from JSON into D.
	Data() D
}

RequestHook is the request handle passed to AHook handlers.

type RequestInput

type RequestInput = RequestEvent[InputEvent]

RequestInput is the request handle passed to AInput handlers.

type RequestKeyboard

type RequestKeyboard = RequestEvent[KeyboardEvent]

RequestKeyboard is the request handle passed to AKeyDown and AKeyUp handlers.

type RequestPointer

type RequestPointer = RequestEvent[PointerEvent]

RequestPointer is the request handle passed to pointer event attr handlers.

type RequestRawForm

type RequestRawForm interface {
	RequestCommon
	RequestAfter
	// SetRequestBodyLimit sets the max body size in bytes accepted by later
	// Body, ParseForm, and Reader calls. A negative limit disables the
	// check; zero rejects a non-empty body. Default: ServerRequestBodyLimit
	// of [Conf].
	SetRequestBodyLimit(limit int)
	// ResponseWriter returns the writer for the response.
	ResponseWriter() http.ResponseWriter
	// Reader returns a multipart reader for streaming the form one part at a
	// time. Unlike [RequestRawForm.ParseForm], it buffers no part to disk.
	Reader() (*multipart.Reader, error)
	// ParseForm parses the whole multipart body, keeping up to maxMemory
	// bytes of file parts in memory and storing the rest in temporary files.
	// It fails if the body is not a multipart form.
	ParseForm(maxMemory int) (ParsedForm, error)
}

RequestRawForm is the request handle passed to ARawSubmit handlers, with the multipart body left undecoded.

type RequestRawHook

type RequestRawHook interface {
	RequestRawForm
	// Body returns the request body, bounded by the limit from
	// [RequestRawForm.SetRequestBodyLimit].
	Body() io.ReadCloser
}

RequestRawHook is the request handle passed to ARawHook handlers, with the body left undecoded.

type Resource

type Resource = printer.SourceHandler

Resource is app-owned content that Doors serves under a generated src or href URL.

Assign it to a src or href attribute, or attach it as a modifier to a tag that takes one of them; a modifier on any other tag fails the render.

Unless the resource is a ResourceStatic served from a cache, the generated URL is private to the current page instance and stops working once the content around it is cleared.

func ResourceHandler

func ResourceHandler(handler func(w http.ResponseWriter, r *http.Request)) Resource

ResourceHandler returns a Resource served by handler.

Unlike ResourceHook, the resource keeps serving every request.

WARNING: the request body is not limited by the ServerRequestBodyLimit of Conf.

func ResourceHook

func ResourceHook(handler func(ctx context.Context, w http.ResponseWriter, r *http.Request) bool) Resource

ResourceHook returns a Resource served by handler.

Return true from handler to stop serving the resource after that request, false to keep it available.

WARNING: the request body is not limited by the ServerRequestBodyLimit of Conf.

func ResourceProxy

func ResourceProxy(url string) Resource

ResourceProxy returns a Resource that reverse-proxies requests to url.

Unlike ResourceExternal, the browser loads it from a Doors-generated URL. If url cannot be parsed, requests fail with status 500.

type ResourceExternal

type ResourceExternal = printer.SourceExternal

ResourceExternal is a URL the browser loads directly from another host.

Doors adds its exact URL to the generated Content-Security-Policy for script tags and stylesheet or modulepreload links rendered with the page.

type ResourceStatic

type ResourceStatic = printer.SourceStatic

ResourceStatic is a Resource whose content Doors reads up front.

Unlike other resources, it accepts the cache, private, and nocache attributes. With cache, Doors keeps the content in RAM and serves it from a shared, publicly reachable URL derived from its hash. It can also be mounted at a fixed path with UseResource, or given that URL in code with NewResource.

func ResourceBytes

func ResourceBytes(content []byte) ResourceStatic

ResourceBytes returns a ResourceStatic that serves content from memory.

func ResourceFS

func ResourceFS(fsys fs.FS, entry string) ResourceStatic

ResourceFS returns a ResourceStatic that serves entry from fsys.

func ResourceLocalFS

func ResourceLocalFS(path string) ResourceStatic

ResourceLocalFS returns a ResourceStatic that serves the local file at path.

func ResourceString

func ResourceString(content string) ResourceStatic

ResourceString returns a ResourceStatic that serves content from memory.

type Scope

type Scope = front.Scope

Scope is one client-side scheduling policy applied to a hook request.

Values come from the Scopes types, such as ScopeBlocking, ScopeDebounce, or ScopeLatest.

type ScopeBlocking

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

ScopeBlocking rejects a hook request while an earlier request in the same scope has not finished.

Each value is one scope: share one value between attrs to make them coordinate, or use separate values to keep them independent.

A rejected request is never sent, so its handler does not run and its indication does not start.

func (*ScopeBlocking) And added in v0.12.1

func (sb *ScopeBlocking) And(s Scopes) Scopes

func (*ScopeBlocking) Scopes added in v0.12.1

func (sb *ScopeBlocking) Scopes(core core.Core) []Scope

type ScopeConcurrent

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

ScopeConcurrent lets hook requests in the same scope overlap only when they share a group.

It does not satisfy Scopes; call Scope to obtain a value.

One value is one scope; see ScopeBlocking for sharing.

func (*ScopeConcurrent) Scope

func (d *ScopeConcurrent) Scope(groupID int) Scopes

Scope assigns a request to the group identified by groupID. While the scope holds requests of one group, a request of any other group is rejected.

type ScopeDebounce

type ScopeDebounce struct {
	// Duration is the quiet period before the pending request is sent. Every
	// new event restarts it. Required.
	Duration time.Duration
	// Limit caps the wait, measured from the first pending event. Optional;
	// zero means no cap.
	Limit time.Duration
	// contains filtered or unexported fields
}

ScopeDebounce delays a hook request until events stop arriving.

A new event in the scope replaces the pending request, and the replaced one is rejected without being sent.

One value is one scope; see ScopeBlocking for sharing.

func (*ScopeDebounce) And added in v0.12.1

func (sd *ScopeDebounce) And(s Scopes) Scopes

func (*ScopeDebounce) Scopes added in v0.12.1

func (s *ScopeDebounce) Scopes(core core.Core) []Scope

type ScopeFrame

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

ScopeFrame separates ordinary hook requests in a scope from a barrier request that runs alone.

It does not satisfy Scopes; call Scope to obtain a value.

One value is one scope; see ScopeBlocking for sharing.

func (*ScopeFrame) Scope

func (d *ScopeFrame) Scope(frame bool) Scopes

Scope selects how a request takes part in this scope. With frame true the request is the barrier: it waits for the requests already running in the scope, then runs while every further request in the scope is rejected. With frame false it is an ordinary member, rejected while a barrier is pending or running.

type ScopeLatest

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

ScopeLatest accepts a hook request immediately and cancels the previous one in the same scope.

Cancellation is client-side and best-effort: a canceled request may already have reached the server and run its handler. Prefer ScopeDebounce when the request must not be sent at all.

One value is one scope; see ScopeBlocking for sharing.

func (*ScopeLatest) And added in v0.12.1

func (sl *ScopeLatest) And(s Scopes) Scopes

func (*ScopeLatest) Scopes added in v0.12.1

func (s *ScopeLatest) Scopes(core core.Core) []Scope

type ScopeRate added in v0.12.31

type ScopeRate struct {
	// Tick is the minimum interval between two requests. Required.
	Tick time.Duration
	// contains filtered or unexported fields
}

ScopeRate enforces a minimum interval between hook requests in the same scope.

Unlike ScopeDebounce, the first request is not delayed. While the interval is open only the newest pending request is kept, and the ones it replaces are rejected.

One value is one scope; see ScopeBlocking for sharing.

func (*ScopeRate) And added in v0.12.31

func (sd *ScopeRate) And(s Scopes) Scopes

func (*ScopeRate) Scopes added in v0.12.31

func (s *ScopeRate) Scopes(core core.Core) []Scope

type ScopeSerial

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

ScopeSerial queues hook requests in the same scope and runs them one at a time, in arrival order.

Unlike ScopeBlocking, a later request waits instead of being rejected. One value is one scope; see ScopeBlocking for sharing.

func (*ScopeSerial) And added in v0.12.1

func (ss *ScopeSerial) And(s Scopes) Scopes

func (*ScopeSerial) Scopes added in v0.12.1

func (ss *ScopeSerial) Scopes(core core.Core) []Scope

type Scopes added in v0.12.1

type Scopes interface {
	Scopes(core core.Core) []Scope
	Joiner[Scopes]
}

Scopes is a composable list of client-side scheduling policies for hook requests.

func JoinScopes added in v0.12.1

func JoinScopes(values ...Scopes) Scopes

JoinScopes returns one Scopes value that applies every value in order. Without arguments it returns nil.

type Selector

type Selector = front.Selector

Selector picks the elements an Indicator applies to.

Query selectors search the whole document. Target and parent selectors need an event element and select nothing without one.

func SelectorQuery

func SelectorQuery(query string) Selector

SelectorQuery selects the first element in the document matching query.

func SelectorQueryAll

func SelectorQueryAll(query string) Selector

SelectorQueryAll selects every element in the document matching query.

func SelectorQueryParent

func SelectorQueryParent(query string) Selector

SelectorQueryParent selects the closest ancestor of the event element matching query.

func SelectorTarget

func SelectorTarget() Selector

SelectorTarget selects the event element.

type SessionTracker added in v0.12.1

type SessionTracker = app.SessionTracker

SessionTracker observes session creation and removal.

id is the Doors session id, which is also the value of the Doors session cookie. Both methods run inline on the goroutine that triggers the change and must not block. With several trackers installed, they run one after another in registration order.

type Setter added in v0.15.0

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

Setter sets attributes on the elements it is attached to.

Attach it as an attribute to one or more elements, then dispatch the action returned by Setter.Set with Call. Prefer ActionEmit when the client should own the DOM change.

Setter is stateless: it changes live elements only. A rerendered element returns to its template attributes.

func (*Setter) Modify added in v0.15.0

func (s *Setter) Modify(ctx context.Context, _ string, attrs gox.Attrs) error

func (*Setter) Proxy added in v0.15.0

func (s *Setter) Proxy(cur gox.Cursor, elem gox.Elem) error

func (*Setter) Set added in v0.15.0

func (s *Setter) Set(name string, value any) ActionInto[int]

Set returns an action setting attribute name to value on attached elements; Into captures the number of live elements it reached, 0 when none is live (see ActionInto). An Emitter event counts hook requests instead.

value follows template attribute semantics: nil and false remove the attribute, true sets it bare, gox.Output values serialize themselves, anything else is formatted with the fmt package. A gox.Mutate value, such as Classes, fails the action: composing it needs the previous value, which only a rerender has.

type Source

type Source[T any] interface {
	Beam[T]

	// Route renders the first route that matches the current value and switches
	// branches as the value changes. Routes are tried in order and can be
	// nested. They receive a writable [Source].
	Route(routes ...SourceRoute[T]) gox.Elem

	// Update sets a new value and propagates it to subscribers and derived beams
	// through the underlying source. Any context is allowed.
	//
	// The returned channel is optional to use. It receives nil when propagation
	// completes, or context.Canceled when a newer update supersedes it, then
	// closes. It closes without a value when no propagation happens: the update
	// is suppressed as equal or there are no subscribers. Never wait on it
	// during rendering, in a hook, or in a subscription; to wait, use your own
	// goroutine with [DetachedContext] or [Go].
	Update(context.Context, T) <-chan error

	// Mutate computes the next value from the current value and propagates it
	// through the underlying source. The function receives a copy of the current
	// value and must return the next value. It may run more than once when a
	// concurrent update lands first, so keep it free of side effects. Any
	// context is allowed.
	//
	// The returned channel is optional to use. It receives nil when propagation
	// completes, or context.Canceled when a newer update supersedes it, then
	// closes. It closes without a value when no propagation happens: the next
	// value is suppressed as equal or there are no subscribers. Never wait on
	// it during rendering, in a hook, or in a subscription; to wait, use your
	// own goroutine with [DetachedContext] or [Go].
	Mutate(context.Context, func(T) T) <-chan error
	// contains filtered or unexported methods
}

Source is a writable reactive value.

A Source is either an original source created with NewSource or a derived source created with DeriveSource; both can be read, subscribed to, routed, and updated. For slices, maps, pointers, and mutable structs, store a replacement instead of mutating the stored value in place.

func DeriveSource added in v0.12.1

func DeriveSource[T1 any, T2 comparable](source Source[T1], get func(v T1) T2, set func(v1 T1, v2 T2) T1) Source[T2]

DeriveSource returns a writable derived source of source. It uses == to suppress equal derived values.

get extracts the derived value from the source value. set receives the current source value and the new derived value and must return the next source value.

Example:

settings := doors.NewSource(Settings{Units: "metric"})
units := doors.DeriveSource(settings,
	func(s Settings) string { return s.Units },
	func(s Settings, u string) Settings { s.Units = u; return s },
)

func DeriveSourceEqual added in v0.12.1

func DeriveSourceEqual[T1 any, T2 any](source Source[T1], get func(v T1) T2, set func(v1 T1, v2 T2) T1, equal func(old T2, new T2) bool) Source[T2]

DeriveSourceEqual returns a writable derived source of source. It calls equal to suppress equal derived values. If equal is nil, every derived value propagates.

get extracts the derived value from the source value. set receives the current source value and the new derived value and must return the next source value.

equal runs while the derived source's lock is held: it must not panic and must not call back into any source or beam.

func NewSource

func NewSource[T comparable](init T) Source[T]

NewSource returns a writable source holding init. It uses == to suppress equal updates.

Example
count := NewSource(1)
label := DeriveBeam(count, func(v int) string {
	return fmt.Sprintf("count:%d", v)
})

fmt.Println(count.Get())
_ = label
Output:
1

func NewSourceEqual

func NewSourceEqual[T any](init T, equal func(old T, new T) bool) Source[T]

NewSourceEqual returns a writable source holding init. It calls equal to suppress equal updates.

equal reports whether old and new should be treated as equal and therefore not propagated. If equal is nil, every update propagates. equal runs while the source's lock is held: it must not panic and must not call back into any source or beam.

func NewSourceEqualNoSkip added in v0.12.1

func NewSourceEqualNoSkip[T any](init T, equal func(old T, new T) bool) Source[T]

NewSourceEqualNoSkip returns a writable source holding init. It calls equal to suppress equal updates and lets in-progress propagation finish even if a newer update arrives.

equal reports whether old and new should be treated as equal and therefore not propagated. If equal is nil, every update propagates. equal runs while the source's lock is held: it must not panic and must not call back into any source or beam.

func NewSourceNoSkip added in v0.12.1

func NewSourceNoSkip[T comparable](init T) Source[T]

NewSourceNoSkip returns a writable source holding init. It uses == to suppress equal updates and lets in-progress propagation finish even if a newer update arrives.

func Router

func Router(ctx context.Context) Source[Location]

Router returns the current URL of the page instance as a writable Source.

Updating it changes the browser URL without a page reload and reroutes the current page. Updates to a location with the same path and query are suppressed.

ctx must belong to a Doors render or handler; otherwise Router panics.

func TabState added in v0.15.5

func TabState[T comparable](ctx context.Context, key string) Source[*T]

TabState returns a writable source of the value stored under key in the browser tab's state. It uses == to suppress equal updates.

The stored value is not available during the initial page render: the browser sends it only after the page has loaded, so the source reads nil until then. Content that depends on tab state should render a placeholder and let the update fill it in.

Tab state is kept by the browser tab: it survives reloads and in-app navigation, back and forward keep the latest value, other tabs do not see it, and it never appears in the URL. Every server-side update is sent back to the browser. Values are stored as JSON. Keep them small: browsers cap history state size, and the whole tab state travels on every page load and update.

Until the sync, the value is nil unless an update set it. After the sync it is never nil: a missing or undecodable key reads as the zero value. Updating with nil removes the key. A non-nil value set before the sync wins over the stored one.

ctx must belong to a Doors render or handler; otherwise TabState panics.

func TabStateEqual added in v0.15.5

func TabStateEqual[T any](ctx context.Context, key string, equal func(old T, new T) bool) Source[*T]

TabStateEqual returns a writable source of the value stored under key in the browser tab's state. It calls equal to suppress equal updates.

equal receives dereferenced values; nil and non-nil never compare equal. If equal is nil, every update propagates. equal runs while the source's lock is held: it must not panic and must not call back into any source or beam.

The stored value is not available during the initial page render: the browser sends it only after the page has loaded, so the source reads nil until then. Content that depends on tab state should render a placeholder and let the update fill it in.

Tab state is kept by the browser tab: it survives reloads and in-app navigation, back and forward keep the latest value, other tabs do not see it, and it never appears in the URL. Every server-side update is sent back to the browser. Values are stored as JSON. Keep them small: browsers cap history state size, and the whole tab state travels on every page load and update.

Until the sync, the value is nil unless an update set it. After the sync it is never nil: a missing or undecodable key reads as the zero value. Updating with nil removes the key. A non-nil value set before the sync wins over the stored one.

ctx must belong to a Doors render or handler; otherwise TabStateEqual panics.

type SourceRoute added in v0.18.0

type SourceRoute[T any] interface {
	// contains filtered or unexported methods
}

func RouteDerive added in v0.12.1

func RouteDerive[T1 any, T2 any](derive func(source Source[T1]) Source[T2], routes ...SourceRoute[T2]) SourceRoute[T1]

func RouteMatch added in v0.12.1

func RouteMatch[T any](match func(v T) bool, routes ...SourceRoute[T]) SourceRoute[T]

func RouteModel added in v0.12.3

func RouteModel[M any](routes ...SourceRoute[M]) SourceRoute[Location]

func RouteSource added in v0.12.1

func RouteSource[T any](render func(s Source[T]) gox.Elem) SourceRoute[T]

func RouteValue added in v0.12.1

func RouteValue[T any](value T, routes ...SourceRoute[T]) SourceRoute[T]

type Store

type Store = ctex.Store

Store is goroutine-safe key-value storage, returned by SessionStore and InstanceStore.

Keys must be comparable; values may be of any type. A stored nil is indistinguishable from an absent key.

func InstanceStore

func InstanceStore(ctx context.Context) Store

InstanceStore returns the Store scoped to the current instance.

Unlike SessionStore, its contents are not visible to other instances.

ctx must belong to a Doors render or handler; otherwise InstanceStore panics.

func SessionStore

func SessionStore(ctx context.Context) Store

SessionStore returns the Store shared by every instance in the current session.

ctx must carry a Doors session; otherwise SessionStore panics.

type SubmitEmit added in v0.15.0

type SubmitEmit struct{}

SubmitEmit is the event init for the synthetic submit events Emitter dispatches. The form data is read from the event target, so attach the Emitter to the form element.

type Use

type Use = func(http.Handler) http.Handler

Use is HTTP middleware for App.Use.

func UseDir added in v0.12.1

func UseDir(prefix string, dirPath string, cacheControl string) Use

UseDir serves the local directory dirPath under prefix.

prefix must be neither empty nor "/", and is normalized to have a leading and trailing slash. cacheControl is set on successful responses; empty leaves the header alone. Requests outside prefix, and requests other than GET and HEAD, go to the next handler.

func UseFS added in v0.12.1

func UseFS(prefix string, fsys fs.FS, cacheControl string) Use

UseFS serves fsys under prefix.

prefix must be neither empty nor "/", and is normalized to have a leading and trailing slash. cacheControl is set on successful responses; empty leaves the header alone. Requests outside prefix, and requests other than GET and HEAD, go to the next handler.

func UseFile added in v0.12.1

func UseFile(path string, filePath string, cacheControl string) Use

UseFile serves the local file filePath at path.

path is matched exactly, with a leading slash added if it lacks one, and must be neither empty nor "/". cacheControl is set on successful responses; empty leaves the header alone. Requests that do not match, and requests other than GET and HEAD, go to the next handler.

func UseResource added in v0.12.1

func UseResource(path string, resource ResourceStatic, contentType string) Use

UseResource serves resource as a managed resource at path.

path is matched exactly, with a leading slash added if it lacks one, and must be neither empty nor "/". contentType is sent as the Content-Type. Requests that do not match, and requests other than GET and HEAD, go to the next handler. UseResource panics on an unusable path or resource.

Responses carry the ServerCacheControl value from Conf and are gzipped unless ServerDisableGzip is set.

type Watcher added in v0.9.8

type Watcher[T any] = beam.Watcher[T]

Watcher is the value-and-cancellation callback pair passed to Beam.Watch.

type With added in v0.12.1

type With interface {
	// contains filtered or unexported methods
}

With is a NewApp option.

func WithCSP added in v0.12.1

func WithCSP(csp CSP) With

WithCSP makes Doors send a Content-Security-Policy header on page responses. Without it, no such header is sent.

func WithConf added in v0.12.1

func WithConf(conf Conf) With

WithConf sets the runtime configuration. Zero and invalid fields take their documented defaults.

func WithESProfiles added in v0.12.1

func WithESProfiles(profile func(p string) api.BuildOptions) With

WithESProfiles sets the esbuild options provider for managed scripts.

profile receives the profile name requested by the script, or an empty string when it names none. A nil provider keeps the Doors defaults.

func WithErrorPage added in v0.12.1

func WithErrorPage(ep ErrorPage) With

WithErrorPage installs the renderer for app-level errors. Without it, Doors sends a plain text 500 response.

func WithFunc added in v0.18.0

func WithFunc(f func() With) With

WithFunc calls f once per app in NewApp and applies the option it returns. Use it to create per-app values, so the same option passed to several apps does not share them. A nil f or a nil result does nothing.

func WithID added in v0.12.1

func WithID(id string) With

WithID sets the app id used in Doors-generated URLs and in the session cookie name. It must survive URL path escaping unchanged; otherwise WithID panics. Default: doors.

func WithIDCookie added in v0.13.12

func WithIDCookie(name string) With

WithIDCookie makes Doors set an extra cookie named name that carries the app id, for sticky load balancing. It is refreshed alongside the session cookie and not while draining. Empty name sets no cookie.

func WithLogger added in v0.12.15

func WithLogger(l *slog.Logger) With

WithLogger sets the logger Doors writes to. If l is nil, Doors uses slog.Default().

func WithPrinter added in v0.15.0

func WithPrinter(p func(next gox.Printer) gox.Printer) With

WithPrinter wraps the printer that serializes HTML output.

p is called once per page render and once per Door render cycle, and must return a non-nil printer. A nil p disables wrapping.

func WithSessionTracker added in v0.12.1

func WithSessionTracker(t SessionTracker) With

WithSessionTracker installs a session lifecycle observer. Repeat it to install several; they run in registration order. A nil tracker installs nothing.

func WithValue added in v0.18.0

func WithValue(key, value any) With

WithValue makes ctx.Value(key) return value in every context Doors creates: renders, handlers, session and instance contexts, and requests. A value you set for the same key inside Doors, with context.WithValue or Ctx, still wins. Repeated keys keep the last value.

Jump to

Keyboard shortcuts

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