ui

package module
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: MIT Imports: 20 Imported by: 0

README

github.com/vuka-lang/ui

The UI library for Vuka: what JSX in a .vuka file renders with. A file that imports github.com/vuka-lang/ui is a JSX file whose elements become ui.El, ui.Text, ui.Child, … (the package declares const VukaJSX = 1, Vuka's JSX target contract).

  • ui — Node (= templ.Component), elements and text, Safe, Style, ErrorBoundary, HTML rendering (String, Write, Handler), Walk and Renderer; stateful components (Live, On, Event); JS commands the browser runs on an event (JS, Ref, Live.PushJS), and a payload for a component's scripts (Live.PushEvent); links a live page follows over its connection (Link, JS.Patch/Navigate, Live.PushPatch/PushNavigate).
  • ui/live — sessions that keep stateful components alive for a connected browser, and the wire protocol transports speak.
  • ui/term — renders a node tree as terminal text.
  • ui/templx — templ interop: children for templ components, the components of .templ files a vuka.File names.
import "github.com/vuka-lang/ui"

func Hello(name string) ui.Node {
	return <p>Hello, {name}!</p>
}

Documentation: https://vuka-lang.github.io/vuka/ui/

The code moved here from github.com/vuka-lang/vuka at commit 1af97d1 (v0.8.0); see that repository's history for its earlier changes.

MIT licensed.

Documentation

Index

Constants

View Source
const Styles = `` /* 6624-byte string literal not displayed */

Styles is the stylesheet the components here render against: the --ui-* design tokens and the rules for every component's classes (.vk-modal, .vk-alert, .vk-toast, .vk-table, .vk-datatable). It is plain CSS — no build step, no Tailwind pass — so an app ships it by putting StyleTag in its layout head, or by serving it as a static file. Tokens have light defaults and dark values under prefers-color-scheme (overridable with a data-theme attribute on the html element), so the components follow the page's theme.

View Source
const VukaJSX = 1

VukaJSX marks the package as a JSX target implementing version 1 of Vuka's contract: a .vuka file importing ui lowers its JSX to El, Text, Child, Fragment, Nodes and Try; on… attributes to On; tags naming a Stateful type to Component; and children of components that read them from their context (templ components) go through WithChildren.

Variables

This section is empty.

Functions

func AttachLive

func AttachLive(c Stateful, inst LiveInstance)

AttachLive binds a component to its session instance. Package live calls it.

func CheckHandler

func CheckHandler(fn any) error

CheckHandler reports a value an on… attribute can't take: a handler is a func(), or a func taking the event's value (a string, number or bool), a form (a struct or pointer to one, or url.Values) or an Event, optionally after a context.Context, returning nothing or an error.

func CheckStateful

func CheckStateful(c Stateful) error

CheckStateful reports a stateful component that embeds *Live rather than Live, which has no instance to attach.

func Contains added in v0.9.0

func Contains(s string) string

Contains is a GetAttr value matching any value that holds s.

Example:

<button onClick={ui.JS.AddClass(ui.GetAttr("title", ui.Contains("draft")), "italic")}>Mark drafts</button>

func EncodeJS added in v0.2.0

func EncodeJS(ctx context.Context, ch JSChain) ([]byte, error)

EncodeJS is a chain's JSON, the value of its data-vk-js-<event> attribute: each Push's handler registered with ctx's live host, which gives its id, or left without one when ctx has none.

func EventName

func EventName(attr string) string

EventName is the DOM event an on… attribute names: onClick is click, onKeyDown keydown.

func Handler

func Handler(f func(r *http.Request) (Node, error)) http.Handler

Handler serves the Node f builds for each request through templ.Handler: rendered in full with the request's context, then sent as text/html. An error from f or from rendering answers 500 with only the status text.

func KeyText

func KeyText(k any) string

KeyText is a key as text, its type and value: int=7.

func LoadableURL added in v0.10.0

func LoadableURL(u string) bool

LoadableURL reports whether a browser may be sent to u by script, as the live runtime's navigations and redirects do: a path or a URL relative to the page, or an absolute http or https URL. A javascript:, vbscript: or data: URL loaded that way would run or show in the page's origin, and other schemes hand the visitor to another program; the runtime refuses them too.

func MountLive

func MountLive(ctx context.Context, c Stateful) error

MountLive runs c's Mount method, if it has one: Mount(), Mount() error, Mount(context.Context) or Mount(context.Context) error.

func Prefix added in v0.9.0

func Prefix(s string) string

Prefix is a GetAttr value matching any value that starts with s.

Example:

<button onClick={ui.JS.Hide(ui.GetAttr("id", ui.Prefix("step-")))}>Hide steps</button>

func SettleState

func SettleState(c Stateful)

SettleState marks c's Assigns unchanged, after a render.

func String

func String(ctx context.Context, n Node) (string, error)

String renders n as HTML into a string.

func Suffix added in v0.9.0

func Suffix(s string) string

Suffix is a GetAttr value matching any value that ends with s.

Example:

<button onClick={ui.JS.Show(ui.GetAttr("href", ui.Suffix(".pdf")))}>Show PDFs</button>

func TrackedState

func TrackedState(c Stateful) (tracked, changed bool)

TrackedState reports whether c's state is all Assigns (tracked), and whether one of them changed since SettleState. Package live calls it.

func Void

func Void(tag string) bool

Void reports whether tag is a void element: no children, no closing tag.

func Walk

func Walk(ctx context.Context, n Node, r Renderer) error

Walk sends n's tree to r. Frames, Groups, Builders and Child conversions are flattened (r never sees them); a TryNode with an error stops the walk with it; a Boundary walks its children into a recording first, and replays it into r — or, when they fail, walks Fallback(err) instead, so r never sees the failed part. Inside a Boundary an opaque Node is rendered while recording and replayed as Opaque of its HTML (a RawHTML). Children on a void element are an error. The first error from r stops the walk.

func WithLiveHost

func WithLiveHost(ctx context.Context, h LiveHost) context.Context

WithLiveHost is ctx carrying h.

func Word added in v0.9.0

func Word(s string) string

Word is a GetAttr value matching any space-separated list of words that has s among them, as class lists are.

Example:

<button onClick={ui.JS.Hide(ui.GetAttr("data-tags", ui.Word("old")))}>Hide old</button>

func Write

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

Write renders n with r's context and sends it as text/html (unless a Content-Type is set already). The page is rendered in full first, so a render error is returned with nothing written.

Types

type AlertProps added in v0.14.0

type AlertProps struct {
	// Variant is the tone: AlertInfo (default), AlertSuccess, AlertWarning or
	// AlertError.
	Variant AlertVariant
	// Title is an optional bold heading above the body.
	Title string
	// Dismissible adds a close button that hides the alert in the browser, no
	// round trip.
	Dismissible bool
	Class       string
	Children    Node
}

AlertProps configures an Alert; Children is the message body.

type AlertVariant added in v0.14.0

type AlertVariant string

AlertVariant is an Alert's tone.

const (
	AlertInfo    AlertVariant = "info"
	AlertSuccess AlertVariant = "success"
	AlertWarning AlertVariant = "warning"
	AlertError   AlertVariant = "error"
)

type Assign

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

Assign is a stateful component's state value whose changes a live session tracks: Set and Update mark it changed. A component whose state fields (its unexported ones, except those tagged `vuka:"-"`) are all Assigns renders again only when one of them changed or its props did; otherwise the session keeps its last render without calling Render.

type Row struct {
	ui.Live
	Name string            // a prop
	qty  ui.Assign[int]  // state
}

func (r *Row) Inc() { r.qty.Update(func(n int) int { return n + 1 }) }

Render must then read nothing but props and Assigns (and fields tagged `vuka:"-"`, which must not change what it renders); in tests (or with VUKA_LIVE_VERIFY=1) the session renders skipped components anyway and fails when the result differs.

func (*Assign[T]) Get

func (a *Assign[T]) Get() T

Get is the value.

func (*Assign[T]) Set

func (a *Assign[T]) Set(v T)

Set sets the value and marks it changed.

func (*Assign[T]) Update

func (a *Assign[T]) Update(f func(T) T)

Update sets the value to f of it and marks it changed.

type Attr

type Attr struct {
	Name  string
	Value any
}

Attr is one attribute of an element. In HTML it renders the way templ renders the same attribute written as an expression:

  • nil and false omit it, true writes it bare;
  • class takes a string or anything templ.Classes does ([]string, map[string]bool, templ.KV, …);
  • style takes a Style or anything templ's style attributes do, sanitized by templ (an unsafe property or value becomes templ's placeholder);
  • URL attributes are sanitized: href on any element (a, link, area, base, SVG's), xlink:href, action on form, data on object, src on iframe, frame, embed, source, track, video, audio, img, input and script, poster on video and formaction on button and input. templ.URL keeps relative URLs and http, https, mailto, tel, ftp and ftps, and turns anything else into about:invalid#TemplFailedSanitizationURL; a media source also keeps a data: URL of its kind (data:image/… on img src). A templ.SafeURL passes as is;
  • a templ.ComponentScript writes its Call; a Node is rendered and escaped; anything else goes through fmt.Sprint and is escaped (templ.ResolveAttributeValue).

className and htmlFor name class and for; ref names the element for JS commands (Ref) and renders as data-vk-ref. Names must be letters, digits, - _ : and . (templ only ever sees literal names; here a dynamic one could smuggle in another attribute), else Render fails.

type Boundary

type Boundary struct {
	Fallback func(err error) Node
	Children []Node
}

Boundary renders Children or, when one of them fails, Fallback(err) in place of everything they produced.

func (Boundary) Render

func (n Boundary) Render(ctx context.Context, w io.Writer) error

type Builder

type Builder func(add func(Node))

Builder produces children as it runs: a loop, if or match block. It runs once per Render or Walk, each added child rendered as it is added.

func (Builder) Render

func (n Builder) Render(ctx context.Context, w io.Writer) error

type BusyArg added in v0.9.0

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

BusyArg is what Busy takes: the targets to mark busy, and ui.Timeout.

type Column added in v0.14.0

type Column[T any] struct {
	// Header is the heading cell's content.
	Header Node
	// Cell renders a row's cell in this column.
	Cell func(T) Node
	// Align is "", "right" or "center".
	Align string
	// Class is added to every cell (header and body) in this column.
	Class string
	// Sort, when set, is the column's sort key: DataTable renders the header
	// as a sort control that calls its OnSort with this key. Table ignores it.
	Sort string
}

Column describes one column of a Table or DataTable over rows of type T.

type Commands added in v0.2.0

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

Commands is a chain of JS commands: changes the browser makes at once when an event fires, such as showing a menu, toggling a class or moving focus, with no round trip. A Push step also calls a handler on the server.

A chain is the value of an on… attribute. Start from JS and add steps; each method returns a new chain and leaves the old one as it was, so a shared start is safe to build on. On(target) gives a chain whose commands all act on one target.

A chain renders the same with or without a live session; without one, its Push steps do nothing.

Example:

<button onClick={ui.JS.RemoveClass(ui.Ref("menu"), "hidden").Push(c.MenuOpened)}>Open</button>
<ul ref="menu" class="hidden">…</ul>
var JS Commands

JS is the empty chain: every chain of commands starts here.

Example:

<button onClick={ui.JS.Toggle(ui.Ref("menu"))}>Menu</button>

func CloseModal added in v0.14.0

func CloseModal(ref string) Commands

CloseModal hides the modal named ref and restores the focus OpenModal remembered.

func DismissToast added in v0.14.0

func DismissToast() Commands

DismissToast hides the toast the event came from (the close button's), no round trip.

func DismissToastRef added in v0.14.0

func DismissToastRef(ref string) Commands

DismissToastRef hides the toast named ref.

func OpenModal added in v0.14.0

func OpenModal(ref string) Commands

OpenModal shows the modal named ref, trapping focus inside it: it remembers what had focus, shows the root and focuses the dialog's first field.

func ShowToast added in v0.14.0

func ShowToast(ref string) Commands

ShowToast reveals the toast named ref (one pre-rendered hidden in the container), for a browser-only notification.

func (Commands) AddClass added in v0.2.0

func (c Commands) AddClass(target Target, names ...string) Commands

AddClass adds CSS classes to target.

Example:

<button onClick={ui.JS.AddClass(ui.Ref("menu"), "open", "shadow")}>Menu</button>

func (Commands) Busy added in v0.9.0

func (c Commands) Busy(args ...BusyArg) Commands

Busy marks target busy — This when none is given — while what the event started is under way: a form posting, a Push waiting for its reply.

It sets aria-busy="true" on the target; makes the inputs, textareas and selects inside it readonly (never disabled, so their values are still submitted); gives its buttons and links aria-disabled="true" and tabindex="-1"; and ignores further clicks and submits on it, so a form can't be sent twice. Style it with Tailwind's aria-busy: variants, or group-aria-busy: inside an element with class="group".

It is undone, each attribute put back as it was, by the reply to a Push of the same chain (success or failure, before OnSuccess or OnError run), by ui.Timeout(d), or when the browser shows the page again from its back/forward cache. A plain form post that loads the next page needs none of them.

Example:

<form method="post" class="group" onSubmit={ui.JS.Busy()}><input name="username" /><button class="group-aria-busy:opacity-50">Sign in</button></form>
<button onClick={ui.JS.Busy(ui.Ref("form"), ui.Timeout(5*time.Second)).Push(c.Save)}>Save</button>

func (Commands) Call added in v0.3.0

func (c Commands) Call(name string, args ...any) Commands

Call runs a JavaScript function of the page: one registered with vuka.register(name, fn), else a dotted path on window ("Chart.refresh"). The function gets a context (ctx.el, ctx.event, ctx.root), then args: JSON values, or element reads such as ui.Ref("q").Value(), made when the step runs.

The chain waits for a returned promise. Returning false stops the chain; a throw stops it too, and fails the Push it predicts for. Call panics unless name is an identifier or a dotted path of them.

Example:

<button onClick={ui.JS.Call("confetti", 120)}>Celebrate</button>
<input ref="q" onInput={ui.JS.Debounce(200*time.Millisecond).Call("Search.preview", ui.Ref("q").Value())} />

func (Commands) Confirm added in v0.2.0

func (c Commands) Confirm(msg string) Commands

Confirm asks msg in the browser's confirm dialog, and stops the chain unless the user accepts.

Example:

<button onClick={ui.JS.Confirm("Delete " + pet.Name + "?").Push(func() { c.Delete(pet.ID) })}>Delete</button>

func (Commands) Copy added in v0.2.0

func (c Commands) Copy(target Target) Commands

Copy copies target's value (an input, textarea or select), or else its text, to the clipboard.

Example:

<input ref="token" value={key.Token} readonly />
<button onClick={ui.JS.Copy(ui.Ref("token")).AddClass(ui.This, "copied")}>Copy</button>

func (Commands) CopyText added in v0.2.0

func (c Commands) CopyText(text string) Commands

CopyText copies text to the clipboard.

Example:

<button onClick={ui.JS.CopyText(post.URL)}>Copy link</button>

func (Commands) Debounce added in v0.2.0

func (c Commands) Debounce(d time.Duration) Commands

Debounce waits until the events have stopped for d, then runs the steps after it. Only the steps after it wait; the steps before it run on every event.

Example: search once the user pauses typing.

<input name="q" onInput={ui.JS.Debounce(150*time.Millisecond).Push(c.Search)} />

func (Commands) Dispatch added in v0.2.0

func (c Commands) Dispatch(target Target, event string, opts ...DispatchOption) Commands

Dispatch fires a CustomEvent named event on target, for the page's scripts to listen to. It bubbles unless NoBubble; Detail sets its detail.

Example:

<button onClick={ui.JS.Dispatch(ui.This, "pet-picked", ui.Detail(pet.ID))}>Pick</button>

func (Commands) Else added in v0.2.0

func (c Commands) Else(chain ...JSChain) Commands

Else is the open If's last branch: its steps run when no branch before it ran. Panics with no open If, or after another Else.

Right after a When, Else(chain) is that When's other branch: chain runs when the condition doesn't hold, and no End is needed.

Example:

<input type="checkbox" ref="all" onChange={ui.JS.If(ui.Ref("all").Checked()).Show(ui.Ref("bulk")).Else().Hide(ui.Ref("bulk")).End()} />
<input type="checkbox" ref="all" onChange={ui.JS.When(ui.Ref("all").Checked(), ui.JS.Show(ui.Ref("bulk"))).Else(ui.JS.Hide(ui.Ref("bulk")))} />

func (Commands) ElseIf added in v0.2.0

func (c Commands) ElseIf(cond Conditional) Commands

ElseIf is another branch of the open If: its steps run when no branch before it ran and cond holds. Panics with no open If, or after its Else.

Example:

<select ref="plan" onChange={ui.JS.If(ui.Ref("plan").Value().Eq("team")).Show(ui.Ref("seats")).ElseIf(ui.Ref("plan").Value().Eq("free")).Hide(ui.Ref("seats")).End()}>…</select>

func (Commands) End added in v0.2.0

func (c Commands) End() Commands

End closes the open If: the steps after it run whichever branch ran. Panics with no open If.

Example: the Push runs whether the box was checked or not.

<input type="checkbox" ref="done" onChange={ui.JS.If(ui.Ref("done").Checked()).AddClass(ui.Closest("li"), "line-through").Else().RemoveClass(ui.Closest("li"), "line-through").End().Push(c.ToggleDone)} />

func (Commands) Exec added in v0.2.0

func (c Commands) Exec(target Target, attr string) Commands

Exec runs the commands held in target's attribute attr: another element's chain, rendered as data-vk-js-<event>, or a JSON list of commands. Inside them, This is target.

Example: Escape runs the Cancel button's click.

<div ref="dialog" onKeyDown={ui.JS.Key("Escape").Exec(ui.Ref("cancel"), "data-vk-js-click")}>
	<button ref="cancel" onClick={ui.JS.Hide(ui.Ref("dialog")).PopFocus()}>Cancel</button>
</div>

func (Commands) Focus added in v0.2.0

func (c Commands) Focus(target Target) Commands

Focus moves the keyboard focus to target.

Example:

<button onClick={ui.JS.Show(ui.Ref("search")).Focus(ui.Ref("search"))}>Search</button>

func (Commands) FocusFirst added in v0.2.0

func (c Commands) FocusFirst(target Target) Commands

FocusFirst focuses the first focusable element inside target, such as a dialog's first field.

Example:

<button onClick={ui.JS.Show(ui.Ref("dialog")).FocusFirst(ui.Ref("dialog"))}>Edit</button>

func (Commands) Hide added in v0.2.0

func (c Commands) Hide(target Target, opts ...ShowOption) Commands

Hide hides target (display: none). Options: Transition, Time.

Example:

<button onClick={ui.JS.Hide(ui.Ref("dialog"))}>Close</button>

func (Commands) If added in v0.2.0

func (c Commands) If(cond Conditional) Commands

If runs the steps after it, up to its ElseIf, Else or End, only when cond holds; cond is read when the If is reached. Ifs nest. Without End, the branch runs to the end of the chain.

Example:

<input type="checkbox" ref="all" onChange={ui.JS.If(ui.Ref("all").Checked()).Show(ui.Ref("bulk")).Else().Hide(ui.Ref("bulk")).End()} />

func (Commands) Key added in v0.2.0

func (c Commands) Key(keys ...string) Commands

Key stops the chain unless the event is a press of one of keys, named as KeyboardEvent.key names them: "Enter", "Escape", "a". Put it first: the steps before it run on every key.

Example:

<div ref="dialog" onKeyDown={ui.JS.Key("Escape").Hide(ui.Ref("dialog"))}>…</div>

func (Commands) Navigate added in v0.4.0

func (c Commands) Navigate(href string) Commands

Navigate moves a live page to another page, href, over its connection: the new page's components mount, and the address bar changes. On a page with no connection, for another origin, or when href's route isn't a page, it loads href. Href is sanitized as Patch's.

Example:

<button onClick={ui.JS.Navigate("/pets/" + strconv.Itoa(pet.ID))}>Open</button>

func (Commands) On added in v0.2.0

func (c Commands) On(target Target) CommandsOn

On returns a chain whose next commands all act on target, so they don't name it. On again switches the target; Commands() goes back to commands naming their own.

Example:

<button onClick={ui.JS.On(ui.Ref("menu")).RemoveClass("hidden").AddClass("opacity-100").Push(c.MenuOpened)}>Open</button>

func (Commands) OnError added in v0.3.0

func (c Commands) OnError(chain JSChain) Commands

OnError runs chain when the last Push before it fails: its handler returns an error, the server refuses the event, or no reply comes in time (see Timeout). That Push's predictions are taken back first, unless KeepOnError, except where the server has rendered a new value since. Panics with no Push before it.

Example: a like shown at once, taken back if it fails.

<button onClick={ui.JS.AddClass(ui.This, "liked").Push(c.Like).OnError(ui.JS.Show(ui.Ref("like-error")))}>Like</button>
<p ref="like-error" style="display: none">Couldn't like</p>

func (Commands) OnSuccess added in v0.3.0

func (c Commands) OnSuccess(chain JSChain) Commands

OnSuccess runs chain when the last Push before it succeeds: the reply carries no error. Its predictions stay, unless the server renders something else. Panics with no Push before it.

Example:

<button onClick={ui.JS.Push(c.Save).OnSuccess(ui.JS.Show(ui.Ref("saved")))}>Save</button>

func (Commands) Patch added in v0.4.0

func (c Commands) Patch(href string) Commands

Patch moves a live page to href on the same route, with other path parameters or query, and the address bar changes: a component whose Update takes the new URL stays mounted and gets the new props. On a page with no connection, or for another origin, it loads href. Href is a path, or an http or https URL (LoadableURL): any other, such as a javascript: URL, becomes about:invalid#TemplFailedSanitizationURL, which the runtime refuses to load. The server decides what stays mounted (see live.Session.Navigate): a component without such an Update mounts again.

Example:

<button onClick={ui.JS.Patch("/pets?page=2")}>Next</button>

func (Commands) PopFocus added in v0.2.0

func (c Commands) PopFocus() Commands

PopFocus focuses the element the last PushFocus remembered, and forgets it.

Example:

<button onClick={ui.JS.Hide(ui.Ref("dialog")).PopFocus()}>Cancel</button>

func (Commands) Push added in v0.2.0

func (c Commands) Push(handler any, opts ...PushOption) Commands

Push calls handler on the server, as onClick={handler} would: a method value, a closure or a func prop, getting the element's value unless ui.Value gives another. Without a live session it does nothing.

The steps before it, since the chain's start or the previous Push, are its predictions: they show at once and are taken back if the push fails. OnError, OnSuccess and Timeout after it apply to it.

Example:

<input name="q" onInput={ui.JS.Debounce(150*time.Millisecond).Push(c.Search)} />
<button onClick={ui.JS.RemoveClass(ui.Ref("menu"), "hidden").Push(c.MenuOpened)}>Open</button>

func (Commands) PushFocus added in v0.2.0

func (c Commands) PushFocus(target ...Target) Commands

PushFocus remembers an element for PopFocus to focus again: target, or with none the element that has the focus now. Use it before opening a dialog, so closing it gives the focus back.

Example:

<button onClick={ui.JS.PushFocus().Show(ui.Ref("dialog")).FocusFirst(ui.Ref("dialog"))}>Edit</button>

func (Commands) RemoveAttr added in v0.2.0

func (c Commands) RemoveAttr(target Target, name string) Commands

RemoveAttr removes target's attribute name, which, as SetAttr's, may not be an event handler attribute or srcdoc.

Example:

<button onClick={ui.JS.RemoveAttr(ui.Ref("save"), "disabled")}>Edit</button>

func (Commands) RemoveClass added in v0.2.0

func (c Commands) RemoveClass(target Target, names ...string) Commands

RemoveClass removes CSS classes from target.

Example:

<button onClick={ui.JS.RemoveClass(ui.Ref("menu"), "hidden")}>Menu</button>

func (Commands) ScrollTo added in v0.2.0

func (c Commands) ScrollTo(target Target) Commands

ScrollTo scrolls the page until target is in view.

Example:

<button onClick={ui.JS.ScrollTo(ui.Ref("comments"))}>Comments</button>

func (Commands) SetAttr added in v0.2.0

func (c Commands) SetAttr(target Target, name, value string) Commands

SetAttr sets target's attribute name to value. A URL attribute's value (href, src, action, formaction, xlink:href, poster, data, …) is sanitized as an href written in markup is: a javascript: URL, say, becomes about:invalid#TemplFailedSanitizationURL. Name may not be an event handler attribute (on…) or srcdoc: SetAttr panics on one, and the runtime refuses one in commands from elsewhere.

Example:

<button onClick={ui.JS.SetAttr(ui.This, "aria-pressed", "true")}>Bold</button>

func (Commands) SetText added in v0.3.0

func (c Commands) SetText(target Target, text string) Commands

SetText replaces target's content with text. Before a Push it predicts what the server will render, such as a new count.

Example:

<button onClick={ui.JS.SetText(ui.Ref("likes"), strconv.Itoa(c.likes+1)).Push(c.Like)}>♥ <span ref="likes">{c.likes}</span></button>

func (Commands) SetValue added in v0.2.0

func (c Commands) SetValue(target Target, v string) Commands

SetValue sets a form field's value ("true" checks a checkbox) and fires input and change on it, so its own on… attributes run.

Example:

<button onClick={ui.JS.SetValue(ui.Ref("q"), "").Focus(ui.Ref("q"))}>Clear</button>

func (Commands) Show added in v0.2.0

func (c Commands) Show(target Target, opts ...ShowOption) Commands

Show makes target visible: it removes its hidden attribute and sets its display (see Display). Options: Display, Transition, Time.

Example:

<button onClick={ui.JS.Show(ui.Ref("dialog"))}>Edit</button>

func (Commands) Throttle added in v0.2.0

func (c Commands) Throttle(d time.Duration) Commands

Throttle runs the steps after it at most once every d; for input events the last one still runs when the time is up. The steps before it run on every event.

Example:

<input type="range" name="volume" onInput={ui.JS.Throttle(100*time.Millisecond).Push(c.SetVolume)} />

func (Commands) Timeout added in v0.3.0

func (c Commands) Timeout(d time.Duration) Commands

Timeout is how long the last Push before it waits for its reply before it fails; 10s unless set. The same as Push's ui.Timeout option. Panics with no Push before it.

Example:

<button onClick={ui.JS.AddClass(ui.This, "liked").Push(c.Like).Timeout(3*time.Second)}>Like</button>

func (Commands) Toggle added in v0.2.0

func (c Commands) Toggle(target Target, opts ...ShowOption) Commands

Toggle shows target when it is hidden, and hides it otherwise. Options: Display, Transition, Time.

Example:

<button onClick={ui.JS.Toggle(ui.Ref("menu"))}>Menu</button>

func (Commands) ToggleAttr added in v0.2.0

func (c Commands) ToggleAttr(target Target, name, v1, v2 string) Commands

ToggleAttr flips target's attribute name between two values: it sets v1, or v2 when the attribute already is v1. Name and values are checked and sanitized as SetAttr's.

Example:

<button onClick={ui.JS.ToggleAttr(ui.This, "aria-expanded", "true", "false").Toggle(ui.Ref("menu"))}>Menu</button>

func (Commands) ToggleClass added in v0.2.0

func (c Commands) ToggleClass(target Target, names ...string) Commands

ToggleClass adds each class target doesn't have, and removes each it has.

Example:

<button onClick={ui.JS.ToggleClass(ui.Ref("menu"), "hidden")}>Menu</button>

func (Commands) Transition added in v0.2.0

func (c Commands) Transition(target Target, during, from, to string, opts ...ShowOption) Commands

Transition runs a class transition on target without showing or hiding it: during and from are added, from is swapped for to on the next frame, and all are removed after Time (200ms).

Example:

<button onClick={ui.JS.Transition(ui.Ref("cart"), "transition duration-300", "scale-110", "scale-100")}>Add to cart</button>

func (Commands) When added in v0.9.0

func (c Commands) When(cond Conditional, chain JSChain) Commands

When runs chain only when cond holds, read when the step is reached; the steps after it run either way. Else(chain) right after it gives the other branch. It needs no End: an If whose branch is chain.

Example:

<input ref="title" onInput={ui.JS.When(ui.Ref("title").Value(), ui.JS.RemoveAttr(ui.Ref("save"), "disabled")).Else(ui.JS.SetAttr(ui.Ref("save"), "disabled", ""))} />

type CommandsOn added in v0.2.0

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

CommandsOn is a chain whose commands act on one target, set by On, which they don't name. It is a chain like Commands, and as immutable.

Example:

<button onClick={ui.JS.On(ui.Ref("menu")).RemoveClass("hidden").Focus()}>Menu</button>

func (CommandsOn) AddClass added in v0.2.0

func (o CommandsOn) AddClass(names ...string) CommandsOn

AddClass adds CSS classes to the target.

Example:

<button onClick={ui.JS.On(ui.Ref("menu")).AddClass("open", "shadow")}>Menu</button>

func (CommandsOn) Busy added in v0.9.0

func (o CommandsOn) Busy(opts ...PushOption) CommandsOn

Busy marks the target busy until a Push of the chain is answered, the timeout given with ui.Timeout passes, or the page comes back from the browser's back/forward cache (see Commands.Busy).

Example:

<form method="post" ref="login" onSubmit={ui.JS.On(ui.Ref("login")).Busy(ui.Timeout(30*time.Second))}>…</form>

func (CommandsOn) Call added in v0.3.0

func (o CommandsOn) Call(name string, args ...any) CommandsOn

Call runs a JavaScript function of the page (see Commands.Call), with the target as its context's element, ctx.el.

Example:

<button onClick={ui.JS.On(ui.Ref("chart")).Call("Chart.refresh")}>Refresh</button>

func (CommandsOn) Commands added in v0.2.0

func (o CommandsOn) Commands() Commands

Commands goes back to a plain chain, whose commands name their own target.

Example:

<button onClick={ui.JS.On(ui.Ref("search")).Show().Commands().AddClass(ui.This, "active")}>Search</button>

func (CommandsOn) Confirm added in v0.2.0

func (o CommandsOn) Confirm(msg string) CommandsOn

Confirm asks msg in the browser's confirm dialog, and stops the chain unless the user accepts.

Example:

<button onClick={ui.JS.On(ui.Closest("li")).Confirm("Delete this todo?").Hide().Push(c.DeleteTodo)}>Delete</button>

func (CommandsOn) Copy added in v0.2.0

func (o CommandsOn) Copy() CommandsOn

Copy copies the target's value (an input, textarea or select), or else its text, to the clipboard.

Example:

<button onClick={ui.JS.On(ui.Ref("token")).Copy()}>Copy</button>

func (CommandsOn) CopyText added in v0.2.0

func (o CommandsOn) CopyText(text string) CommandsOn

CopyText copies text to the clipboard; the target plays no part.

Example:

<button onClick={ui.JS.On(ui.This).CopyText(post.URL).AddClass("copied")}>Copy link</button>

func (CommandsOn) Debounce added in v0.2.0

func (o CommandsOn) Debounce(d time.Duration) CommandsOn

Debounce waits until the events have stopped for d, then runs the steps after it; the steps before it run on every event.

Example:

<input name="q" onInput={ui.JS.On(ui.Ref("spinner")).Show().Debounce(150*time.Millisecond).Push(c.Search)} />

func (CommandsOn) Dispatch added in v0.2.0

func (o CommandsOn) Dispatch(event string, opts ...DispatchOption) CommandsOn

Dispatch fires a CustomEvent named event on the target. It bubbles unless NoBubble; Detail sets its detail.

Example:

<button onClick={ui.JS.On(ui.Ref("chart")).Dispatch("refresh", ui.NoBubble())}>Refresh</button>

func (CommandsOn) Else added in v0.2.0

func (o CommandsOn) Else(chain ...JSChain) CommandsOn

Else is the open If's last branch, taken when no branch before it was; right after a When, Else(chain) is its other branch (see Commands.Else).

Example:

<input type="checkbox" ref="all" onChange={ui.JS.On(ui.Ref("bulk")).If(ui.Ref("all").Checked()).Show().Else().Hide().End()} />
<input type="checkbox" ref="all" onChange={ui.JS.On(ui.Ref("bulk")).When(ui.Ref("all").Checked(), ui.JS.Show(ui.Ref("bulk"))).Else(ui.JS.Hide(ui.Ref("bulk")))} />

func (CommandsOn) ElseIf added in v0.2.0

func (o CommandsOn) ElseIf(cond Conditional) CommandsOn

ElseIf is another branch of the open If, taken when no branch before it was and cond holds.

Example:

<select ref="plan" onChange={ui.JS.On(ui.Ref("seats")).If(ui.Ref("plan").Value().Eq("team")).Show().ElseIf(ui.Ref("plan").Value().Eq("free")).Hide().End()}>…</select>

func (CommandsOn) End added in v0.2.0

func (o CommandsOn) End() CommandsOn

End closes the open If: the steps after it run whichever branch ran.

Example:

<input type="checkbox" ref="all" onChange={ui.JS.On(ui.Ref("bulk")).If(ui.Ref("all").Checked()).Show().Else().Hide().End().Push(c.SelectAll)} />

func (CommandsOn) Exec added in v0.2.0

func (o CommandsOn) Exec(attr string) CommandsOn

Exec runs the commands held in the target's attribute attr, such as another element's chain rendered as data-vk-js-<event>.

Example:

<div onKeyDown={ui.JS.Key("Escape").On(ui.Ref("cancel")).Exec("data-vk-js-click")}>…</div>

func (CommandsOn) Focus added in v0.2.0

func (o CommandsOn) Focus() CommandsOn

Focus moves the keyboard focus to the target.

Example:

<button onClick={ui.JS.On(ui.Ref("search")).Show().Focus()}>Search</button>

func (CommandsOn) FocusFirst added in v0.2.0

func (o CommandsOn) FocusFirst() CommandsOn

FocusFirst focuses the first focusable element inside the target.

Example:

<button onClick={ui.JS.On(ui.Ref("dialog")).Show().FocusFirst()}>Edit</button>

func (CommandsOn) Hide added in v0.2.0

func (o CommandsOn) Hide(opts ...ShowOption) CommandsOn

Hide hides the target (display: none). Options: Transition, Time.

Example:

<button onClick={ui.JS.On(ui.Ref("dialog")).Hide()}>Close</button>

func (CommandsOn) If added in v0.2.0

func (o CommandsOn) If(cond Conditional) CommandsOn

If runs the steps after it, up to its ElseIf, Else or End, only when cond holds (see Commands.If).

Example:

<input type="checkbox" ref="all" onChange={ui.JS.On(ui.Ref("bulk")).If(ui.Ref("all").Checked()).Show().Else().Hide().End()} />

func (CommandsOn) Key added in v0.2.0

func (o CommandsOn) Key(keys ...string) CommandsOn

Key stops the chain unless the event is a press of one of keys ("Enter", "Escape", …). Put it first.

Example:

<div onKeyDown={ui.JS.Key("Escape").On(ui.Ref("dialog")).Hide()}>…</div>

func (CommandsOn) Navigate added in v0.4.0

func (o CommandsOn) Navigate(href string) CommandsOn

Navigate moves a live page to another page, href (see Commands.Navigate).

Example:

<button onClick={ui.JS.On(ui.This).AddClass("opacity-50").Navigate("/pets/new")}>New pet</button>

func (CommandsOn) On added in v0.2.0

func (o CommandsOn) On(target Target) CommandsOn

On switches the target of the commands added from here on.

Example:

<button onClick={ui.JS.On(ui.Ref("dialog")).Hide().On(ui.Ref("saved")).Show()}>Done</button>

func (CommandsOn) OnError added in v0.3.0

func (o CommandsOn) OnError(chain JSChain) CommandsOn

OnError runs chain when the last Push before it fails, after its predictions are taken back (see Commands.OnError).

Example:

<button onClick={ui.JS.On(ui.This).AddClass("liked").Push(c.Like).OnError(ui.JS.Show(ui.Ref("like-error")))}>Like</button>

func (CommandsOn) OnSuccess added in v0.3.0

func (o CommandsOn) OnSuccess(chain JSChain) CommandsOn

OnSuccess runs chain when the last Push before it succeeds.

Example:

<button onClick={ui.JS.On(ui.Ref("saved")).Hide().Push(c.Save).OnSuccess(ui.JS.Show(ui.Ref("saved")))}>Save</button>

func (CommandsOn) Patch added in v0.4.0

func (o CommandsOn) Patch(href string) CommandsOn

Patch moves a live page to href on the same route (see Commands.Patch).

Example:

<button onClick={ui.JS.On(ui.Ref("list")).AddClass("opacity-50").Patch("/pets?page=2")}>Next</button>

func (CommandsOn) PopFocus added in v0.2.0

func (o CommandsOn) PopFocus() CommandsOn

PopFocus focuses the element the last PushFocus remembered, and forgets it; the target plays no part.

Example:

<button onClick={ui.JS.On(ui.Ref("dialog")).Hide().PopFocus()}>Cancel</button>

func (CommandsOn) Push added in v0.2.0

func (o CommandsOn) Push(handler any, opts ...PushOption) CommandsOn

Push calls handler on the server; the steps before it are its predictions (see Commands.Push). The target plays no part.

Example:

<button onClick={ui.JS.On(ui.Ref("menu")).RemoveClass("hidden").Push(c.MenuOpened)}>Open</button>

func (CommandsOn) PushFocus added in v0.2.0

func (o CommandsOn) PushFocus() CommandsOn

PushFocus remembers the target for PopFocus to focus again.

Example:

<button onClick={ui.JS.On(ui.This).PushFocus().On(ui.Ref("dialog")).Show().FocusFirst()}>Edit</button>

func (CommandsOn) RemoveAttr added in v0.2.0

func (o CommandsOn) RemoveAttr(name string) CommandsOn

RemoveAttr removes the target's attribute name.

Example:

<button onClick={ui.JS.On(ui.Ref("save")).RemoveAttr("disabled")}>Edit</button>

func (CommandsOn) RemoveClass added in v0.2.0

func (o CommandsOn) RemoveClass(names ...string) CommandsOn

RemoveClass removes CSS classes from the target.

Example:

<button onClick={ui.JS.On(ui.Ref("menu")).RemoveClass("hidden")}>Menu</button>

func (CommandsOn) ScrollTo added in v0.2.0

func (o CommandsOn) ScrollTo() CommandsOn

ScrollTo scrolls the page until the target is in view.

Example:

<button onClick={ui.JS.On(ui.Ref("comments")).Show().ScrollTo()}>Comments</button>

func (CommandsOn) SetAttr added in v0.2.0

func (o CommandsOn) SetAttr(name, value string) CommandsOn

SetAttr sets the target's attribute name to value.

Example:

<button onClick={ui.JS.On(ui.This).SetAttr("aria-pressed", "true")}>Bold</button>

func (CommandsOn) SetText added in v0.3.0

func (o CommandsOn) SetText(text string) CommandsOn

SetText replaces the target's content with text.

Example:

<button onClick={ui.JS.On(ui.Ref("status")).SetText("Saving…").Push(c.Save)}>Save</button>

func (CommandsOn) SetValue added in v0.2.0

func (o CommandsOn) SetValue(v string) CommandsOn

SetValue sets the target field's value ("true" checks a checkbox) and fires input and change on it.

Example:

<button onClick={ui.JS.On(ui.Ref("q")).SetValue("").Focus()}>Clear</button>

func (CommandsOn) Show added in v0.2.0

func (o CommandsOn) Show(opts ...ShowOption) CommandsOn

Show makes the target visible: it removes its hidden attribute and sets its display (see Display). Options: Display, Transition, Time.

Example:

<button onClick={ui.JS.On(ui.Ref("dialog")).Show(ui.Display("flex")).FocusFirst()}>Edit</button>

func (CommandsOn) Throttle added in v0.2.0

func (o CommandsOn) Throttle(d time.Duration) CommandsOn

Throttle runs the steps after it at most once every d; the steps before it run on every event.

Example:

<input type="range" ref="volume" onInput={ui.JS.On(ui.Ref("volume")).Throttle(100*time.Millisecond).AddClass("busy").Push(c.SetVolume)} />

func (CommandsOn) Timeout added in v0.3.0

func (o CommandsOn) Timeout(d time.Duration) CommandsOn

Timeout is how long the last Push before it waits for its reply before it fails; 10s unless set.

Example:

<button onClick={ui.JS.On(ui.This).AddClass("liked").Push(c.Like).Timeout(3*time.Second)}>Like</button>

func (CommandsOn) Toggle added in v0.2.0

func (o CommandsOn) Toggle(opts ...ShowOption) CommandsOn

Toggle shows the target when it is hidden, and hides it otherwise.

Example:

<button onClick={ui.JS.On(ui.Ref("menu")).Toggle()}>Menu</button>

func (CommandsOn) ToggleAttr added in v0.2.0

func (o CommandsOn) ToggleAttr(name, v1, v2 string) CommandsOn

ToggleAttr flips the target's attribute name between two values: it sets v1, or v2 when the attribute already is v1.

Example:

<button onClick={ui.JS.On(ui.This).ToggleAttr("aria-expanded", "true", "false")}>Menu</button>

func (CommandsOn) ToggleClass added in v0.2.0

func (o CommandsOn) ToggleClass(names ...string) CommandsOn

ToggleClass adds each class the target doesn't have, and removes each it has.

Example:

<button onClick={ui.JS.On(ui.Ref("menu")).ToggleClass("hidden")}>Menu</button>

func (CommandsOn) Transition added in v0.2.0

func (o CommandsOn) Transition(during, from, to string, opts ...ShowOption) CommandsOn

Transition runs a class transition on the target without showing or hiding it (see Commands.Transition).

Example:

<button onClick={ui.JS.On(ui.Ref("cart")).Transition("transition duration-300", "scale-110", "scale-100")}>Add to cart</button>

func (CommandsOn) When added in v0.9.0

func (o CommandsOn) When(cond Conditional, chain JSChain) CommandsOn

When runs chain only when cond holds (see Commands.When). The chain names its own targets.

Example:

<input ref="title" onInput={ui.JS.On(ui.Ref("save")).When(ui.Ref("title").Value().Not(), ui.JS.SetAttr(ui.Ref("save"), "disabled", "")).AddClass("checked")} />

type ComponentNode

type ComponentNode struct {
	Site  string
	Key   any
	Props Stateful
}

ComponentNode is a stateful component's tag, <Counter Start={5} />: Props is a fresh value carrying the attributes, never mounted itself. Site (the tag's place in the source), Key and the instance rendering it identify the instance a session keeps.

func (*ComponentNode) Render

func (n *ComponentNode) Render(ctx context.Context, w io.Writer) error

type Condition added in v0.2.0

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

Condition is a test for If, ElseIf and When, made from a target: t.Checked(), t.Value(), t.Value().Eq(v), t.Attr(name), t.Is(css) or t.Exists(), or conditions joined with And, Or, Not, All and Any. It is read in the browser when it is reached, not when the chain is built.

A read of a target that finds several elements holds when every one of them passes it, or with Some when at least one does; a target that finds none fails every read but Exists.

Example:

<input type="checkbox" ref="all" onChange={ui.JS.If(ui.Ref("all").Checked()).Show(ui.Ref("bulk")).Else().Hide(ui.Ref("bulk")).End()} />

func All added in v0.9.0

func All(conds ...Conditional) Condition

All holds when every one of conds holds; with none, it holds.

Example:

<input ref="name" onInput={ui.JS.When(ui.All(ui.Ref("name").Value(), ui.Ref("email").Value()), ui.JS.RemoveAttr(ui.Ref("send"), "disabled"))} />

func Any added in v0.9.0

func Any(conds ...Conditional) Condition

Any holds when one of conds holds; with none, it doesn't.

Example:

<input ref="phone" onInput={ui.JS.When(ui.Any(ui.Ref("phone").Value(), ui.Ref("email").Value()), ui.JS.Hide(ui.Ref("contact-error")))} />

func (Condition) And added in v0.9.0

func (c Condition) And(more ...Conditional) Condition

And holds when c and every one of more hold. Joining nests as written: a.And(b).Or(d) holds when a and b hold, or d does.

Example:

<input ref="email" onInput={ui.JS.If(ui.Ref("email").Value().And(ui.Ref("terms").Checked())).RemoveAttr(ui.Ref("send"), "disabled").End()} />

func (Condition) MarshalJSON added in v0.2.0

func (c Condition) MarshalJSON() ([]byte, error)

func (Condition) Not added in v0.9.0

func (c Condition) Not() Condition

Not holds when c doesn't.

Example:

<button onClick={ui.JS.If(ui.Ref("menu").Attr("hidden").Not()).Hide(ui.Ref("menu")).End()}>Close</button>

func (Condition) Or added in v0.9.0

func (c Condition) Or(more ...Conditional) Condition

Or holds when c or one of more holds.

Example:

<select ref="plan" onChange={ui.JS.If(ui.Ref("plan").Value().Eq("team").Or(ui.Ref("plan").Value().Eq("business"))).Show(ui.Ref("seats")).End()}>…</select>

func (Condition) Some added in v0.9.0

func (c Condition) Some() Condition

Some makes a read hold when at least one of the elements its target finds passes it, rather than every one. Panics on a joined condition.

Example:

<button onClick={ui.JS.If(ui.Inner("input").Value().Some()).Show(ui.Ref("clear")).End()}>Check</button>

type Conditional added in v0.2.0

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

Conditional is what If, ElseIf and When test and what Call reads from an element: a Condition or a ValueCondition.

type DataTableProps added in v0.14.0

type DataTableProps[T any] struct {
	Columns []Column[T]
	// Page is the current page of rows (see web.Paginate).
	Page Page[T]

	// OnPage is called with a 1-based page number when a pager control is
	// used; without it the pager renders as static text.
	OnPage any
	// OnSize is called with a new page size when the size select changes;
	// shown only with Sizes.
	OnSize any
	// Sizes are the page-size options offered when OnSize is set.
	Sizes []int
	// OnSearch is called with the search box's value as the user types;
	// without it no search box is shown.
	OnSearch any
	// Search is the current search value (kept in the box across renders).
	Search            string
	SearchPlaceholder string
	// OnSort is called with a column's Sort key when its header is clicked;
	// columns with no Sort key stay plain.
	OnSort any
	// Sort and SortDir ("asc"/"desc") mark the sorted column for the header
	// indicator.
	Sort    string
	SortDir string

	// Window is how many numbered pager buttons to show; default 5.
	Window int

	// Passed through to the underlying Table.
	RowKey     func(T) any
	RowHref    func(T) string
	RowActions func(T) Node
	Selectable bool
	SelectName string
	Empty      Node
	Class      string
}

DataTableProps configures a DataTable over a page of rows of type T. The On… handlers are live event handlers (a func, as an on… attribute takes); leaving one nil drops its control, so a DataTable can offer just paging, or paging with search and sort.

type DispatchOption added in v0.2.0

type DispatchOption jsArg

DispatchOption changes the event Dispatch fires: Detail, NoBubble.

func Detail added in v0.2.0

func Detail(v any) DispatchOption

Detail is the dispatched event's detail (event.detail in a listener), sent as JSON.

Example:

<button onClick={ui.JS.Dispatch(ui.This, "pet-picked", ui.Detail(pet.ID))}>Pick</button>

func NoBubble added in v0.2.0

func NoBubble() DispatchOption

NoBubble keeps the dispatched event on its target: it doesn't bubble up to the target's ancestors.

Example:

<button onClick={ui.JS.Dispatch(ui.Ref("chart"), "refresh", ui.NoBubble())}>Refresh</button>

type Element

type Element struct {
	Tag      string
	Attrs    []Attr
	Children []Node
}

Element is an element: <Tag Attrs>Children</Tag>. A void element (br, img, input, …; see Void) has no closing tag, and children on one are an error; in HTML, html is preceded by the doctype.

Text inside script follows templ's Go expressions in a script: it is JSON-encoded (templ's runtime.ScriptContentOutsideStringLiteral), so it arrives as a quoted JS string with < > & escaped. templ has no expressions inside style; here text in a style element is written as is with "</" written "<\/", so it can't end the element.

func (*Element) Render

func (n *Element) Render(ctx context.Context, w io.Writer) error

type Event

type Event struct {
	Target string     `json:"target"`
	Type   string     `json:"event,omitempty"`
	Value  string     `json:"value,omitempty"`
	Key    string     `json:"key,omitempty"`
	Form   url.Values `json:"form,omitempty"`
}

Event is what the browser reports of an event, and what a handler taking a ui.Event receives. Target is the handler's id; Type the DOM event; Value the target element's value (for a checkbox, "true" or "false"); Key the key of a keyboard event; Form the fields of the form a submit event comes from.

type EventHandler

type EventHandler struct{ Fn any }

EventHandler is an on… attribute's expression on an element: onClick={c.Inc}. Under a live session it renders as data-vk-on-<event>="<handler id>" and the session calls Fn when the browser reports the event; without one it renders nothing. A chain of JS commands (Commands, CommandsOn) renders as data-vk-js-<event>, with or without a session; a templ.ComponentScript as templ renders it.

func On

func On(fn any) EventHandler

On is an on… attribute's expression.

type Frame

type Frame struct {
	FP    uint64
	Shape string
	Kids  []Node
	// contains filtered or unexported fields
}

Frame is a piece of JSX as the compiler saw it: a tree's root, a block's body (one per loop iteration or branch taken), or a component tag's children. It renders exactly as its Kids would; under a live session it is also a frame of the render tree, whose markup splits into statics (what the source fixes, identical every render) and dynamics (what Go expressions produce), so a session sends the statics once and then only the dynamics that changed.

FP fingerprints what its statics are made of: its tags, attribute names and literal values, text, and where the expressions go — pieces of JSX that render the same statics share it, however they are formatted. Shape describes Kids, one item each, in the order they appear:

t        text from the source
h b c    a dynamic: an {expr} child, a {for}/{if}/{match} block, a component tag
E…(…)    an element: a flag per attribute, s (a literal) or d (an expression),
         then its children's items in parentheses
G(…)     a fragment, <>…</>

Hand-written trees need no Frame: a Node that isn't one is a single dynamic of the frame around it, rendered to HTML.

func (*Frame) Render

func (n *Frame) Render(ctx context.Context, w io.Writer) error

type Group

type Group []Node

Group is children with no element around them.

func (Group) Render

func (n Group) Render(ctx context.Context, w io.Writer) error

type HTMLRenderer

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

HTMLRenderer is the Renderer writing HTML: what Render does. Escaping and sanitizing are templ's (see Attr and Element).

func NewHTMLRenderer

func NewHTMLRenderer(ctx context.Context, w io.Writer) *HTMLRenderer

NewHTMLRenderer is an HTMLRenderer writing to w, unbuffered; ctx renders Node attribute values.

func (*HTMLRenderer) Close

func (h *HTMLRenderer) Close(e *Element) error

func (*HTMLRenderer) Opaque

func (h *HTMLRenderer) Opaque(ctx context.Context, n Node) error

func (*HTMLRenderer) Open

func (h *HTMLRenderer) Open(e *Element) error

func (*HTMLRenderer) Raw

func (h *HTMLRenderer) Raw(html string) error

func (*HTMLRenderer) Text

func (h *HTMLRenderer) Text(s string) error

type JSChain added in v0.2.0

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

JSChain is either kind of chain, Commands or CommandsOn: what an on… attribute, OnError and OnSuccess take.

type LinkProps added in v0.4.0

type LinkProps struct {
	Href string
	// Patch asks for the same live route with other parameters: the page
	// stays mounted when the server says so (an Update taking the URL),
	// else mounts again.
	Patch bool
	ID    string
	Class string
	Title string
	// Target and Rel as an a element's: a link with a target other than
	// _self is left to the browser.
	Target   string
	Rel      string
	Attrs    []Attr // any other attributes
	Children Node
}

LinkProps is a Link's attributes; the children are its content.

type Live

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

Live, embedded by value in a struct whose pointer has a Render() Node method, makes the struct a stateful component:

type Counter struct {
	ui.Live
	Start int // exported fields are props, set from the tag's attributes
	n     int // unexported fields are state
}

Rendered without a live session (ui.String, Handler, …) a stateful component mounts and renders once, as plain HTML. Under a session (package live) it is an instance that keeps its state between renders and answers the events of the elements it renders.

func (*Live) ID

func (l *Live) ID() string

ID is the instance's id in its session, the value of its root element's data-vk-id; "" when rendered without one.

func (*Live) PushEvent added in v0.7.0

func (l *Live) PushEvent(name string, payload any)

PushEvent hands payload to the component's scripts once the reply to the current event (or message, or the join) is applied: a hook's ctx.on(name, fn) gets fn(payload), payload as JSON. In the browser it is a "vk:event" CustomEvent fired on the component's root, not bubbling, its detail {name, payload}.

func (*Live) PushJS added in v0.2.0

func (l *Live) PushJS(ch JSChain)

PushJS runs commands in the browser once the reply to the current event (or message, or the join, from Mount) is applied, This being the component's root element and refs its own. Without a session it does nothing.

func (*Live) PushNavigate added in v0.4.0

func (l *Live) PushNavigate(href string)

PushNavigate moves the page to href once the reply to the current event (or message) is applied, as JS.Navigate does.

func (*Live) PushPatch added in v0.4.0

func (l *Live) PushPatch(href string)

PushPatch moves the page to href once the reply to the current event (or message) is applied, as JS.Patch does: the same live route with other parameters, the page staying mounted when an Update of its takes the URL (see live.Session.Navigate).

func (*Live) Subscribe

func (l *Live) Subscribe(topics ...string)

Subscribe asks the session for the messages published on topics, delivered to the component's Update methods. Without a session it does nothing.

type LiveHost

type LiveHost interface {
	Component(ctx context.Context, n *ComponentNode, w io.Writer) error
	Handler(ctx context.Context, fn any) string
	Keyed(ctx context.Context, key any) context.Context
}

LiveHost renders stateful components and registers event handlers for a live session. Package live implements it; ctx carries it.

type LiveInstance

type LiveInstance interface {
	ID() string
	Subscribe(topics ...string)
	PushJS(c Commands)
}

LiveInstance is a session's side of a component instance. Package live implements it.

type ModalProps added in v0.14.0

type ModalProps struct {
	// Ref names the modal's root for the open/close commands (OpenModal,
	// CloseModal) and for a server variant's Show/Hide. It must be unique on
	// the page; the default is "modal".
	Ref string
	// Title is the header content; omitted when nil.
	Title Node
	// Footer is the footer content (buttons); omitted when nil.
	Footer Node
	// Open renders the modal already shown, for a server-owned modal whose
	// open state is a live field. A browser-only modal leaves it false and
	// opens with OpenModal.
	Open bool
	// Dismissible shows a close button and closes on backdrop click and
	// Escape. Default true; set Closed to make a modal that only its own
	// buttons or the server can close.
	Closed bool
	// OnClose, when set, is the server handler the close affordances call
	// (a func, as an on… attribute takes); the close also pops focus in the
	// browser. Without it the close is browser-only (CloseModal).
	OnClose any
	// Size is "sm", "" (default) or "lg".
	Size     string
	Class    string
	Children Node
}

ModalProps configures a Modal; Children is its body.

type Node

type Node = templ.Component

Node is anything that renders HTML: what a JSX expression evaluates to. It is templ.Component itself, so Vuka components are templ components and templ components are Vuka children, with nothing in between.

The Nodes built here (*Element, TextNode, RawHTML, Group, Builder, TryNode, Boundary, *Frame) are also a tree any Renderer can Walk; any other Node — a templ component, a NodeFunc — is opaque: it can only render HTML. Nodes are immutable values; rendering one concurrently is safe.

func Alert added in v0.14.0

func Alert(p AlertProps) Node

Alert is an inline message box in one of four tones:

ui.Alert(ui.AlertProps{Variant: ui.AlertSuccess, Title: "Saved"}, ui.Text("Your changes are live."))

A dismissible alert hides itself with a browser command; a server that wants it gone for good drops it from its own render instead.

func Child

func Child(x any) Node

Child is a {expr} child: a Node as is, nil as nothing, an error as its message, a []Node or []any as each element in turn, anything else as Text.

func Component

func Component(site string, key any, props Stateful) Node

Component is a stateful component's tag.

func DataTable added in v0.14.0

func DataTable[T any](p DataTableProps[T]) Node

DataTable is a Table with a search box, sortable headers and a pager, driven from a live view's events. It renders a page (ui.Page[T], e.g. from web.Paginate) and calls the handlers the host supplies:

ui.DataTable(ui.DataTableProps[Book]{
	Columns:  cols,
	Page:     p.page.Get(),
	Search:   p.query.Get(),
	OnSearch: p.Search,   // func(string)
	OnSort:   p.SortBy,   // func(string)
	OnPage:   p.GoTo,     // func(int)
})

func El

func El(tag string, attrs []Attr, children ...Node) Node

El is an element.

func ErrorBoundary

func ErrorBoundary(fallback func(err error) Node, children ...Node) Node

ErrorBoundary renders children, or — when one of them fails — fallback(err) in place of everything they wrote.

func F

func F(fp uint64, shape string, kids ...Node) Node

F is a Frame. Generated code calls it.

func FT added in v0.13.0

func FT(fp uint64, shape string, build func([]any) Node, dyns ...any) Node

FT is a lazy Frame. Generated code calls it when the JSX target declares FT (ui does): build reconstructs the frame exactly as F would, from the dynamics; dyns are the dynamics in the order the shape lists them — a child expression, a block (ui.Nodes), a component tag, or an attribute value. The statics around them are derived once, by ui, from a sample tree build, so they match the live render tree the same source lowered with F.

func Fragment

func Fragment(children ...Node) Node

Fragment renders children in order, with no element around them.

func Link(p LinkProps) Node

Link is a link a live page follows over its connection:

<ui.Link href="/books/7">Dune</ui.Link>            another page: its components mount
<ui.Link href="/books?page=2" patch>Next</ui.Link>  this page, other parameters

It renders an a element with href, marked data-vk-link (data-vk-link="patch" with Patch), so it is an ordinary link wherever the runtime doesn't take it: without JavaScript, on a page that isn't connected, opened in a new tab or with a modifier key, or to another origin. Href is sanitized as an a element's (templ.URL), and the runtime follows only paths and http and https URLs.

func Modal(p ModalProps) Node

Modal is a dialog centred over a backdrop. A browser-only modal is hidden until OpenModal shows it and keeps its open state in the DOM:

<button onClick={ui.OpenModal("edit")}>Edit</button>
ui.Modal(ui.ModalProps{Ref: "edit", Title: ui.Text("Edit")}, body…)

A server-owned modal sets Open from a live field and OnClose to the handler that clears it, so the server decides when it shows:

ui.Modal(ui.ModalProps{Ref: "edit", Open: m.open, OnClose: m.Close}, body…)

Opening traps focus (PushFocus then FocusFirst); closing restores it (PopFocus). Escape and a backdrop click close a dismissible modal.

func Nodes

func Nodes(build func(add func(Node))) Node

Nodes is the children a loop, if or match block produces.

func RootAttrs

func RootAttrs(n Node, attrs ...Attr) (Node, bool)

RootAttrs is n with attrs added after its root element's own, when n is an element or a frame of one element; ok is false otherwise.

func Safe

func Safe(html string) Node

Safe is trusted HTML, written as is. Never pass it user input.

func StyleTag added in v0.14.0

func StyleTag() Node

StyleTag is a <style> element holding Styles, to place in a page's head so the components are themed:

func layout(page ui.Node) ui.Node {
	return ui.El("html", nil, ui.El("head", nil, ui.StyleTag()), ui.El("body", nil, page))
}

func Table added in v0.14.0

func Table[T any](p TableProps[T]) Node

Table renders rows of type T as an HTML table styled with the --ui-* tokens. It is presentational — DataTable adds paging, search and sort:

ui.Table(ui.TableProps[Book]{
	Columns: []ui.Column[Book]{
		{Header: ui.Text("Title"), Cell: func(b Book) ui.Node { return ui.Text(b.Title) }},
		{Header: ui.Text("Author"), Cell: func(b Book) ui.Node { return ui.Text(b.Author) }},
	},
	Rows:   books,
	RowKey: func(b Book) any { return b.ID },
})

func Text

func Text(v any) Node

Text is text: v formatted like fmt.Sprint, nil as nothing.

func Toast added in v0.14.0

func Toast(p ToastProps) Node

Toast is one notification. Its tone matches Alert's variants:

ui.Toast(ui.ToastProps{Variant: ui.AlertSuccess, Title: "Saved", Timeout: 4 * time.Second})

func ToastContainer added in v0.14.0

func ToastContainer(p ToastContainerProps) Node

ToastContainer is the fixed region toasts stack in. Place one per page (a live view renders a Toast per message it holds inside it):

ui.ToastContainer(ui.ToastContainerProps{Children: ui.Fragment(toasts…)})

func Try

func Try(n Node, err error) Node

Try is a (Node, error) component's result as a child.

func WithChildren

func WithChildren(c Node, children Node) Node

WithChildren renders c with children as its templ children (templ.WithChildren), so a templ component's { children... } renders them: <Card>{…}</Card> on a templ Card.

type NodeFunc

type NodeFunc = templ.ComponentFunc

NodeFunc is a function rendering HTML: templ.ComponentFunc.

type Page added in v0.14.0

type Page[T any] struct {
	Items   []T  // the items of this page
	Total   int  // how many items the whole list holds
	Page    int  // this page's number, 1-based
	Size    int  // how many items a full page holds
	Pages   int  // how many pages the list has (0 when empty)
	HasPrev bool // whether a page comes before this one
	HasNext bool // whether a page comes after this one
}

Page is one page of a larger list: the items of this page and the counts a pager needs. It is a plain value with no dependencies, so a server builds it (see web.Paginate) and a view renders it (see DataTable) without either side knowing the other.

p := ui.NewPage(rows, total, page, size)
for _, row := range p.Items { … }
if p.HasNext { … }

func NewPage added in v0.14.0

func NewPage[T any](items []T, total, page, size int) Page[T]

NewPage builds a Page from the items fetched for a page and the total count of the list. page is 1-based and clamped to the list; size is the page window (at least 1). It computes Pages, HasPrev and HasNext; it does not slice items, which the caller has already fetched for the page.

func (Page[T]) Empty added in v0.14.0

func (p Page[T]) Empty() bool

Empty reports whether the whole list holds no items.

func (Page[T]) From added in v0.14.0

func (p Page[T]) From() int

From is the 1-based number of this page's first item, for "showing 1–10 of 42"; 0 when the page has no items.

func (Page[T]) To added in v0.14.0

func (p Page[T]) To() int

To is the 1-based number of this page's last item; 0 when the page has no items.

func (Page[T]) Window added in v0.14.0

func (p Page[T]) Window(n int) []int

Window is up to n page numbers centred on the current page, for a pager's numbered controls: a stable-width run clamped to the list, e.g. with n=5 on page 7 of 20 it is [5 6 7 8 9]. It returns nil when the list has no pages.

type PageInfo added in v0.12.0

type PageInfo struct {
	// Live: the page renders a stateful component, an event handler or a JS
	// command pushing to one, so it takes a live session (package live),
	// whose render writes it differently. RenderPage stops at the first.
	Live bool
	// JS: the page has JS commands (data-vk-js-<event>), which the
	// runtime script runs.
	JS bool
	// Opaque: the page holds HTML the renderer didn't write, a templ
	// component's (or another opaque Node's) or Safe HTML naming a data-vk-
	// attribute, which only its HTML tells live or JS apart.
	Opaque bool
}

PageInfo is what RenderPage learned of a page while rendering it.

func RenderPage added in v0.12.0

func RenderPage(ctx context.Context, n Node, w io.Writer) (info PageInfo, err error)

RenderPage writes n to w as a live session's first render of a page writes it when nothing in it is live (keyed elements marked data-vk-key), and reports what it met. When info.Live it stops at the first live thing, w holding part of the page, and the page is the session's to render.

type PushOption added in v0.2.0

type PushOption func(*push)

PushOption changes a Push: Value, Timeout, KeepOnError.

func KeepOnError added in v0.3.0

func KeepOnError() PushOption

KeepOnError keeps a Push's predictions when it fails, instead of taking them back; OnError still runs. For a change the user should see either way, such as a "not sent" mark.

Example:

<button onClick={ui.JS.SetText(ui.Ref("status"), "Sending…").Push(c.Send, ui.KeepOnError()).OnError(ui.JS.SetText(ui.Ref("status"), "Not sent"))}>Send</button>

func Timeout added in v0.3.0

func Timeout(d time.Duration) PushOption

Timeout is how long a Push waits for the server's reply before it counts as failed and its OnError runs; 10s unless set. A reply that comes later is still applied.

Example:

<button onClick={ui.JS.AddClass(ui.This, "liked").Push(c.Like, ui.Timeout(3*time.Second))}>Like</button>

func Value added in v0.2.0

func Value(v any) PushOption

Value sends v to the handler in place of the element's value. The handler's parameter parses it as it would the element's value: a string as is, anything else as its JSON.

Example, for func (c *Pets) Pick(id int):

<button onClick={ui.JS.Push(c.Pick, ui.Value(pet.ID))}>Pick</button>

type RawHTML

type RawHTML string

RawHTML is trusted HTML, written as is.

func (RawHTML) Render

func (n RawHTML) Render(ctx context.Context, w io.Writer) error

type Rec added in v0.5.0

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

Rec is what generated templ code records a render through. Its zero value only writes. Not for hand-written code.

func Record added in v0.5.0

func Record(ctx context.Context, w io.Writer) Rec

Record is the recorder of the live render ctx belongs to, when w is the writer it records: the component renders into a frame of the tree. Else the zero Rec. Generated code calls it.

func (Rec) Close added in v0.5.0

func (c Rec) Close()

func (Rec) D added in v0.5.0

func (c Rec) D()

D ends a run of expression output: what was written since the last static or frame is a dynamic, empty if nothing was.

func (Rec) End added in v0.5.0

func (c Rec) End()

func (Rec) For added in v0.5.0

func (c Rec) For()

For starts a loop, Item each of its iterations, End the loop: a block of one frame per iteration, a dynamic of the frame around it.

func (Rec) Item added in v0.5.0

func (c Rec) Item()

func (Rec) Open added in v0.5.0

func (c Rec) Open()

Open starts a branch's frame (an if or switch); Close ends it, a dynamic of the frame around it.

func (Rec) Render added in v0.5.0

func (c Rec) Render(n Node, ctx context.Context, w io.Writer) error

Render renders n into w, as n.Render(ctx, w) does; recording, n is a dynamic of the frame, as a JSX child is: a frame of its own when it has one (JSX, a recorded templ component), a stateful component's instance, else its HTML.

func (Rec) S added in v0.5.0

func (c Rec) S(w io.Writer, n int, s string) error

S writes s, the n-th static of its file: a static of the frame.

type Renderer

type Renderer interface {
	Open(e *Element) error  // before children
	Close(e *Element) error // after children (not called for void elements)
	Text(s string) error
	Raw(html string) error                    // Safe content
	Opaque(ctx context.Context, n Node) error // a component that only renders HTML (templ, NodeFunc)
}

Renderer receives a node tree in document order; Walk drives it. The HTML renderer behind every Node's Render is one; package term is another.

type ShowOption added in v0.2.0

type ShowOption jsArg

ShowOption changes how Show, Hide, Toggle and Transition work: Display, Transition, Time.

func Display added in v0.2.0

func Display(v string) ShowOption

Display is the display Show sets, such as "flex" or "grid". Without it, Show removes the element's display style, and sets block if the element would still be hidden.

Example:

<button onClick={ui.JS.Show(ui.Ref("dialog"), ui.Display("flex"))}>Edit</button>

func Time added in v0.2.0

func Time(d time.Duration) ShowOption

Time is how long a transition runs before its classes are removed; 200ms unless set.

Example:

<button onClick={ui.JS.Hide(ui.Ref("toast"), ui.Transition("transition-opacity", "opacity-100", "opacity-0"), ui.Time(300*time.Millisecond))}>Dismiss</button>

func Transition added in v0.2.0

func Transition(during, from, to string) ShowOption

Transition animates Show, Hide or Toggle with CSS classes: during and from are added, from is swapped for to on the next frame, and all of them are removed once Time (200ms) has passed. Each is a space-separated list of classes.

Example:

<button onClick={ui.JS.Show(ui.Ref("menu"), ui.Transition("transition duration-200", "opacity-0", "opacity-100"))}>Menu</button>

type Stateful

type Stateful interface {
	Render() Node
	// contains filtered or unexported methods
}

Stateful is a stateful component: a pointer to a struct embedding Live, with a Render method.

func CopyLive

func CopyLive(c Stateful) Stateful

CopyLive is a shallow copy of c.

type Style

type Style map[string]string

Style is an inline style: style={ui.Style{"color": "red"}}, rendered by templ as "color:red;" sorted by property, each property and value sanitized.

type TableProps added in v0.14.0

type TableProps[T any] struct {
	Columns []Column[T]
	Rows    []T
	// RowKey gives each row a stable key for the live diff (the row's id).
	RowKey func(T) any
	// RowHref, when set, makes a row navigate to it on click (over the live
	// connection when connected).
	RowHref func(T) string
	// RowActions, when set, adds a trailing column rendering per-row controls.
	RowActions func(T) Node
	// Selectable adds a leading checkbox column; the checkboxes are named
	// SelectName (default "selected") with the row's RowKey as value, for a
	// form or a server handler to read.
	Selectable bool
	SelectName string
	// Empty is shown in place of the body when there are no rows; a default
	// message is used when nil.
	Empty Node
	Class string
}

TableProps configures a Table over rows of type T.

type Target added in v0.2.0

type Target string

Target is the element or elements a command acts on:

ui.This                  the element the attribute is on (the default)
ui.Ref("menu")           the element with ref="menu" in the same component
ui.Ref("user", "pass")   the elements with either ref, in page order
ui.GetAttr("name", "q")  the component's elements whose name attribute is "q"
ui.Closest(".card")      the nearest of This and its ancestors matching a selector
ui.Inner(".item")        the elements inside This matching a selector
ui.Sel("#cart")          every element of the page matching a selector

A plain string is a selector too: ui.JS.Hide("#cart") hides #cart. A target of several parts matches every element any part matches, in page order, each once.

Example:

<button onClick={ui.JS.Hide(ui.Closest("li"))}>Dismiss</button>
const This Target = ""

This is the element the on… attribute is on, and a command's target when it names none. In a chain the server pushes with PushJS, it is the component's root element.

Example:

<button onClick={ui.JS.ToggleClass(ui.This, "active")}>Bold</button>

func Closest added in v0.2.0

func Closest(sel string) Target

Closest is the nearest element matching a CSS selector, looking at This first and then up its ancestors.

Example:

<li class="todo">{todo.Title} <button onClick={ui.JS.Hide(ui.Closest("li"))}>Dismiss</button></li>

func GetAttr added in v0.9.0

func GetAttr(name string, values ...string) Target

GetAttr is the elements of the component instance that have the attribute name: any value with no values given, else one of values. A plain value is an exact match; Prefix, Suffix, Contains and Word match part of one. Page() widens it to the whole page. GetAttr picks elements; a target's Attr reads one.

When the component's JSX writes the attribute literally, the compiler checks each literal value against those it has. Panics when name is empty or not an attribute name.

Example:

<button onClick={ui.JS.SetAttr(ui.GetAttr("name", "username", "password"), "readonly", "")}>Lock</button>
<input name="username" /><input name="password" type="password" />
<button onClick={ui.JS.Hide(ui.GetAttr("data-step"))}>Skip</button>

func Inner added in v0.2.0

func Inner(sel string) Target

Inner is every element inside This matching a CSS selector.

Example:

<li onClick={ui.JS.Show(ui.Inner(".actions"))}>{post.Title} <span class="actions" style="display: none">Edit</span></li>

func Ref added in v0.2.0

func Ref(names ...string) Target

Ref is the element marked ref="name" in the same component instance, or with several names, every element marked with one of them, in page order. Each instance has its own refs, so ten Dropdowns each open their own menu; the compiler checks that the component's JSX has each ref. Focus, ScrollTo and Copy act on the first element a target finds.

Example:

<button onClick={ui.JS.Toggle(ui.Ref("menu"))}>Menu</button>
<ul ref="menu" style="display: none">…</ul>
<button onClick={ui.JS.SetAttr(ui.Ref("username", "password"), "readonly", "")}>Lock</button>
<input ref="username" /><input ref="password" type="password" />

func Sel added in v0.2.0

func Sel(css ...string) Target

Sel is every element of the page matching a CSS selector, or any of several, in page order; a plain string is the same target. Inside a component prefer Ref or GetAttr, which can't reach into another component.

Example:

<button onClick={ui.JS.Show(ui.Sel("#cart"))}>Cart</button>
<button onClick={ui.JS.Hide(ui.Sel("#cart", "#wishlist"))}>Close</button>

func (Target) Attr added in v0.2.0

func (t Target) Attr(name string) Condition

Attr holds when the target has the attribute name, whatever its value. As an argument of Call it is the attribute's value, or null.

Example:

<button onClick={ui.JS.If(ui.Ref("menu").Attr("hidden")).Show(ui.Ref("menu")).Else().Hide(ui.Ref("menu")).End()}>Menu</button>

func (Target) Checked added in v0.2.0

func (t Target) Checked() Condition

Checked holds when the target is a checked checkbox or radio button. As an argument of Call it is true or false.

Example:

<input type="checkbox" ref="all" onChange={ui.JS.If(ui.Ref("all").Checked()).Show(ui.Ref("bulk")).Else().Hide(ui.Ref("bulk")).End()} />

func (Target) Exists added in v0.2.0

func (t Target) Exists() Condition

Exists holds when the target finds an element at all.

Example:

<button onClick={ui.JS.If(ui.Sel("#cart").Exists()).Show("#cart").Else().Navigate("/cart").End()}>Cart</button>

func (Target) Is added in v0.2.0

func (t Target) Is(css string) Condition

Is holds when the target matches a CSS selector.

Example:

<button onClick={ui.JS.If(ui.This.Is(".active")).Push(c.Unfollow).Else().Push(c.Follow).End()}>Follow</button>

func (Target) MarshalJSON added in v0.2.0

func (t Target) MarshalJSON() ([]byte, error)

func (Target) Page added in v0.9.0

func (t Target) Page() Target

Page widens a GetAttr target from the component instance to the whole page. Panics on any other target.

Example:

<button onClick={ui.JS.Hide(ui.GetAttr("role", "alert").Page())}>Dismiss all</button>

func (Target) String added in v0.9.0

func (t Target) String() string

String is the target as its JSON shows it.

func (Target) Value added in v0.2.0

func (t Target) Value() ValueCondition

Value holds when the target's value isn't empty; .Eq(v) compares it. As an argument of Call it is the value itself, read when the step runs.

Example:

<input ref="title" onInput={ui.JS.If(ui.Ref("title").Value()).RemoveAttr(ui.Ref("save"), "disabled").Else().SetAttr(ui.Ref("save"), "disabled", "").End()} />

type TextNode

type TextNode string

TextNode is text, escaped when rendered.

func (TextNode) Render

func (n TextNode) Render(ctx context.Context, w io.Writer) error

type ToastContainerProps added in v0.14.0

type ToastContainerProps struct {
	// Ref names the region for ShowToast to reveal a toast inside it; the
	// default is "toasts".
	Ref string
	// Position is the corner the stack sits in; ToastTopRight by default.
	Position ToastPosition
	Class    string
	Children Node
}

ToastContainerProps configures a ToastContainer; Children are its toasts.

type ToastPosition added in v0.14.0

type ToastPosition string

ToastPosition is a ToastContainer's corner.

const (
	ToastTopRight    ToastPosition = "top-right"
	ToastTopLeft     ToastPosition = "top-left"
	ToastBottomRight ToastPosition = "bottom-right"
	ToastBottomLeft  ToastPosition = "bottom-left"
)

type ToastProps added in v0.14.0

type ToastProps struct {
	// Variant is the tone: AlertInfo (default), AlertSuccess, AlertWarning or
	// AlertError, shared with Alert.
	Variant AlertVariant
	// Title is an optional bold heading.
	Title string
	// ID identifies the toast for DismissToastRef and for a server list's key;
	// it renders as both id and ref so ShowToast/DismissToastRef can find it.
	ID string
	// Dismissible adds a close button; default true.
	Closed bool
	// Timeout, when set, fades the toast out after it in the browser (a CSS
	// animation, no JavaScript). The server removing it from its render is the
	// reliable way to drop it.
	Timeout  time.Duration
	Class    string
	Children Node
}

ToastProps configures one Toast; Children is the message body.

type Tree

type Tree struct {
	Key     uint64
	Statics []string
	Dyn     []any
}

Tree is a frame of a live render tree: the markup of a piece of JSX as statics, the strings its source fixes, around dynamics, what its expressions rendered. Its HTML is Statics[0] + Dyn[0] + Statics[1] + … + Statics[len(Dyn)]. A dynamic is a string of HTML, a nested *Tree, a *TreeList (a block's items) or a TreeRef (a stateful component instance, rendered by the session as a tree of its own).

Key identifies the statics: the frame's fingerprint in its render context. Two trees with the same Key have the same Statics, which are shared and must not be modified.

func BuildTree

func BuildTree(ctx context.Context, n Node, verify bool) (*Tree, error)

BuildTree renders n as a render tree. A Frame becomes a Tree split as its shape says; anything else is a frame of one dynamic. ctx should carry a live host; with verify, statics already known for a Key are rendered again and compared, and a difference is an error.

func OpaqueTree

func OpaqueTree(dyns ...any) *Tree

OpaqueTree is a frame with no statics of its own around dyns.

func (*Tree) HTML

func (t *Tree) HTML(b *strings.Builder, ref func(b *strings.Builder, id string))

HTML writes t's HTML into b, each TreeRef as ref writes it.

type TreeHost

type TreeHost interface {
	LiveHost
	ComponentRef(ctx context.Context, n *ComponentNode) (id string, err error)
}

TreeHost is a LiveHost that can render a stateful component's tag as a reference to its instance. Package live implements it.

type TreeList

type TreeList struct {
	Items []*Tree
	Keys  []string
}

TreeList is a {for}, {if} or {match} block's items, a frame per iteration or branch taken. Keys are the items' keys, from the key attribute of each item's first element or component tag; nil unless every item has one.

type TreeRef

type TreeRef string

TreeRef is a stateful component instance in a render tree: its id.

type TryNode

type TryNode struct {
	Node Node
	Err  error
}

TryNode is a (Node, error) component's result as a child: Err fails the render, else Node renders.

func (TryNode) Render

func (n TryNode) Render(ctx context.Context, w io.Writer) error

type ValueCondition added in v0.2.0

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

ValueCondition is t.Value(): it holds when the target's value isn't empty, and Eq compares it. As an argument of Call it is the value itself.

func (ValueCondition) And added in v0.9.0

func (c ValueCondition) And(more ...Conditional) Condition

And holds when the target has a value and every one of more holds.

Example:

<input ref="email" onInput={ui.JS.When(ui.Ref("email").Value().And(ui.Ref("terms").Checked()), ui.JS.RemoveAttr(ui.Ref("send"), "disabled"))} />

func (ValueCondition) Eq added in v0.2.0

Eq holds when the target's value is exactly v.

Example:

<select ref="kind" onChange={ui.JS.If(ui.Ref("kind").Value().Eq("other")).Show(ui.Ref("other")).Else().Hide(ui.Ref("other")).End()}>…</select>

func (ValueCondition) MarshalJSON added in v0.2.0

func (c ValueCondition) MarshalJSON() ([]byte, error)

func (ValueCondition) Not added in v0.9.0

func (c ValueCondition) Not() Condition

Not holds when the target's value is empty.

Example:

<input ref="title" onInput={ui.JS.When(ui.Ref("title").Value().Not(), ui.JS.SetAttr(ui.Ref("save"), "disabled", ""))} />

func (ValueCondition) Or added in v0.9.0

func (c ValueCondition) Or(more ...Conditional) Condition

Or holds when the target has a value or one of more holds.

Example:

<input ref="phone" onInput={ui.JS.When(ui.Ref("phone").Value().Or(ui.Ref("email").Value()), ui.JS.Hide(ui.Ref("contact-error")))} />

func (ValueCondition) Some added in v0.9.0

func (c ValueCondition) Some() ValueCondition

Some holds when at least one of the elements the target finds has a value, rather than every one; .Eq still compares.

Example:

<form onInput={ui.JS.If(ui.GetAttr("name", "q", "tag").Value().Some()).Show(ui.Ref("clear")).Else().Hide(ui.Ref("clear")).End()}>…</form>

Directories

Path Synopsis
Package live runs stateful components for a connected browser: a Session keeps the component instances of one page, calls their event handlers and Update methods, and answers each with the HTML of the components whose output changed.
Package live runs stateful components for a connected browser: a Session keeps the component instances of one page, calls their event handlers and Update methods, and answers each with the HTML of the components whose output changed.
internal/demo
Package demo is stateful components compiled by the Vuka compiler, for the live package's property tests and benchmarks.
Package demo is stateful components compiled by the Vuka compiler, for the live package's property tests and benchmarks.
internal/templdemo
templ: version: v0.3.1020
templ: version: v0.3.1020
livetest
Package livetest is a reference client of the live protocol, in Go: it keeps what a browser runtime keeps — the page's HTML for v1, each instance's render tree for v2 — and applies the server's messages the way a runtime must, so tests can check that what a client ends up with is what the server rendered.
Package livetest is a reference client of the live protocol, in Go: it keeps what a browser runtime keeps — the page's HTML for v1, each instance's render tree for v2 — and applies the server's messages the way a runtime must, so tests can check that what a client ends up with is what the server rendered.
Package templx bridges templ: children for templ components, and the components of .templ files a vuka.File names.
Package templx bridges templ: children for templ components, and the components of .templ files a vuka.File names.
Package term renders a ui Node tree as terminal text: headings, paragraphs word-wrapped at a width, lists, tables, quotes, code, links, and inline bold/italic/underline as ANSI styles when Color is on.
Package term renders a ui Node tree as terminal text: headings, paragraphs word-wrapped at a width, lists, tables, quotes, code, links, and inline bold/italic/underline as ANSI styles when Color is on.

Jump to

Keyboard shortcuts

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