Skip to content
Gx
GitHub

The gx package

Each exported function, type, constant and variable of package gx.

Package github.com/alternayte/gx is the whole public API of the framework. just docs-gen writes this page from the source. The text of each entry is the doc comment of the symbol.

Generated code calls some of these symbols. An app does not call a symbol whose name starts with Gx.

Functions

func Action

func Action[In any](fn func(*Ctx, In) error) *action[In]

Action registers a handler for a route type of any method. The handler answers with Patch, SetSignals, Redirect, Toast or nothing.

func AllowCredentials

func AllowCredentials(origins ...string) originsOption

AllowCredentials lists the origins that can call the routes that follow it in a Group from a different origin with the cookies of the user. It takes exact origins only: a wildcard trusts each later subdomain with the session of each user. Use it for an app of your own on a different subdomain.

func AllowOrigins

func AllowOrigins(origins ...string) originsOption

AllowOrigins lists the origins that can call the routes that follow it in a Group from a different origin. An origin is exact ("https://shop.example.com") , the subdomains of a host ("https://*.partner.io") , or AnyOrigin. A request from a listed origin carries no cookie: the server removes the Cookie header before the middleware runs. The user of such a request comes from a token.

func AppendJSONBool

func AppendJSONBool(b []byte, v bool) []byte

AppendJSONBool appends a JSON boolean.

func AppendJSONFloat

func AppendJSONFloat(b []byte, f float64) []byte

AppendJSONFloat appends a JSON number in the form encoding/json writes. JSON has no NaN and no infinity: such a value is null, and a panic in dev.

func AppendJSONFloat32

func AppendJSONFloat32(b []byte, f float32) []byte

AppendJSONFloat32 appends a float32 as a JSON number in the form encoding/json writes for a float32: the shortest text that gives the same float32. The text of the float64 value has more digits, for example 0.10000000149011612 for 0.1.

func AppendJSONInt

func AppendJSONInt(b []byte, v int64) []byte

AppendJSONInt appends a JSON number. In dev it panics for an integer outside the 53-bit safe range, because the browser rounds it.

func AppendJSONSignalRef

func AppendJSONSignalRef(b []byte, path string) []byte

AppendJSONSignalRef appends a gx.SignalRef prop of an island. The island loader turns the object into a reference that the context of the island resolves.

func AppendJSONString

func AppendJSONString(b []byte, s string) []byte

AppendJSONString appends s as a JSON string. It escapes <, > and & so the text is safe in a script, and writes an invalid UTF-8 byte as U+FFFD.

func AppendJSONTime

func AppendJSONTime(b []byte, t time.Time) []byte

AppendJSONTime appends a time as a JSON string in RFC 3339 form, which the Date constructor of JavaScript reads.

func AppendJSONUint

func AppendJSONUint(b []byte, v uint64) []byte

AppendJSONUint appends a JSON number. In dev it panics for an integer outside the 53-bit safe range, because the browser rounds it.

func BasePath

func BasePath() string

BasePath returns the configured link prefix.

func BindSignal

func BindSignal(signals map[string]any, scope, name string, dst any) error

BindSignal fills dst from the named signal inside scope, for example scope "cart.Cart" and name "qty". A signal that is not in the request leaves dst unchanged.

func CSP

func CSP(opt CSPOptions) func(http.Handler) http.Handler

CSP is middleware that sets a strict Content-Security-Policy with one fresh nonce per response. It works around a whole app, in an app.Group call and around any handler that calls gx.Render.

func CSRF

func CSRF(next http.Handler) http.Handler

CSRF protects non-GET requests with Go's cross-origin protection, plus a token for browser-shaped requests that carry no Fetch Metadata. gx.App applies it to every route. An action or a form on another router applies the cross-origin protection to itself, so no adoption level needs middleware for it. The token needs the cookie that this middleware sets, so mount it around another router to protect browsers without Fetch Metadata.

func Classes

func Classes(parts ...string) string

Classes joins the non-empty parts with single spaces, in source order. Resolve conflicts with gx.Cx.

func Collection

func Collection[Meta any](dir string) *collection[Meta]

Collection declares a content collection rooted at dir, relative to the module root.

func Cx

func Cx(parts ...string) string

Cx merges class strings with the semantics of tailwind-merge for Tailwind v4. A later class removes an earlier class of the same class group or of a group that conflicts with it. A modifier scopes the conflict. The classes that stay keep their order, and a class that Tailwind does not know stays.

func DefaultMessage

func DefaultMessage(key string) string

DefaultMessage returns the English message of a built-in rule key, or the key itself when the key has no default.

func Event

func Event[D any](name string) func(D) EventValue

Event returns a typed domain event. Call it with a detail to make the value that Ctx.Emit sends:

func ExprCall

func ExprCall(method, url, scope string) string

ExprCall returns the tree node of an action invocation.

func ExprOp

func ExprOp(op string, parts ...string) string

ExprOp returns a tree node with a name and its parts. Each part is a tree node or a path.

func ExprPath

func ExprPath(base string, key Key, name string) string

ExprPath returns the path of a signal of a component instance, for the target of a signal statement.

func ExprRef

func ExprRef(path string) string

ExprRef returns the tree node of a signal that a gx.SignalRef prop names. path is the text of the reference.

func ExprRefPath

func ExprRefPath(path string) string

ExprRefPath returns the path of a signal that a gx.SignalRef prop names. The text of a reference is a bracket path, as gx.SignalRefPath writes it.

func ExprSignal

func ExprSignal(base string, key Key, name string) string

ExprSignal returns the tree node of a signal of a component instance.

func ExprValue

func ExprValue(v any) string

ExprValue returns the tree node of a server value. The value is data in the tree, as it is in gx.JSON.

func FieldError

func FieldError[T any](field *T, key string) error

FieldError re-renders the form with key as the error of one input field. The field pointer names the field through the generated GxFieldName method.

func FieldID

func FieldID(form, path string) string

FieldID returns the element id of one form field, for example ("signup", "addresses[0].street") gives "signup-addresses-0-street".

func FieldNames

func FieldNames(errs map[string]string) []string

FieldNames returns the sorted field names of a field error map.

func Forbidden

func Forbidden() error

Forbidden tells the page to answer 403.

func Form

func Form[In any, P any](fn func(*Ctx, In) error, view func(P) Node) *form[In, P]

Form registers a form action for a route type. In is a pointer to the route input type:

func FormIndexes

func FormIndexes(r *http.Request, prefix string) []int

FormIndexes returns the sorted row indexes present for an indexed form name, for example 0 and 2 for addresses[0].street and addresses[2].city.

func FormText

func FormText(r *http.Request, name string) string

FormText returns one request form value after parsing.

func FragmentID

func FragmentID(component, name string, key Key) string

FragmentID returns the id of one fragment instance: component-scoped, and keyed when the instance has a key.

func IsDev

func IsDev() bool

IsDev reports whether the dev checks are on.

func IsIconBody

func IsIconBody(body string) bool

IsIconBody reports whether a string looks like the inner markup of an icon. The icon generator refuses anything else, so a generated icon cannot carry markup that breaks out of the svg.

func IsZero

func IsZero[T comparable](v T) bool

IsZero reports whether v is the zero value of its type. The generated encoder of an island calls it for a json omitzero option.

func JSON

func JSON(v any) string

JSON returns the JSON form of a server value inlined into a client expression. It panics when the value has no JSON form: the compiler must not inline it.

func Keep

func Keep(signals ...string) string

Keep returns the statement that gives the values of signals to the Gx runtime before an optimistic directive changes them. The runtime puts the values back when the action of the element fails. While a request of the element is in flight and the element sends no second request (a click with no .concurrent) , the statement returns: the directive changes no signal, as the action does not run.

func KeepSignal

func KeepSignal(base string, key Key, name string) string

KeepSignal returns the text that reads one signal of a component instance into an object with the shape of the signals of the page. Generated code gives it to Keep for each signal that an optimistic directive writes.

func Layout

func Layout[P any](load func(*Ctx) (P, error), view func(P, Node) Node) layout[P]

Layout builds a layout from an optional loader and a view that takes the loaded props and the page node. Pass a nil load when the layout needs no data.

func Nav

func Nav(mode Navigation, opts ...navSetting) navOption

Nav sets the navigation mode of the routes that follow it in a Group. KeepFocus and Prefetch are options of MorphNavigation, for example gx.Nav(gx.MorphNavigation, gx.KeepFocus, gx.Prefetch(gx.PrefetchHover)). Nav panics when it gets an option with FullNavigation.

func Nonce

func Nonce(r *http.Request) string

Nonce returns the CSP nonce of the request, or "" when no policy set one. A page author needs it only for a script inside trusted raw HTML.

func NotFound

func NotFound() error

NotFound tells the page to answer 404.

func Once

func Once[T any](c *Ctx, fn func() (T, error)) (T, error)

Once runs fn once per request and returns its value. It keys on the call site, so share one call site or extract a helper.

func Page

func Page[In any, P any](load func(*Ctx, In) (P, error), view func(P) Node) *page[In, P]

Page builds a typed page from a loader and a view. The route input type In carries the pattern and the generated Bind method.

func Params

func Params(fn ParamsFunc) func(http.Handler) http.Handler

Params returns middleware that installs a path variable reader for routers that do not fill r.PathValue.

func ParseBool

func ParseBool(s string) (bool, error)

ParseBool parses an HTML form boolean. "on" is the value of a checked checkbox without a value attribute.

func PathValue

func PathValue(r *http.Request, name string) string

PathValue reads a path variable through the Params reader, or through r.PathValue when no reader is set.

func Prefetch

func Prefetch(mode PrefetchMode) navSetting

Prefetch is an option of Nav. It sets when the links of the pages load their page before the click. The runtime keeps each answer for 10 s, and a write request clears the answers that it keeps.

func Redirect

func Redirect[In interface{ URL() string }](to In) error

Redirect tells the page to answer 303 with a Location.

func RefPath

func RefPath[T any](r SignalRef[T]) string

RefPath returns the adapter reference of a signal ref, with the leading $, so a child can share a parent signal.

func Render

func Render(w http.ResponseWriter, r *http.Request, n Node) error

Render renders n inside any http.Handler. It sets the content type, marks active links for r and writes the merged head.

func RenderNode

func RenderNode(w io.Writer, n Node) error

RenderNode writes n to a writer with no request in scope.

func RenderRequest

func RenderRequest(w io.Writer, r *http.Request, n Node) error

RenderRequest renders n with the request in scope, so typed links mark the active page. The rendered markers feed the runtime script decision of the app.

func RoomToken

func RoomToken(base string, room Room) string

RoomToken returns the token that the page carries for the room of one component: the key, the time of its expiry and a signature of the server over the component, the key and that time. The token of one component is not valid at the routes of a different component. Generated code calls it with the signal namespace of the component. A room that RoomKey did not make gives an empty token, and the page joins no room.

func RoomURL

func RoomURL(base string) string

RoomURL returns the address of the shared signals of a component, for the runtime. Generated code writes it into the root of the component.

func Scope

func Scope(r *http.Request) string

Scope returns the signal scope of the invoking component instance, or "".

func ScopeString

func ScopeString(base string, key Key) string

ScopeString returns the signal namespace of a component instance: the component path plus its key.

func SetAdapter

func SetAdapter(a Adapter)

SetAdapter sets the adapter of the process. New does this from Config.Adapter. Actions mounted outside a gx.App use the default.

func SetBasePath

func SetBasePath(path string)

SetBasePath sets the prefix of generated links.

func SetDev

func SetDev(on bool)

SetDev turns the dev checks on or off. gx dev sets it.

func SetFrontmatterDecoder

func SetFrontmatterDecoder(fn func([]byte, any) error)

SetFrontmatterDecoder installs the frontmatter decoder of the process. The gx/content package installs one.

func SetGallery

func SetGallery(fixtures []Fixture)

SetGallery installs the fixture list of the dev gallery. The generated gxdev_gallery package supplies it; the scaffold's main calls this with gxdev.

func SetIslands

func SetIslands(b IslandBundle)

SetIslands installs the island bundle of the app.

func SetRouteStylesheets

func SetRouteStylesheets(sheets map[string][]byte)

SetRouteStylesheets installs the stylesheet of each page route, by the pattern of the route. A generated app gives it gxstyles.Routes(). A page of such a route links its own stylesheet, which holds only the classes that the page can use; each other page links the stylesheet of the app. Two routes with the same content share one file.

func SetSecret

func SetSecret(secret []byte)

SetSecret sets the secret that signs the room keys. gx.New calls it for Config.Secret.

func SetStylesheet

func SetStylesheet(css []byte)

SetStylesheet installs the app stylesheet.

func SetTranslator

func SetTranslator(t Translator)

SetTranslator sets the message translator of the process.

func SetWidgetStylesheets

func SetWidgetStylesheets(sheets map[string][]byte)

SetWidgetStylesheets installs the stylesheet of each widget, by the tag of the widget. The main of an app calls it with gxstyles.Widgets(). The stylesheet of a widget holds only the classes that the widget uses, and lives in the shadow root of the element.

func ShareEffect

func ShareEffect(base string, key Key, names ...string) string

ShareEffect returns the effect of the root of a component with shared signals: it gives the runtime the value of each shared signal, at the start and after each change. The runtime writes a changed value to the room. Generated code calls it.

func SignalJSON

func SignalJSON(base string, key Key, values map[string]any) string

SignalJSON renders the data-signals JSON of one component instance from the initial values of its signals.

func SignalName

func SignalName(base string, key Key, name string) string

SignalName returns the dotted name of one signal, as data-bind takes it, for example cart.Cart.42.qty.

func SignalPath

func SignalPath(base string, key Key, name string) string

SignalPath returns the adapter signal reference of one signal in one component instance, for example $["cart"]["Cart"]["42"]["qty"].

func SignalRefPath

func SignalRefPath(base string, key Key, name string) string

SignalRefPath returns the bracket path of one signal, without the leading $, for example ["cart"]["Cart"]["42"]["qty"].

func Signals

func Signals(r *http.Request) (map[string]any, error)

Signals decodes the request signals through the app adapter. It returns nil when no adapter is set. The signals of a widget request come in the wire form of a widget.

func SortedKeys

func SortedKeys[K ~string, V any](m map[K]V) []K

SortedKeys returns the keys of a map in order, so that the props of an island render the same bytes each time.

func StaticInputs

func StaticInputs(h Handler) ([]any, bool, error)

StaticInputs reports the export inputs of a route, when it lists any.

func String

func String(n Node) string

String returns the HTML of n with no request in scope.

func StringRequest

func StringRequest(r *http.Request, n Node) string

StringRequest returns the HTML of n with the request in scope.

func Stylesheet

func Stylesheet() []byte

Stylesheet returns the installed stylesheet, or nil.

func TextValue

func TextValue(v any) string

TextValue returns the text form of a renderable value.

func ToolResult

func ToolResult(c *Ctx, v any)

ToolResult sets the structured output of the tool call that runs the action. An agent gets v as JSON. With no ToolResult the agent gets a summary of the patches of the action. For a request of a browser it does nothing.

func TopicToken

func TopicToken(topic Topic) string

TopicToken returns the token that the page carries for a topic: the key, the time of its expiry and a signature of the server over the key and that time. The token does not name a component: each listener of the key on a page carries the same token, and App.Publish of the key reaches each one. Generated code calls it for on:topic. A topic that TopicKey did not make gives an empty token, and the page listens to nothing.

func Transition

func Transition[K any](name string) func(K) TransitionName

Transition returns a typed transition. Call it with a key to pair one element across two pages:

func Translate

func Translate(key, fallback string) string

Translate returns the message of key. Without a translator it returns fallback, the English default.

func ValidateURL

func ValidateURL(action, field string) string

ValidateURL returns the live validation URL of one field.

func ViolationKey

func ViolationKey(err error) string

ViolationKey returns the message key of a field violation, or "invalid".

func When

func When(name string, on bool) string

When returns name when on is true, and the empty string otherwise.

func Widget

func Widget[In any, P any](load func(*Ctx, In) (P, error), view func(P) Node) *widget[In, P]

Widget builds a widget from a loader and a view. A widget is a component that a page of a different site uses as a custom element. This server renders it.

func WithNonce

func WithNonce(r *http.Request, nonce string) *http.Request

WithNonce returns r with the CSP nonce of the response in scope. Every script element Gx renders for r then carries it. gx.CSP calls it; an app with its own policy middleware calls it with its own nonce.

Types

type Adapter

type Adapter interface {
    // Name identifies the adapter, for example "datastar".
    Name() string
    // Signals reports whether the adapter supports client signals and
    // client expressions (REQ-ACT-09).
    Signals() bool
    // Runtime returns the script nodes every page needs (request
    // lifecycle step 6), or nil.
    Runtime() Node
    // Assets returns static files keyed by their name below /_gx/.
    Assets() map[string][]byte
    // Respond writes the commands of an action or a navigation.
    Respond(w http.ResponseWriter, r *http.Request, res *Response) error
    // ReadSignals decodes the request signals into dst, a pointer.
    ReadSignals(r *http.Request, dst any) error
    // Invoke returns the attribute that makes an element invoke the
    // action at url with the HTTP method on its click (REQ-ACT-02). A
    // non-empty scope names the invoking component instance
    // (REQ-ACT-03). It returns the zero Attr for a method the client
    // cannot invoke.
    Invoke(method, url, scope string) Attr
    // On returns the attributes that make an element invoke an action
    // on an event, with the event modifiers (REQ-ACT-08). It returns
    // nil for an invocation that the adapter cannot express.
    On(inv Invocation) []Attr
}

Adapter is the public hook between Gx and one hypermedia library. One adapter serves one app (P2) .

func AdapterOf

func AdapterOf(r *http.Request) Adapter

AdapterOf returns the adapter of the request, or the process default.

type App

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

App is an http.Handler that owns a ServeMux.

func New

func New(cfg Config) *App

New returns an empty app.

func (App) CallTool

func (a *App) CallTool(ctx context.Context, header http.Header, name string, args json.RawMessage) ToolAnswer

CallTool runs the tool with the given name for an agent. args is the JSON object of the arguments. header holds the headers of the request of the agent: the request of the action gets them, so the middleware of the group of the action sees the caller as it sees a user. The caller of CallTool makes the cross-origin check of the request of the agent; a handler that the app mounts has it.

func (App) CallToolFor

func (a *App) CallToolFor(caller *http.Request, name string, args json.RawMessage) ToolAnswer

CallToolFor runs a tool as CallTool does, for the request of an agent that the caller has in hand. The request of the action then has the host, the client address and the TLS state of that request too. A middleware that reads them sees the caller.

func (App) Errors

func (a *App) Errors(notFound, forbidden, serverError func(*Ctx) Node) *App

Errors sets the error components per status.

func (App) Group

func (a *App) Group(prefix string, parts ...any) *App

Group mounts routes under a prefix. Middleware applies to the routes that follow it in the same call. gx.Nav selects the navigation mode of the routes that follow it. gx.AllowOrigins and gx.AllowCredentials list the origins that can call the routes that follow them from a different origin.

func (App) Publish

func (a *App) Publish(ctx context.Context, key string) error

Publish tells each open page that listens to the topic key to run the action of its on:topic directive. It goes through the bus of the app, so a page that a different replica serves gets it too. Code in any goroutine can call it, with no request. The message carries no data: each page asks for the new state with the session of its viewer, and a page that is not connected does not get it.

func (App) ServeHTTP

func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves the app with cross-origin protection. A page response is buffered so the adapter runtime can join it; action responses stream through (request lifecycle step 6 and 7) .

func (App) Tools

func (a *App) Tools() []ToolInfo

Tools returns the description of each tool of the app, by name. A tool is a mounted action or form with Tool; no other route is a tool.

type Attr

type Attr struct {
    Key    string
    Value  string
    Kind   AttrKind
    Active string
}

Attr is one attribute of an element. Active marks a typed link for the aria-current and data-active rules of REQ-RTE-13: "page" (exact match) or "section" (path prefix) .

func Bool

func Bool(key string, present bool) Attr

Bool returns a boolean attribute that is omitted when present is false.

func Client

func Client(key, value, tree string) Attr

Client returns a client attribute. key and value are the attribute of the adapter. tree is the same expression as data, for a widget. Generated code calls it.

func ElementModule

func ElementModule(module string) Attr

ElementModule returns the attribute that names the entry file of an imported web component. module is the import specifier of gx.lock. The generated code of a web component tag calls it. The render puts the URL of the entry file in the attribute.

func Invoke

func Invoke(method, url, scope string) Attr

Invoke returns the attribute that invokes the action at url with the HTTP method. A non-empty scope names the invoking component instance. Generated code puts the Value in the attribute of an on: handler. The adapter of the request, or the process default, writes the attribute when the node renders.

func On

func On(spec, method, url, scope string) Attr

On returns the attribute that invokes an action on an event. Generated code calls it for an on: handler that is one route literal. spec is the text after "on:", for example "click.debounce(300ms)". The adapter of the request, or the process default, writes its own attributes when the node renders.

type AttrKind

type AttrKind uint8

AttrKind selects the escaping rule of an attribute value.

const (
    // AttrText is a plain attribute value.
    AttrText AttrKind = iota
    // AttrURL is a URL attribute value.
    AttrURL
    // AttrBool is a boolean attribute: present when Value is "true".
    AttrBool
    // AttrStyle is a style attribute value.
    AttrStyle
)

type Attrs

type Attrs []Attr

Attrs is an ordered attribute list.

func FieldControlAttrs

func FieldControlAttrs(f FieldView, describedBy ...string) Attrs

FieldControlAttrs returns the control attributes of one field with extra aria-describedby ids, for example a hint element.

func JoinAttrs

func JoinAttrs(parts ...Attrs) Attrs

JoinAttrs concatenates attribute lists in order.

func ToastAttrs

func ToastAttrs(p ToastPatch) Attrs

ToastAttrs returns the attributes the root element of a toast carries: the contract between the markup and the behaviour runtime. A component that renders a toast spreads them on its root element.

type BindError

type BindError struct {
    Err error
}

BindError marks a request whose input did not bind; the page answers 400.

func (BindError) Error

func (e *BindError) Error() string

func (BindError) Unwrap

func (e *BindError) Unwrap() error

type Binder

type Binder interface {
    Pattern() string
    Bind(*http.Request) error
}

Binder is the generated route interface: a pattern and request binding. The gx generator writes Pattern and Bind.

type Builder

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

Builder collects nodes while a generated component runs.

func (Builder) Add

func (b *Builder) Add(n ...Node)

Add appends nodes to the builder.

func (Builder) Node

func (b *Builder) Node() Node

Node returns the built node.

type Bus

type Bus interface {
    Publish(ctx context.Context, topic string, message []byte) error
    Subscribe(ctx context.Context, topic string, receive func(message []byte)) (cancel func(), err error)
}

Bus carries the values of shared signals and the messages of App.Publish between the replicas of an app. Publish gives a message to each subscriber of the topic, on each replica. Subscribe calls receive for each message of the topic until the caller calls cancel.

func NewMemoryBus

func NewMemoryBus() Bus

NewMemoryBus returns a bus that lives in this process. Two replicas of an app do not see the messages of each other through it.

type CSPOptions

type CSPOptions struct {
    // UnsafeEval adds 'unsafe-eval' to script-src. The Datastar adapter
    // needs it: Datastar evaluates client expressions at runtime.
    UnsafeEval bool
    // Directives holds more directives, for example
    // "img-src 'self' data:; frame-ancestors 'none'".
    Directives string
}

CSPOptions configure gx.CSP.

type Code

type Code struct {
    // File is the module-relative path of the source file.
    File string
    // Lang is the chroma lexer name; empty guesses from File.
    Lang string
    // Source is the selected source text with a trailing newline.
    Source string
}

Code is one code block of the docs kit. The compiler fills it from gx.CodeFile at build time and fails the build when the file or a selected line is missing.

func CodeFile

func CodeFile(path, lines string) Code

CodeFile names a repository file for a code block. The compiler replaces the call with the resolved gx.Code value. The values here keep a generated file type-checking and make the intent explicit.

type Config

type Config struct {
    BasePath string
    Adapter  Adapter
    // Toast renders one toast (REQ-REG-11). An app sets it to the Render
    // function of its installed toast item, so the toast markup and its
    // classes stay in app-owned source. Without it a toast is the plain
    // ToastNode.
    Toast func(ToastPatch) Node
    // Public holds the app's own static files, for example an embedded
    // public directory. A GET for a path that names a file in it answers
    // that file before any route, so the binary needs no file beside it
    // (NFR-08).
    Public fs.FS
    // Bus carries the values of shared signals and the messages of
    // App.Publish between the replicas of the app (REQ-ACT-22). With no
    // bus, the in-memory bus of Gx carries them inside one process.
    Bus Bus
    // Secret signs the room keys of shared signals and the topic keys
    // (SI-17). Each replica of the app needs the same secret. With no
    // secret, the process makes its own.
    Secret []byte
    // DisableCompression turns off the brotli and gzip compression of the
    // answers, for an app behind a proxy that compresses (REQ-RTE-21).
    DisableCompression bool
}

Config holds app options. BasePath prefixes every generated link, and Adapter selects the hypermedia library. Package gx exports only the standard library plus an optional adapter runtime dependency.

type ContentError

type ContentError struct {
    File string
    Msg  string
}

ContentError is a frontmatter or rule error of one content file.

func (ContentError) Error

func (e *ContentError) Error() string

type ContentPage

type ContentPage struct {
    Slug string `path:"slug"`
    // contains filtered or unexported fields
}

ContentPage is the export input of one content page.

func (ContentPage) URL

func (p ContentPage) URL() string

URL implements the typed link value of a content page. The index entry is the root of the collection.

type ContentRoute

type ContentRoute[Meta any] struct {
    // contains filtered or unexported fields
}

ContentRoute serves one content collection and carries the configuration of the llms.txt export.

func ContentEntries

func ContentEntries[Meta any](c *collection[Meta], view func(Entry[Meta]) Node) *ContentRoute[Meta]

ContentEntries makes one route per entry and passes the whole Entry to view. The docs shell needs the slug to build links, the table of contents and the previous and next pages.

func ContentPages

func ContentPages[Meta any](c *collection[Meta], view func(Meta, []byte) Node) *ContentRoute[Meta]

ContentPages makes the content route of the collection: one URL per entry under "/{slug...}". view builds the page from the typed frontmatter and the raw Markdown body; the docs kit renders the body.

func (ContentRoute[Meta]) LLMS

func (h *ContentRoute[Meta]) LLMS(opt LLMSOptions[Meta]) *ContentRoute[Meta]

LLMS configures the llms.txt files of this collection.

func (ContentRoute[Meta]) Pattern

func (h *ContentRoute[Meta]) Pattern() string

Pattern implements Handler. The trailing wildcard serves a nested entry slug ("guides/routing") as one path.

func (ContentRoute[Meta]) ServeHTTP

func (h *ContentRoute[Meta]) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP renders the entry named by the path value. The empty slug is the collection index.

type Ctx

type Ctx struct {
    W http.ResponseWriter
    R *http.Request
    // contains filtered or unexported fields
}

Ctx is the per-request context.

func (Ctx) Emit

func (c *Ctx) Emit(e EventValue)

Emit sends a domain event with the answer of an action or a form. The server knows that a change is real. An event is thus a call of the server and not of the template.

func (Ctx) Patch

func (c *Ctx) Patch(nodes ...Node) error

Patch sends fragment patches by id. The default mode is morph.

func (Ctx) Redirect

func (c *Ctx) Redirect(to interface{ URL() string }) error

Redirect answers with a client navigation to a route value.

func (Ctx) SetSignals

func (c *Ctx) SetSignals(v any) error

SetSignals updates the signals of the invoking component instance.

func (Ctx) Toast

func (c *Ctx) Toast(text string, opts ...ToastOption) error

Toast adds a toast to the toaster region. A kind is an option: c.Toast("Saved", gx.ToastSuccess).

func (Ctx) Update

func (c *Ctx) Update(n Node) error

Update sends the fragments of the node that differ from the fragments of the browser. n is the node of the invoking component from new props. The request holds the hash of each fragment that the browser has; the server keeps no render state for a viewer. A node with no fragment goes as its root elements, as c.Patch sends it.

type ElementPatch

type ElementPatch struct {
    Mode       PatchMode
    Target     string
    Node       Node
    Transition bool
}

ElementPatch changes one element, named by Target, a CSS selector.

type EmailMessage

type EmailMessage struct {
    HTML string
    Text string
}

EmailMessage is one rendered email: the HTML document and the same content as plain text. Give the two parts to the mail library of the app; Gx sends no email.

func RenderEmail

func RenderEmail(n Node, opt EmailOptions) (EmailMessage, error)

RenderEmail renders n as an email. The HTML is a full document: a node with no html element gets the document around it. A site path in a link or an image becomes an absolute URL from the base URL. A var() of a style becomes the value of its token.

type EmailOptions

type EmailOptions struct {
    // BaseURL is the address of the site, for example
    // "https://shop.example". Each link and each image address that is a
    // site path gets it, because an email has no site of its own.
    BaseURL string
    // Tokens are the theme tokens as values, by the name of the custom
    // property: "--primary" to "#171717". The generated functions
    // gxstyles.LightTokens and gxstyles.DarkTokens return them. A style
    // that reads a token with var() gets the value.
    Tokens map[string]string
    // Lang is the language of the document. Empty means "en".
    Lang string
    // Title is the title of the document.
    Title string
}

EmailOptions are the options of RenderEmail.

type Entry

type Entry[Meta any] struct {
    // Slug is the path below the collection directory without ".md".
    Slug string
    // File is the absolute path of the file.
    File string
    // Meta is the decoded frontmatter.
    Meta Meta
    // Body is the Markdown without the frontmatter.
    Body []byte
}

Entry is one loaded content page.

type Enum

type Enum[T comparable] map[T]string

Enum[T] is a class map for the constants of T. The analyzer requires an entry for every constant of T.

type EventPatch

type EventPatch struct {
    Name   string
    Detail any
    // Scope names the component instance that invoked the action.
    Scope string
}

EventPatch is a domain event in the answer of an action. An adapter dispatches it in the browser as a CustomEvent.

type EventValue

type EventValue struct {
    Name   string
    Detail any
}

EventValue is one domain event with its detail, ready for Ctx.Emit.

type FieldView

type FieldView interface {
    Attrs() Attrs
    FieldName() string
    FieldID() string
    FieldValue() string
    FieldError() string
    FieldErrorKey() string
    FieldValidateURL() string
    // FieldInputType returns the rule-derived input type ("email", "url"),
    // or fallback (REQ-FRM-04).
    FieldInputType(fallback string) string
    // FieldHint returns the helper text, or "".
    FieldHint() string
}

FieldView is the non-generic view of a field, for field components that serve every field type.

type FieldViolation

type FieldViolation struct {
    Field   string
    Key     string
    Message string
}

FieldViolation is one failed field rule.

func RunAllRulesContext

func RunAllRulesContext(ctx context.Context, v any) []*FieldViolation

RunAllRulesContext runs every field rule and returns one failure per failing field, in rule order. The form handler shows the whole error list.

func RunRules

func RunRules(v any) *FieldViolation

RunRules runs the Rules of an input value and returns the first failure.

func RunRulesContext

func RunRulesContext(ctx context.Context, v any) *FieldViolation

RunRulesContext is RunRules with a request context for CheckCtx.

func (FieldViolation) Error

func (e *FieldViolation) Error() string

type File

type File struct {
    // Name is the client file name.
    Name string
    // Size is the number of bytes stored.
    Size int64
    // Type is the content type, for example "image/png".
    Type string
    // Temp is the path of the temp file.
    Temp string
}

File is one uploaded file. The upload streams to a temp file during binding; the framework removes it after the handler returns.

func ReadUploads

func ReadUploads(r *http.Request, name string, maxSize int64, patterns []string) ([]File, error)

ReadUploads streams every part of one form name to a temp file and enforces the size and type limits before the handler runs.

func (File) Open

func (f File) Open() (io.ReadCloser, error)

Open opens the uploaded file for reading.

func (File) Remove

func (f File) Remove() error

Remove deletes the temp file.

type Fixture

type Fixture struct {
    Component string
    // Package is the import path of the component, for the dev gallery.
    Package string
    Name    string
    Node    func() Node
    Missing bool
}

Fixture is one gallery entry. A component without a fixtures file has Missing set and no Node.

func Gallery() []Fixture

Gallery returns a copy of the installed fixture list.

type Fixtures

type Fixtures[Props any] map[string]Props

Fixtures names example prop sets for the dev gallery. A file <Name>.fixtures.go declares one:

type FormField

type FormField[T any] struct {
    // Name is the form field name, for example "email".
    Name string
    // ID is the control id, for example "signup-email".
    ID string
    // Value is the bound value.
    Value T
    // Error is the translated error message, or "".
    Error string
    // ErrorKey is the stable message key of Error, for example "required".
    ErrorKey string
    // Constraints holds the native constraints of the rules
    // (REQ-FRM-04).
    Constraints Attrs
    // ValidateURL is the URL of the live validation action (REQ-FRM-06).
    ValidateURL string
    // Hint is the helper text of the control, or "".
    Hint string
}

Field is one generated form control. The compiler writes the static parts; the form handler writes Error and ErrorKey.

func (FormField[T]) Attrs

func (f FormField[T]) Attrs() Attrs

Attrs returns the control attributes: name, id, value, native constraints and the aria state.

func (FormField[T]) FieldError

func (f FormField[T]) FieldError() string

FieldError implements FieldView.

func (FormField[T]) FieldErrorKey

func (f FormField[T]) FieldErrorKey() string

FieldErrorKey implements FieldView.

func (FormField[T]) FieldHint

func (f FormField[T]) FieldHint() string

FieldHint implements FieldView.

func (FormField[T]) FieldID

func (f FormField[T]) FieldID() string

FieldID implements FieldView.

func (FormField[T]) FieldInputType

func (f FormField[T]) FieldInputType(fallback string) string

FieldInputType implements FieldView.

func (FormField[T]) FieldName

func (f FormField[T]) FieldName() string

FieldName implements FieldView.

func (FormField[T]) FieldValidateURL

func (f FormField[T]) FieldValidateURL() string

FieldValidateURL implements FieldView.

func (FormField[T]) FieldValue

func (f FormField[T]) FieldValue() string

FieldValue implements FieldView.

type FormInput

type FormInput interface {
    Pattern() string
    // GxNewForm returns a fresh input value.
    GxNewForm() FormInput
    GxBindForm(*http.Request) (map[string]string, error)
    Rules() Rules
    GxFormValue(map[string]string) FormValue
    GxFieldName(any) string
    // GxRunForm calls the user handler with the concrete input type.
    GxRunForm(*Ctx, any) error
}

FormInput is the generated interface of a form input type.

type FormMeta

type FormMeta struct {
    // Name is the input type in lower-first form, for example "signup".
    Name string
    // ID is the id of the form element, for example "signup-form". A form
    // with a key has the key in its id: "revokeSession-form-<key>".
    ID string
    // Key is the value of the key field of the route type, the field with
    // the tag gx:"key". It is "" for a route type with no key field, and
    // for a key field with an empty value. The key is in the id of the
    // form and of each field, so two forms of one route type on one page
    // have different ids.
    Key string
    // KeyField is the form name of the key field, or "". Live validation
    // sends the value of that field, so the patch finds the field of the
    // same form (REQ-FRM-06).
    KeyField string
    // Action is the form action URL, from the route pattern.
    Action string
    // Method is the HTTP method, for example "POST".
    Method string
    // Enctype is the form encoding when the form holds files
    // (REQ-FRM-09).
    Enctype string
    // Tool is the name of the tool of the form, or "" for a form with no
    // Tool (REQ-AI-06).
    Tool string
}

FormMeta is the generated form element state of an input type. The compiler embeds it in every <Type>Form value.

func (FormMeta) Attrs

func (m FormMeta) Attrs() Attrs

Attrs returns the attributes of the form element. The client runtime submits every form marked with data-gx-form through the adapter.

func (FormMeta) GxFieldPrefix

func (m FormMeta) GxFieldPrefix() string

GxFieldPrefix returns the first part of the id of each field: the name, or the name and the key for a form with a key.

func (FormMeta) GxFormAction

func (m FormMeta) GxFormAction() string

GxFormAction implements FormValue.

func (FormMeta) GxFormID

func (m FormMeta) GxFormID() string

GxFormID implements FormValue.

func (FormMeta) GxFormMethod

func (m FormMeta) GxFormMethod() string

GxFormMethod implements FormValue.

func (FormMeta) GxFormName

func (m FormMeta) GxFormName() string

GxFormName implements FormValue.

func (FormMeta) GxKeyFormID

func (m FormMeta) GxKeyFormID() string

GxKeyFormID returns the id of the form element: the name and "-form", and the key for a form with a key. Generated code sets ID from it.

type FormProps

type FormProps interface {
    GxSetForm(FormValue)
}

FormProps is implemented by a generated view props struct that holds a form value. The generated GxSetForm fills that field.

type FormValue

type FormValue interface {
    GxFormName() string
    GxFormID() string
    GxFormAction() string
    GxFormMethod() string
}

FormValue is implemented by every generated <Type>Form.

type Handler

type Handler interface {
    http.Handler
    Pattern() string
}

Handler is one typed route: a pattern plus an http.Handler.

func Collect

func Collect(hs ...Handler) []Handler

Collect returns its arguments as one route list.

func SharedSignals

func SharedSignals[S any](base string, names ...string) []Handler

SharedSignals returns the two routes of the shared signals of a component: the stream that a viewer of a room reads, and the write of a value. S is the generated Signals struct of the component, base is the signal namespace of the component, and names are its shared signals. Generated code makes the value; the app mounts it in a group, so each request passes the middleware of that group.

type HeadProps

type HeadProps struct {
    Title string `json:"title,omitempty"`
    Meta  []Meta `json:"meta,omitempty"`
    Links []Link `json:"links,omitempty"`
    // Lang, HtmlClass and BodyClass set attributes of the document shell.
    // The deepest value wins; Lang defaults to "en".
    Lang      string `json:"lang,omitempty"`
    HtmlClass string `json:"htmlClass,omitempty"`
    BodyClass string `json:"bodyClass,omitempty"`
}

HeadProps is the props of the gx.Head component.

func HeadOf

func HeadOf(n Node) HeadProps

HeadOf returns the merged head of a node tree.

type IconProps

type IconProps struct {
    // Label sets role="img" and aria-label. Without it the icon is
    // decorative: aria-hidden="true".
    Label string
    // Class is the class attribute of the svg.
    Class string
    // Attrs adds extra attributes.
    Attrs Attrs
}

IconProps are the props of a generated icon component.

type Invocation

type Invocation struct {
    // Method is the HTTP method and URL is the address of the action.
    Method string
    URL    string
    // Scope names the invoking component instance, or is empty
    // (REQ-ACT-03).
    Scope string
    // Event is the name of a DOM event, or "load", "visible",
    // "interval" or "topic". The element of a topic event carries the
    // token of its topic; the runtime dispatches the DOM event gx-topic on
    // it when the topic changes (REQ-ACT-22).
    Event string
    // Every is the period of an interval event, for example "5s".
    Every string
    // Mods are the event modifiers in source order.
    Mods []Modifier
    // Optimistic is true when the element changes signals before the
    // request (REQ-ACT-18). The runtime puts the signals back at the
    // first failure, so the adapter must not send the request again.
    Optimistic bool
    // Concurrent is true for the modifier .concurrent: the element can
    // send a request while its earlier request is in flight.
    Concurrent bool
    // Hidden is true for the modifier .background of an interval event.
    // With it, the element runs each tick, as Datastar and htmx do. With
    // no such modifier, the invocation is Polled (REQ-ACT-11).
    Hidden bool
}

Invocation is one client call of an action on an event.

func (Invocation) Background

func (inv Invocation) Background() bool

Background reports whether no user makes the event of the invocation: load, visible, interval and topic. The element of such an event gets no pending mark and no guard. The element of every other event gets aria-busy while its request is in flight.

func (Invocation) Guarded

func (inv Invocation) Guarded() bool

Guarded reports whether the element of the invocation sends no second request while its request is in flight: the event is click, dblclick or submit, and the invocation is not Concurrent. The request of each other user event goes, and the newest answer wins.

func (Invocation) Polled

func (inv Invocation) Polled() bool

Polled reports whether the element of the invocation is a poll that the runtime holds: an interval event with no .background modifier. A tick does not run while the page is hidden. A tick does not run while the request of the last tick is open. The element runs one time when the page shows again.

type IslandBundle

type IslandBundle struct {
    // Entries maps the name of an island to its file.
    Entries map[string]string
    // Files maps a file name to its content. Each name holds the hash of
    // the content.
    Files map[string]string
}

IslandBundle is the built JavaScript of the islands of an app. gx build writes it into the generated package gxislands, and the app's main installs it with gx.SetIslands(gxislands.Bundle()).

type IslandOption

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

IslandOption sets how the browser loads an island.

func IslandKey

func IslandKey(key Key) IslandOption

IslandKey gives one island of a list its identity. The element gets an id from the key. A morph then pairs the island with its own row, and the state of the island follows the row.

func IslandLoad

func IslandLoad(strategy string) IslandOption

IslandLoad names the time the browser loads the island file: "eager" at once, "idle" when the browser is idle, "visible" when the element comes near the viewport. With no option the island loads when it is visible.

func IslandMedia

func IslandMedia(query string) IslandOption

IslandMedia loads the island when the media query matches, for example "(min-width: 768px)".

type Key

type Key string

Key identifies one component instance.

func ChildKey

func ChildKey(parent Key, index int) Key

ChildKey returns the key of an unkeyed call site under parent. The same call site gives the same key on every render.

func InstanceKey

func InstanceKey(v any) Key

InstanceKey returns the key of a component call site from its key expression.

func ScopeKey

func ScopeKey(scope, base string) Key

ScopeKey returns the instance key inside a scope for a component base, for example "42" for base "cart.Cart" and scope "cart.Cart.42". It returns "" when the scope is not that component.

type LLMSEntry

type LLMSEntry struct {
    Path        string `json:"path"`
    Title       string `json:"title"`
    Description string `json:"description"`
    Body        string `json:"body"`
    Skip        bool   `json:"skip"`
}

LLMSEntry is one page of the llms.txt export.

type LLMSManifest

type LLMSManifest struct {
    Site    string      `json:"site"`
    Summary string      `json:"summary"`
    Entries []LLMSEntry `json:"entries"`
}

LLMSManifest is the llms.txt data of one content route. The dev-only export manifest carries it to the exporter.

type LLMSOptions

type LLMSOptions[Meta any] struct {
    // Site is the H1 of llms.txt.
    Site string
    // Summary is the blockquote line of llms.txt.
    Summary string
    // Title returns the entry title.
    Title func(Meta) string
    // Description returns the entry description.
    Description func(Meta) string
    // Skip keeps the entry out of the llms files when it returns true.
    Skip func(Meta) bool
}

LLMSOptions configure the llms.txt export of one content route.

type Link struct {
    Rel  string `json:"rel,omitempty"`
    Href string `json:"href,omitempty"`
    // As is the kind of file of a preload, for example "font".
    As string `json:"as,omitempty"`
    // Type is the media type of the file, for example "font/woff2".
    Type string `json:"type,omitempty"`
    // CrossOrigin is the crossorigin attribute: "anonymous" or
    // "use-credentials". A font preload needs it.
    CrossOrigin string `json:"crossOrigin,omitempty"`
}

Link is one link tag in the head. Two links merge when they have the same Rel and Href; a canonical or a manifest link merges by its Rel, as a page has one of each. A font preload has the Rel "preload", the As "font", the Type of the font file and the CrossOrigin "anonymous".

type Meta

type Meta struct {
    Name     string `json:"name,omitempty"`
    Property string `json:"property,omitempty"`
    Content  string `json:"content,omitempty"`
}

Meta is one meta tag in the head.

type Modifier

type Modifier struct {
    Name  string
    Value string
}

Modifier is one event modifier of an Invocation. Value is the text in its parentheses, for example "300ms" for debounce(300ms).

func ParseOn

func ParseOn(spec string) (event, every string, mods []Modifier)

ParseOn splits the text after "on:" into an event, the period of an interval event and the modifiers. A dot inside parentheses does not start a modifier.

type Navigation

type Navigation uint8

Navigation selects how a link between two pages with a shared layout loads.

const (
    // FullNavigation loads every link as a full page.
    FullNavigation Navigation = iota
    // MorphNavigation fetches only the slot of the deepest shared layout.
    MorphNavigation
)

type Node

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

Node is one node of a render tree. Only this package implements Node.

var Append Node = patchModeNode{ModeAppend}

Append sends the following patches with append mode.

var Prepend Node = patchModeNode{ModePrepend}

Prepend sends the following patches with prepend mode.

var Remove Node = patchModeNode{ModeRemove}

Remove sends the following patches with remove mode.

var Replace Node = patchModeNode{ModeReplace}

Replace sends the following patches with replace mode.

var ViewTransition Node = transitionNode{}

ViewTransition wraps the following patches in startViewTransition.

func DevRender

func DevRender(pkgPath, name string, args ...any) (Node, bool)

DevRender is the dev hook of a generated function. A production build never calls it.

func EachRow

func EachRow[T any](rows []T, fn func(int, T) Node) Node

EachRow renders one node per row of a slice field.

func El

func El(name string, attrs Attrs, children ...Node) Node

El returns an element node. An empty attribute value means a boolean attribute; AttrBool with the value "false" is omitted.

func FieldErrorNode

func FieldErrorNode(fieldID, message string) Node

FieldErrorNode renders the error element of one field. Field components render the same element so a live validation patch morphs it.

func FlashToasts

func FlashToasts() Node

FlashToasts renders the toasts that a handler queued with the redirect to this page. gx.Toaster holds it; a toaster component of the app puts it inside its own region. It renders nothing on a page with no flash.

func Frag

func Frag(children ...Node) Node

Frag returns a node that renders its children in order.

func Head

func Head(p HeadProps) Node

Head marks the head of a page or layout. The deepest title wins and the other tags merge.

func Icon

func Icon(body string, p IconProps) Node

Icon renders one icon as an inline svg with currentColor. body is the inner markup of a pinned icon pack, not user input.

func Int

func Int(v int64) Node

Int returns a text node for an integer. Generated code uses it for an expression of an integer type: the render writes the digits with no string.

func Island

func Island(name, props string, opts ...IslandOption) Node

Island returns the element of a TypeScript island. name is the import path of the package and the component name. props is the JSON of the props. The generated component function of an island calls it.

func NoFragment

func NoFragment(id string) Node

NoFragment returns the mark of a fragment that this render does not have. The fragment is in a branch of an if or a switch that the render did not take. The mark writes nothing. c.Update sends a patch that removes the fragment when the browser has it. The compiler writes the call.

func Open

func Open(name string, attrs Attrs) Node

Open returns the attributes of one element as a dynamic value. The static string before it ends with the name of the element.

func OpenFragment

func OpenFragment(name string, attrs Attrs) Node

OpenFragment returns the attributes of a fragment element as a dynamic value. A render with a request in scope gives the element a hash of its content.

func Raw

func Raw(s SafeHTML) Node

Raw returns a node that writes s without escaping. Use it only for gx.SafeHTML values.

func RenderToast

func RenderToast(r *http.Request, p ToastPatch) Node

RenderToast renders one toast for an adapter: with Config.Toast of the app that serves the request, or as ToastNode when the app sets none.

func Text

func Text(s string) Node

Text returns a node that escapes s as HTML text.

func ToastNode

func ToastNode(p ToastPatch) Node

ToastNode is the plain markup of one toast. An app that sets Config.Toast renders its own component instead.

func Toaster

func Toaster() Node

Toaster renders the plain region that Toast patches into. On the page after a redirect it holds the toasts that the handler queued with the redirect.

func Value

func Value(v any) Node

Value returns a text node for a renderable value: bool, integer, float, string, fmt.Stringer or error.

type ParamsFunc

type ParamsFunc func(*http.Request, string) string

ParamsFunc reads a path variable from a request.

type Patch

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

Patch is one change an adapter sends to the client.

type PatchMode

type PatchMode uint8

PatchMode selects how an element patch reaches the DOM.

const (
    // ModeMorph morphs the node into the existing element. It is the
    // default.
    ModeMorph PatchMode = iota
    // ModeInner replaces the children of the existing element.
    ModeInner
    // ModeAppend puts the node inside the existing element, at the end.
    ModeAppend
    // ModePrepend puts the node inside the existing element, at the start.
    ModePrepend
    // ModeReplace replaces the existing element with the node.
    ModeReplace
    // ModeRemove removes the existing element.
    ModeRemove
)

type PrefetchMode

type PrefetchMode uint8

PrefetchMode selects when a link of a morph navigation loads its page before the click. The attribute data-gx-prefetch="hover", "viewport" or "none" on a link overrides the mode of the app.

const (
    // PrefetchNone loads a page only when the user clicks its link.
    PrefetchNone PrefetchMode = iota
    // PrefetchHover loads a page 100 ms after the pointer or the focus
    // comes to its link, or after a touch on the link.
    PrefetchHover
    // PrefetchViewport loads a page when its link comes into the viewport.
    PrefetchViewport
)

type RedirectPatch

type RedirectPatch struct{ URL string }

RedirectPatch navigates the client to URL.

type Response

type Response struct {
    Patches []Patch
    // Status is the HTTP status to answer with, or 0 for the default.
    Status int
    // Err is the handler error, shown by the dev overlay (REQ-DEV-06).
    Err error
    // Navigate marks a partial navigation response (REQ-RTE-12).
    Navigate bool
    // Head is the merged head of a partial navigation (REQ-RTE-12).
    Head *HeadProps
    // contains filtered or unexported fields
}

Response is the ordered answer of an action, a form or a navigation.

type Room

type Room string

Room is the key of a room with the signature of the server. A room is the set of viewers that share the shared signals of one component instance. A loader makes the value with RoomKey and gives it to the component as a prop; the page carries it, and a viewer cannot make one for a different key.

func RoomKey

func RoomKey(c *Ctx, key string) Room

RoomKey returns the room with the given key, signed by the server. A loader calls it for a viewer that can be in the room: the middleware of the group of the page ran before the loader. The key is what the viewers share, for example the id of a document.

type Route

type Route struct{}

Route is embedded in a route input struct. The tag carries the method and the pattern: "GET /products/{id}".

type Rule

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

Rule checks one input value. Every built-in rule leaves the zero value alone; Required rejects it.

func Accept

func Accept(types ...string) Rule

Accept limits the content types of an uploaded file.

func Check

func Check(fn func(v any) error) Rule

Check runs a server-only function.

func CheckCtx

func CheckCtx(fn func(ctx context.Context, v any) error) Rule

CheckCtx runs a server-only function with the request context.

func Each

func Each(rule Rule) Rule

Each applies a rule to every element of a slice or array.

func Field

func Field[T any](v *T, rules ...Rule) Rule

Field binds rules to one field. All rules must pass.

func Max

func Max(n int64) Rule

Max rejects a numeric value above n.

func MaxLen

func MaxLen(n int) Rule

MaxLen rejects a string longer than n code points.

func MaxSize

func MaxSize(n int64) Rule

MaxSize limits an uploaded file in bytes.

func Min

func Min(n int64) Rule

Min rejects a numeric value below n.

func MinLen

func MinLen(n int) Rule

MinLen rejects a string shorter than n code points.

func OneOf

func OneOf(values ...string) Rule

OneOf rejects a string outside the allowed values.

func Pattern

func Pattern(re *regexp.Regexp) Rule

Pattern rejects a string that does not match a constant regexp.

func True

func True(key string) Rule

True rejects a false bool.

type Rules

type Rules []Rule

Rules is the rule set of an input type.

type SafeHTML

type SafeHTML string

SafeHTML is HTML that needs no escaping.

type Secret

type Secret string

Secret is a value that must not leave the server. It renders and marshals as "[redacted]".

func (Secret) MarshalJSON

func (s Secret) MarshalJSON() ([]byte, error)

MarshalJSON never writes the secret.

func (Secret) Reveal

func (s Secret) Reveal() string

Reveal returns the secret value. Use it on the server only.

func (Secret) String

func (s Secret) String() string

String returns the redacted form.

type SignalPatch

type SignalPatch struct {
    Scope   string
    Signals any
}

SignalPatch sets the signals of one component scope.

type SignalRef

type SignalRef[T any] string

SignalRef is a prop that carries a parent signal reference into a child component.

func Ref

func Ref[T any](path string) SignalRef[T]

Ref builds a signal reference value from a bracket path.

type Slot

type Slot[T any] func(T) Node

Slot is a typed slot: a function that renders one value.

type Style

type Style string

Style is a dynamic style attribute value.

func StyleJoin

func StyleJoin(parts ...Style) Style

StyleJoin joins style parts with a semicolon.

func TransitionStyle

func TransitionStyle(t TransitionName) Style

TransitionStyle renders the sanitized view-transition-name and view-transition-class of a transition.

type Template

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

Template is the constant part of a template value: the static strings of one piece of generated markup, and the facts that a pass over a page needs. Generated code makes each Template one time, in a package variable. Code that a person writes uses gx.El.

func NewTemplate

func NewTemplate(static []string, depth []int, els []TemplateEl, roots []TemplateRoot) *Template

NewTemplate returns the constant part of a template value. Generated code calls it; the compiler gives the facts.

func (Template) With

func (t *Template) With(dyn ...Node) Node

With returns the template value of one render: the template and its dynamic values, in the order of the document.

type TemplateEl

type TemplateEl struct {
    Slot, Start, EndStatic, End int
}

TemplateEl is one element of a template whose attributes are a dynamic value. Slot is the index of that value. The element starts at the byte Start of the static string before the value, and ends at the byte End of the static string EndStatic.

type TemplateRoot

type TemplateRoot struct {
    El   int
    Slot int
    Name string
}

TemplateRoot is one top-level part of a template: an element of els (El, or -1) , an element with no dynamic attribute (Name) , a dynamic value (Slot, or -1) or text.

type ToastControl

type ToastControl struct {
    Label string
    URL   URL
    // Method is the HTTP method of the action. It is empty for a link.
    Method string
}

ToastControl is the one control of a toast: a link to URL, or a button that invokes the action at URL.

type ToastKind

type ToastKind uint8

ToastKind is the kind of one toast. A kind is also a ToastOption, so an action passes it directly: c.Toast("Saved", gx.ToastSuccess).

const (
    // ToastDefault is a neutral message with no icon.
    ToastDefault ToastKind = iota
    // ToastSuccess reports a finished operation.
    ToastSuccess
    // ToastInfo gives neutral information.
    ToastInfo
    // ToastWarning reports a result the user must check.
    ToastWarning
    // ToastError reports a failure. It renders as role="alert".
    ToastError
    // ToastLoading reports running work. It stays until a later toast with
    // the same ID replaces it, or the user closes it.
    ToastLoading
)

func (ToastKind) String

func (k ToastKind) String() string

String returns the kind as the data-kind value of the toast markup.

type ToastOption

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

ToastOption sets one field of a toast.

var ToastSticky ToastOption = toastOptionFunc(func(p *ToastPatch) { p.Sticky = true })

ToastSticky keeps the toast until the user closes it.

func ToastAction

func ToastAction[In interface {
    Pattern() string
    URL() string
}](label string, in In) ToastOption

ToastAction adds one button that invokes the action of a route value, for example Undo. The toast closes when the user presses the button. A toast holds one control: of ToastLink and ToastAction, the later option wins.

func ToastDescription

func ToastDescription(text string) ToastOption

ToastDescription adds a second line below the text.

func ToastDuration

func ToastDuration(d time.Duration) ToastOption

ToastDuration sets how long the toast stays. The default is 4 seconds.

func ToastID

func ToastID(id string) ToastOption

ToastID names the toast. A later toast with the same ID replaces the earlier one in place, so a handler can show loading and then success.

func ToastLink(label string, to interface{ URL() string }) ToastOption

ToastLink adds one link that navigates to a route value. A toast holds one control: of ToastLink and ToastAction, the later option wins.

type ToastPatch

type ToastPatch struct {
    Text        string
    Kind        ToastKind
    Description string
    // ID makes a later toast with the same ID replace this one in place.
    ID string
    // Duration is the time before the toast leaves, or 0 for the default.
    Duration time.Duration
    // Sticky keeps the toast until the user closes it.
    Sticky bool
    // Action is the control: a link or an action button. The zero value
    // renders none.
    Action ToastControl
}

ToastPatch adds one toast to the toaster region.

func (ToastPatch) Timeout

func (p ToastPatch) Timeout() time.Duration

Timeout returns the time before the toast leaves on its own. It is 0 for a sticky toast and for a loading toast: they never leave on their own.

type ToolAnswer

type ToolAnswer struct {
    // Text says what the call did. For a typed result it is the JSON of
    // the result.
    Text string
    // Structured is the JSON of the value that ToolResult set, or nil.
    Structured json.RawMessage
    // IsError is true when the call did not run the action to its end.
    IsError bool
}

ToolAnswer is the answer of one tool call for an agent.

type ToolField

type ToolField struct {
    Name string
    In   string
}

ToolField is one top-level argument of a tool. In names the part of the request that the binder reads it from: "path", "query", "form" or "signal".

type ToolInfo

type ToolInfo struct {
    Name        string
    Description string
    // Schema is the JSON Schema of the arguments.
    Schema string
    // Fields are the top-level arguments, in the order of the struct.
    Fields []ToolField
    // Confirm is true for a tool with gx.Confirm: a client asks the user
    // before an agent runs it. ReadOnly is true for a tool whose action has
    // the method GET. App.Tools sets the two; generated code does not.
    Confirm  bool
    ReadOnly bool
}

ToolInfo describes one tool: an action or a form that an agent can call. Generated code makes it from the input type. The name comes from the type, and the description from the doc comment of the action. The JSON Schema comes from the fields and the rules of the input.

type ToolOption

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

ToolOption changes how an agent can call a tool.

type Topic

type Topic string

Topic is the key of a server topic with the signature of the server. A loader makes the value with TopicKey and gives it to a component as a prop; the directive on:topic of the component listens to it. Code outside a request calls App.Publish with the key, and each open page that listens runs its action. A viewer cannot make a Topic for a different key.

func TopicKey

func TopicKey(c *Ctx, key string) Topic

TopicKey returns the topic with the given key, signed by the server. A loader calls it for a viewer that can see the data of the topic: the middleware of the group of the page ran before the loader. The key is what the server code publishes, for example "orders:" + userID.

type TransitionName

type TransitionName struct {
    Name string
    Key  string
}

TransitionName is the rendered value of a typed transition.

type Translator

type Translator func(key, fallback string) string

Translator turns a message key into a message. fallback is the English message of the key.

type URL

type URL string

URL is a prebuilt URL for an href or src.

func (URL) URL

func (u URL) URL() string

URL implements the redirect target interface.

type Unchecked

type Unchecked struct{}

Unchecked marks an action input whose signal fields need no rules. Embed it in the route struct.

Constants and variables

AnyOrigin

const AnyOrigin = "*"

AnyOrigin lists each origin in AllowOrigins. Use it for a public widget. AllowCredentials does not take it.

Confirm

var Confirm = ToolOption{/* contains filtered or unexported fields */}

Confirm makes the browser ask the user before an agent runs the tool. Use it for an action that the user cannot undo.

DefaultThemeCSS

const DefaultThemeCSS = `@import "tailwindcss";

@source "../.gx/classes.txt";
@source not "../js/vendor";
@source not "../gxislands";
@source not "../gxstyles";

@custom-variant dark {
  &:where(.dark, .dark *) {
    @slot;
  }
  @media (prefers-color-scheme: dark) {
    &:where(:root:not(.light), :root:not(.light) *) {
      @slot;
    }
  }
}

@layer base {
  * {
    @apply border-border outline-ring/50;
  }
}

/* Cross-document view transitions for full loads (REQ-STY-09). */
@view-transition {
  navigation: auto;
}

:root {
  --radius: 0.625rem;
  --background: oklch(1 0 0);
  --foreground: oklch(0.145 0 0);
  --card: oklch(1 0 0);
  --card-foreground: oklch(0.145 0 0);
  --popover: oklch(1 0 0);
  --popover-foreground: oklch(0.145 0 0);
  --primary: oklch(0.205 0 0);
  --primary-foreground: oklch(0.985 0 0);
  --secondary: oklch(0.97 0 0);
  --secondary-foreground: oklch(0.205 0 0);
  --muted: oklch(0.97 0 0);
  --muted-foreground: oklch(0.556 0 0);
  --accent: oklch(0.97 0 0);
  --accent-foreground: oklch(0.205 0 0);
  --destructive: oklch(0.577 0.245 27.325);
  --destructive-foreground: oklch(0.985 0 0);
  --border: oklch(0.922 0 0);
  --input: oklch(0.922 0 0);
  --ring: oklch(0.708 0 0);
  --chart-1: oklch(0.646 0.222 41.116);
  --chart-2: oklch(0.6 0.118 184.704);
  --chart-3: oklch(0.398 0.07 227.392);
  --chart-4: oklch(0.828 0.189 84.429);
  --chart-5: oklch(0.769 0.188 70.08);
  --sidebar: oklch(0.985 0 0);
  --sidebar-foreground: oklch(0.145 0 0);
  --sidebar-primary: oklch(0.205 0 0);
  --sidebar-primary-foreground: oklch(0.985 0 0);
  --sidebar-accent: oklch(0.97 0 0);
  --sidebar-accent-foreground: oklch(0.205 0 0);
  --sidebar-border: oklch(0.922 0 0);
  --sidebar-ring: oklch(0.708 0 0);
}

.dark {
  --background: oklch(0.145 0 0);
  --foreground: oklch(0.985 0 0);
  --card: oklch(0.205 0 0);
  --card-foreground: oklch(0.985 0 0);
  --popover: oklch(0.269 0 0);
  --popover-foreground: oklch(0.985 0 0);
  --primary: oklch(0.922 0 0);
  --primary-foreground: oklch(0.205 0 0);
  --secondary: oklch(0.269 0 0);
  --secondary-foreground: oklch(0.985 0 0);
  --muted: oklch(0.269 0 0);
  --muted-foreground: oklch(0.708 0 0);
  --accent: oklch(0.371 0 0);
  --accent-foreground: oklch(0.985 0 0);
  --destructive: oklch(0.704 0.191 22.216);
  --destructive-foreground: oklch(0.985 0 0);
  --border: oklch(1 0 0 / 10%);
  --input: oklch(1 0 0 / 15%);
  --ring: oklch(0.556 0 0);
  --sidebar: oklch(0.205 0 0);
  --sidebar-foreground: oklch(0.985 0 0);
  --sidebar-primary: oklch(0.488 0.243 264.376);
  --sidebar-primary-foreground: oklch(0.985 0 0);
  --sidebar-accent: oklch(0.269 0 0);
  --sidebar-accent-foreground: oklch(0.985 0 0);
  --sidebar-border: oklch(1 0 0 / 10%);
  --sidebar-ring: oklch(0.556 0 0);
}

@media (prefers-color-scheme: dark) {
  :root:not(.light) {
    --background: oklch(0.145 0 0);
    --foreground: oklch(0.985 0 0);
    --card: oklch(0.205 0 0);
    --card-foreground: oklch(0.985 0 0);
    --popover: oklch(0.269 0 0);
    --popover-foreground: oklch(0.985 0 0);
    --primary: oklch(0.922 0 0);
    --primary-foreground: oklch(0.205 0 0);
    --secondary: oklch(0.269 0 0);
    --secondary-foreground: oklch(0.985 0 0);
    --muted: oklch(0.269 0 0);
    --muted-foreground: oklch(0.708 0 0);
    --accent: oklch(0.371 0 0);
    --accent-foreground: oklch(0.985 0 0);
    --destructive: oklch(0.704 0.191 22.216);
    --destructive-foreground: oklch(0.985 0 0);
    --border: oklch(1 0 0 / 10%);
    --input: oklch(1 0 0 / 15%);
    --ring: oklch(0.556 0 0);
    --sidebar: oklch(0.205 0 0);
    --sidebar-foreground: oklch(0.985 0 0);
    --sidebar-primary: oklch(0.488 0.243 264.376);
    --sidebar-primary-foreground: oklch(0.985 0 0);
    --sidebar-accent: oklch(0.269 0 0);
    --sidebar-accent-foreground: oklch(0.985 0 0);
    --sidebar-border: oklch(1 0 0 / 10%);
    --sidebar-ring: oklch(0.556 0 0);
  }
}

@theme inline {
  --color-background: var(--background);
  --color-foreground: var(--foreground);
  --color-card: var(--card);
  --color-card-foreground: var(--card-foreground);
  --color-popover: var(--popover);
  --color-popover-foreground: var(--popover-foreground);
  --color-primary: var(--primary);
  --color-primary-foreground: var(--primary-foreground);
  --color-secondary: var(--secondary);
  --color-secondary-foreground: var(--secondary-foreground);
  --color-muted: var(--muted);
  --color-muted-foreground: var(--muted-foreground);
  --color-accent: var(--accent);
  --color-accent-foreground: var(--accent-foreground);
  --color-destructive: var(--destructive);
  --color-destructive-foreground: var(--destructive-foreground);
  --color-border: var(--border);
  --color-input: var(--input);
  --color-ring: var(--ring);
  --color-chart-1: var(--chart-1);
  --color-chart-2: var(--chart-2);
  --color-chart-3: var(--chart-3);
  --color-chart-4: var(--chart-4);
  --color-chart-5: var(--chart-5);
  --color-sidebar: var(--sidebar);
  --color-sidebar-foreground: var(--sidebar-foreground);
  --color-sidebar-primary: var(--sidebar-primary);
  --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
  --color-sidebar-accent: var(--sidebar-accent);
  --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
  --color-sidebar-border: var(--sidebar-border);
  --color-sidebar-ring: var(--sidebar-ring);
  --radius-sm: calc(var(--radius) - 4px);
  --radius-md: calc(var(--radius) - 2px);
  --radius-lg: var(--radius);
  --radius-xl: calc(var(--radius) + 4px);
}
`

DefaultThemeCSS is the Tailwind v4 theme file that gx init writes to app/theme.css. Token names match shadcn. Dark mode follows a .dark class, and a system preference when no class is set.

Dev

const Dev = false

Dev is false in a production build. Generated code asks it before it calls DevRender, so the compiler removes that call and the binary holds no part of the dev interpreter.

Email

var Email = Rule{
    // contains filtered or unexported fields
}

Email rejects a non-empty string that is not an email address.

IsURL

var IsURL = Rule{
    // contains filtered or unexported fields
}

IsURL rejects a non-empty string that is not an http or https URL. It is named IsURL because gx.URL is the typed link value.

KeepFocus

const KeepFocus navSetting = 1

KeepFocus is an option of Nav. After a morph navigation, focus stays where it is and no live region announces the new page.

MaxFormRows

const MaxFormRows = 1000

MaxFormRows is the number of rows one repeated form field can hold. A row with a larger index is ignored.

Required

var Required = Rule{
    // contains filtered or unexported fields
}

Required rejects the zero value of a string, number or bool.