Documentation
¶
Index ¶
- Constants
- Variables
- func AttachLive(c Stateful, inst LiveInstance)
- func CheckHandler(fn any) error
- func CheckIsland(t reflect.Type) error
- func CheckStateful(c Stateful) error
- func CheckValidate(t reflect.Type) error
- func Contains(s string) string
- func Count(n int) *int
- func EncodeJS(ctx context.Context, ch JSChain) ([]byte, error)
- func EventName(attr string) string
- func Handler(f func(r *http.Request) (Node, error)) http.Handler
- func IconNames() []string
- func IsHook(c any, method string) bool
- func IsIsland(t reflect.Type) bool
- func IsUpdate(m reflect.Method) bool
- func KeyStates(ctx context.Context, props Stateful)
- func KeyText(k any) string
- func LoadableURL(u string) bool
- func MountLive(ctx context.Context, c Stateful) error
- func PageTitle(ctx context.Context) string
- func Prefix(s string) string
- func Props(v any) string
- func PropsJSON(ctx context.Context, props any, opts ...IslandOpt) ([]byte, error)
- func Ptr[T any](v T) *T
- func RegisterIcon(name, body string)
- func RegisterIsland[T any](args ...any)
- func SetBound(ctx context.Context, x reflect.Value, data json.RawMessage) error
- func SettleState(c Stateful)
- func String(ctx context.Context, n Node) (string, error)
- func Suffix(s string) string
- func TrackedState(c Stateful) (tracked, changed bool)
- func TypeName(t reflect.Type) string
- func UntagProps(data []byte) ([]byte, error)
- func Validate(v any) error
- func ValidateTags(v any, tags ...string) error
- func Void(tag string) bool
- func Walk(ctx context.Context, n Node, r Renderer) error
- func WithLiveHost(ctx context.Context, h LiveHost) context.Context
- func WithPageTitle(ctx context.Context, title string) context.Context
- func Word(s string) string
- func Write(w http.ResponseWriter, r *http.Request, n Node) error
- type Alert
- type AlertPropsdeprecated
- type AlertVariant
- type AnyState
- type Assign
- type Attr
- type Badge
- type BadgePropsdeprecated
- type Bind
- type Binding
- type Boundary
- type Builder
- type BusyArg
- type Button
- type ButtonPropsdeprecated
- type Card
- type CardPropsdeprecated
- type Changed
- type Checkbox
- type Class
- type Classes
- type Column
- type Commands
- func (c Commands) AddClass(target Target, names ...string) Commands
- func (c Commands) Busy(args ...BusyArg) Commands
- func (c Commands) Call(name string, args ...any) Commands
- func (c Commands) Confirm(msg string) Commands
- func (c Commands) Copy(target Target) Commands
- func (c Commands) CopyText(text string) Commands
- func (c Commands) Debounce(d time.Duration) Commands
- func (c Commands) Dispatch(target Target, event string, opts ...DispatchOption) Commands
- func (c Commands) Else(chain ...JSChain) Commands
- func (c Commands) ElseIf(cond Conditional) Commands
- func (c Commands) End() Commands
- func (c Commands) Exec(target Target, attr string) Commands
- func (c Commands) Focus(target Target) Commands
- func (c Commands) FocusFirst(target Target) Commands
- func (c Commands) Hide(target Target, opts ...ShowOption) Commands
- func (c Commands) If(cond Conditional) Commands
- func (c Commands) Key(keys ...string) Commands
- func (c Commands) Navigate(href string) Commands
- func (c Commands) On(target Target) CommandsOn
- func (c Commands) OnError(chain JSChain) Commands
- func (c Commands) OnSuccess(chain JSChain) Commands
- func (c Commands) Patch(href string) Commands
- func (c Commands) PopFocus() Commands
- func (c Commands) Push(handler any, opts ...PushOption) Commands
- func (c Commands) PushFocus(target ...Target) Commands
- func (c Commands) RemoveAttr(target Target, name string) Commands
- func (c Commands) RemoveClass(target Target, names ...string) Commands
- func (c Commands) ScrollTo(target Target) Commands
- func (c Commands) Set(s AnyState, v any) Commands
- func (c Commands) SetAttr(target Target, name, value string) Commands
- func (c Commands) SetText(target Target, text string) Commands
- func (c Commands) SetValue(target Target, v string) Commands
- func (c Commands) Show(target Target, opts ...ShowOption) Commands
- func (c Commands) Throttle(d time.Duration) Commands
- func (c Commands) Timeout(d time.Duration) Commands
- func (c Commands) Toggle(target Target, opts ...ShowOption) Commands
- func (c Commands) ToggleAttr(target Target, name, v1, v2 string) Commands
- func (c Commands) ToggleClass(target Target, names ...string) Commands
- func (c Commands) Transition(target Target, during, from, to string, opts ...ShowOption) Commands
- func (c Commands) When(cond Conditional, chain JSChain) Commands
- type CommandsOn
- func (o CommandsOn) AddClass(names ...string) CommandsOn
- func (o CommandsOn) Busy(opts ...PushOption) CommandsOn
- func (o CommandsOn) Call(name string, args ...any) CommandsOn
- func (o CommandsOn) Commands() Commands
- func (o CommandsOn) Confirm(msg string) CommandsOn
- func (o CommandsOn) Copy() CommandsOn
- func (o CommandsOn) CopyText(text string) CommandsOn
- func (o CommandsOn) Debounce(d time.Duration) CommandsOn
- func (o CommandsOn) Dispatch(event string, opts ...DispatchOption) CommandsOn
- func (o CommandsOn) Else(chain ...JSChain) CommandsOn
- func (o CommandsOn) ElseIf(cond Conditional) CommandsOn
- func (o CommandsOn) End() CommandsOn
- func (o CommandsOn) Exec(attr string) CommandsOn
- func (o CommandsOn) Focus() CommandsOn
- func (o CommandsOn) FocusFirst() CommandsOn
- func (o CommandsOn) Hide(opts ...ShowOption) CommandsOn
- func (o CommandsOn) If(cond Conditional) CommandsOn
- func (o CommandsOn) Key(keys ...string) CommandsOn
- func (o CommandsOn) Navigate(href string) CommandsOn
- func (o CommandsOn) On(target Target) CommandsOn
- func (o CommandsOn) OnError(chain JSChain) CommandsOn
- func (o CommandsOn) OnSuccess(chain JSChain) CommandsOn
- func (o CommandsOn) Patch(href string) CommandsOn
- func (o CommandsOn) PopFocus() CommandsOn
- func (o CommandsOn) Push(handler any, opts ...PushOption) CommandsOn
- func (o CommandsOn) PushFocus() CommandsOn
- func (o CommandsOn) RemoveAttr(name string) CommandsOn
- func (o CommandsOn) RemoveClass(names ...string) CommandsOn
- func (o CommandsOn) ScrollTo() CommandsOn
- func (o CommandsOn) Set(s AnyState, v any) CommandsOn
- func (o CommandsOn) SetAttr(name, value string) CommandsOn
- func (o CommandsOn) SetText(text string) CommandsOn
- func (o CommandsOn) SetValue(v string) CommandsOn
- func (o CommandsOn) Show(opts ...ShowOption) CommandsOn
- func (o CommandsOn) Throttle(d time.Duration) CommandsOn
- func (o CommandsOn) Timeout(d time.Duration) CommandsOn
- func (o CommandsOn) Toggle(opts ...ShowOption) CommandsOn
- func (o CommandsOn) ToggleAttr(name, v1, v2 string) CommandsOn
- func (o CommandsOn) ToggleClass(names ...string) CommandsOn
- func (o CommandsOn) Transition(during, from, to string, opts ...ShowOption) CommandsOn
- func (o CommandsOn) When(cond Conditional, chain JSChain) CommandsOn
- type ComponentNode
- type Condition
- type Conditional
- type DataTable
- type DataTablePropsdeprecated
- type Defer
- type DeferredLoad
- type DispatchOption
- type Element
- type Event
- type EventHandler
- type Field
- type FieldAttr
- type FieldOptions
- type FieldPropsdeprecated
- type Form
- type FormPropsdeprecated
- type Frame
- type Group
- type HTMLRenderer
- type Image
- type ImagePropsdeprecated
- type Input
- type Invalid
- type IslandDecorator
- type IslandError
- type IslandField
- type IslandMethod
- type IslandOpt
- func CallAt(url, sig string) IslandOpt
- func Callback(prop string, fn any) IslandOpt
- func ClientOnly() IslandOpt
- func Emit(name string, handler any) IslandOpt
- func Fallback(n Node) IslandOpt
- func Idle() IslandOpt
- func IslandErr(err *IslandError) IslandOpt
- func Load() IslandOpt
- func Media(query string) IslandOpt
- func Once() IslandOpt
- func SSR() IslandOpt
- func Slot(n Node) IslandOpt
- func StateProp[T any](prop string, s State[T]) IslandOpt
- func Visible(rootMargin ...string) IslandOpt
- func WithLoads(l *Loads) IslandOpt
- type IslandOption
- type JSChain
- type LayoutFunc
- type LinkProps
- type Live
- func (l *Live) ID() string
- func (l *Live) Loads(group string, fn any)
- func (l *Live) OnChange(fn any)
- func (l *Live) OnMount(fn any)
- func (l *Live) PushEvent(name string, payload any)
- func (l *Live) PushJS(ch JSChain)
- func (l *Live) PushNavigate(href string)
- func (l *Live) PushPatch(href string)
- func (l *Live) Subscribe(topics ...string)
- type LiveHost
- type LiveInstance
- type LiveSchema
- type Loads
- type Modal
- type ModalPropsdeprecated
- type Node
- func Actions(buttons ...Node) Node
- func Cancel(on any, label ...string) Node
- func Child(x any) Node
- func Component(site string, key any, props Stateful) Node
- func Ctx(build func(ctx context.Context) Node) Node
- func Each[T any](items []T, fn func(T) Node) Node
- func El(tag string, attrs []Attr, children ...Node) Node
- func ErrorBoundary(fallback func(err error) Node, children ...Node) Node
- func F(fp uint64, shape string, kids ...Node) Node
- func FT(fp uint64, shape string, build func([]any) Node, dyns ...any) Node
- func Fragment(children ...Node) Node
- func HTML(src string, args ...any) Node
- func Icon(name string, class ...string) Node
- func If(cond bool, n Node) Node
- func IslandPage(x any, opts ...IslandOpt) Node
- func JSON(v any) Node
- func Key(key any, c Stateful) Node
- func Link(p LinkProps) Node
- func Mount(props any, opts ...IslandOpt) Node
- func MountIsland(site string, props any, opts ...IslandOpt) Node
- func Nodes(build func(add func(Node))) Node
- func ResolveContext(ctx context.Context, n Node) Node
- func RootAttrs(n Node, attrs ...Attr) (Node, bool)
- func Safe(html string) Node
- func Show(p ShowProps) Node
- func Spinner() Node
- func States(v any) Node
- func StyleTag() Node
- func Template(...any) Node
- func Text(v any) Node
- func TileGrid(tiles ...Node) Node
- func Try(n Node, err error) Node
- func WithChildren(c Node, children Node) Node
- type NodeFunc
- type Option
- type Page
- type PageInfo
- type Password
- type PushOption
- type RawHTML
- type Rec
- type Renderer
- type Select
- type Setter
- type ShowOption
- type ShowProps
- type Size
- type State
- func At[T, S any](s State[S], path string) State[T]
- func Derived[T any](value T) State[T]
- func NewDerived[T any](value T, expr string, deps ...any) State[T]
- func NewState[T any](site string, initial T) State[T]
- func PageState[T any](site string, initial T) State[T]
- func StateField[S, T any](s State[S], name string, sample T) State[T]
- func UsePageState[T any](initial T) State[T]
- func UseState[T any](initial T) State[T]
- func (s State[T]) And(o any) State[bool]
- func (s State[T]) Dec() Commands
- func (s State[T]) Eq(o any) State[bool]
- func (s State[T]) Ge(o any) State[bool]
- func (s State[T]) Get() T
- func (s State[T]) Gt(o any) State[bool]
- func (s State[T]) Inc() Commands
- func (s State[T]) Le(o any) State[bool]
- func (s State[T]) Len() State[int]
- func (s State[T]) Lt(o any) State[bool]
- func (s State[T]) Minus(o any) State[T]
- func (s State[T]) Ne(o any) State[bool]
- func (s State[T]) Neg() State[T]
- func (s State[T]) Not() State[bool]
- func (s State[T]) Or(o any) State[bool]
- func (s State[T]) Plus(o any) State[T]
- func (s State[T]) Reset() Commands
- func (s State[T]) Set(v T) Commands
- func (s State[T]) Toggle() Commands
- type StateHost
- type Stateful
- type Style
- type Submit
- type Tab
- type Table
- type TablePropsdeprecated
- type Tabs
- type TabsPropsdeprecated
- type Target
- func (t Target) Attr(name string) Condition
- func (t Target) Checked() Condition
- func (t Target) Exists() Condition
- func (t Target) Is(css string) Condition
- func (t Target) MarshalJSON() ([]byte, error)
- func (t Target) Page() Target
- func (t Target) String() string
- func (t Target) Value() ValueCondition
- type TextNode
- type Textarea
- type Tile
- type TilePropsdeprecated
- type Toast
- type ToastContainer
- type ToastContainerPropsdeprecated
- type ToastPosition
- type ToastPropsdeprecated
- type Tree
- type TreeHost
- type TreeList
- type TreeRef
- type TryNode
- type URL
- type ValueCondition
- func (c ValueCondition) And(more ...Conditional) Condition
- func (c ValueCondition) Eq(v string) Condition
- func (c ValueCondition) MarshalJSON() ([]byte, error)
- func (c ValueCondition) Not() Condition
- func (c ValueCondition) Or(more ...Conditional) Condition
- func (c ValueCondition) Some() ValueCondition
- type Variant
Constants ¶
const DefaultDebounce = 300 * time.Millisecond
DefaultDebounce is how long a bound field's set waits for more sets before it is sent; bind:"q,debounce=500" changes it.
const NoDebounce time.Duration = -1
NoDebounce, as a Bind's Debounce, sends each set at once: ui.Bind{Debounce: ui.NoDebounce}. A zero Debounce is DefaultDebounce.
const Styles = `` /* 16592-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.
const VukaJSX = 3
VukaJSX marks the package as a JSX target implementing version 3 of Vuka's contract: a .vuka file importing ui lowers each piece of its JSX to an HTML call, blocks to Go building a Node or []Node, tags naming a Stateful type to &T{…} (Key with a key), islands to their props (Mount with options), ui.State to UseState, and reads of states to State's methods; children of components that read them from their context (templ components) go through WithChildren.
Variables ¶
var IsRedirect = func(error) bool { return false }
IsRedirect, set by package web, tells an error that must reach the live session (a redirect) from one the component shows.
var Viewer func(ctx context.Context) any
Viewer is what every island's component knows of the visitor — $vuka in Vue, useVuka() in React, the vuka store in Svelte: package web/auth sets it to the signed-in identity's id, roles and perms.
Functions ¶
func AttachLive ¶
func AttachLive(c Stateful, inst LiveInstance)
AttachLive binds a component to its session instance. Package live calls it.
func CheckHandler ¶
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 CheckIsland ¶ added in v0.26.0
CheckIsland reports what a page backed by t (a pointer to its island's struct) can't be: a mistake in its LiveSchema, a Bind that doesn't fit, a method and a field (or two fields) of one wire name, a Changed method that isn't Changed([ctx]) [error].
func CheckStateful ¶
CheckStateful reports a stateful component that embeds *Live rather than Live, which has no instance to attach.
func CheckValidate ¶ added in v0.28.0
CheckValidate reports a validate tag of t, or of a struct it holds, that isn't one of Validate's rules.
func Contains ¶ added in v0.9.0
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
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 ¶
EventName is the DOM event an on… attribute names: onClick is click, onKeyDown keydown.
func 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 IconNames ¶ added in v0.15.0
func IconNames() []string
IconNames are the names in the built-in set, sorted.
func IsHook ¶ added in v1.0.0
IsHook reports whether method is LiveSchema or one of the hooks c's LiveSchema sets: never called from the browser. Package live asks.
func IsIsland ¶ added in v0.25.0
IsIsland reports whether t (a struct, or a pointer to one) is a registered island.
func IsUpdate ¶ added in v1.0.0
IsUpdate reports whether m, a method of a live component's type, is one of its Update methods, which a session calls with a message and the browser never does: Update, or an overload of it named after the type of the message it takes last, as vuka names Update's overloads and as a person writes them —
func (c *Chat) UpdateNewMessage(m NewMessage) { … }
func (c *Chat) UpdateTyping(ctx context.Context, t Typing) { … }
Update__T, the name older vuka commands gave an overload, is one too.
func KeyStates ¶ added in v0.24.0
KeyStates keys the states among a stateful component's props in the render ctx is of, its parent's: a state the parent passes is the parent's, whether or not the parent's own markup reads it first. Package ui calls it before a live host renders a component's tag.
func LoadableURL ¶ added in v0.10.0
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 ¶
MountLive runs c's Mount hook, the one its LiveSchema sets; or, from earlier releases, its Mount method: Mount(), Mount() error, Mount(context.Context) or Mount(context.Context) error.
func PageTitle ¶ added in v0.29.0
PageTitle is the title of the page being rendered, for a layout's <title>: what WithPageTitle set, else "".
func Prefix ¶ added in v0.9.0
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 Props ¶ added in v1.0.0
Props is a component's data as its script reads it: the exported fields of the struct v (or *v) as a JSON object, named as encoding/json names them — but Nodes, funcs, channels and an embedded Live, which never leave the server. A .vuka.html template with a component script writes it on its root as data-vk-p.
func PropsJSON ¶ added in v0.25.0
PropsJSON is props (an island's struct) as its data-vk-props holds it; package web signs a stateless page's. Its deferred fields not loaded (WithLoads; without it, none) are left out, as IslandPage leaves them.
func Ptr ¶ added in v0.25.0
func Ptr[T any](v T) *T
Ptr is a pointer to v: what the compiler writes for a value given to an optional island prop (a pointer field).
func RegisterIcon ¶ added in v0.15.0
func RegisterIcon(name, body string)
RegisterIcon adds or replaces an icon in the built-in set. body is the inner markup of a 24×24 SVG, drawn in currentColor (as the built-in icons are).
func RegisterIsland ¶ added in v0.25.0
RegisterIsland registers T as an island whose props are its exported fields. It takes what Island takes: a component path and a strategy, then options. Bare, the component is islands/[<module>/]<T>.<ext> under the frontend root, found by the vuka command (go tool vuka build-islands):
func init() { ui.RegisterIsland[Chart]() }
func init() { ui.RegisterIsland[Chart]("islands/Chart.vue", ui.Strategy("load")) }
It is what the compiler writes for @ui.Island on a type and for a .vuka file's import of a component file (import Counter "./islands/Counter.vue").
func SetBound ¶ added in v0.26.0
SetBound sets x's (a pointer to the island's struct) bound fields from data, the JSON object of wire names and values the component set, then runs its OnChange hook (or, from earlier releases, its Changed method). A field that isn't bound is refused, a value breaking its field's rules (or the validate: tags of a struct it holds) is Invalid under its wire name (q, address.city), and either way nothing is set.
func SettleState ¶
func SettleState(c Stateful)
SettleState marks c's Assigns unchanged, after a render.
func Suffix ¶ added in v0.9.0
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 ¶
TrackedState reports whether c's state is all Assigns (tracked), and whether one of them changed since SettleState. Package live calls it.
func TypeName ¶ added in v1.0.0
TypeName is t written as part of a Go name, as vuka names an overload after its parameters' types: int is Int, *Order Order, []Order Orders, map[string]int MapStringInt, any Any.
func UntagProps ¶ added in v0.25.0
UntagProps is props JSON as encoding/json reads it into the island's struct: each tagged date as its text; function and state props left out.
func Validate ¶ added in v0.28.0
Validate checks v (a struct, a pointer to one, or a slice, array or map of them) against its fields' validate:"…" tags, and the structs they hold, at any depth. It answers nil, or an error naming each failing field by its path of json names (level.code, items.0.name) with its message: a 422 whose FieldErrors a component reads as error.fields.
required not the zero value (a nil pointer, "", 0, false, an empty slice) omitempty the rest is skipped for the zero value min=n max=n a string's characters, a number's value, a slice's or map's items len=n exactly n of the same oneof=a b c one of the values (a|b|c also works) email an email address
func ValidateTags ¶ added in v0.28.1
ValidateTags is Validate naming each field by the first of tags it carries, else its Go name, as a form binder does (ValidateTags(v, "form", "json")); a tag of "-" leaves the field out.
func Walk ¶
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 ¶
WithLiveHost is ctx carrying h.
func WithPageTitle ¶ added in v0.29.0
WithPageTitle is ctx carrying the title of the page being rendered. Package web sets it for a page backed by a component: its Title(), else the type's name.
Types ¶
type Alert ¶ added in v0.14.0
type Alert 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
}
Alert is an inline message box in one of four tones:
<ui.Alert variant={ui.AlertSuccess} title="Saved">Your changes are live.</ui.Alert>
A dismissible alert hides itself with a browser command; a server that wants it gone for good drops it from its own render instead.
type AlertProps
deprecated
added in
v0.14.0
type AlertProps = Alert
AlertProps is Alert, by its former name.
Deprecated: use Alert: ui.Alert{…}, or <ui.Alert …> in a template.
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 AnyState ¶ added in v0.24.0
type AnyState interface {
// contains filtered or unexported methods
}
AnyState is a State of any type: what Commands.Set takes.
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.
type Attr ¶
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.
func BindAttr ¶ added in v0.25.0
BindAttr is an attribute named name that reads state s: rendered with its value, and kept up to date by the browser, as a JSX attribute reading a state is. It is for attribute lists built in Go — a component's []ui.Attr — where the compiler doesn't lower reads; an expression of states goes through ui.Derived:
<components.Button attrs={[]ui.Attr{
ui.BindAttr("aria-expanded", open),
ui.BindAttr("data-busy", ui.Derived(saving && !failed)),
}} />
An aria-* attribute writes a bool as "true" or "false"; any other bool attribute is there while true.
func BindValue ¶ added in v1.0.0
BindValue is the attributes of <input bind:value={p.Q}>, field a pointer to a field of the struct owner points to: the field's value as the input's, and an onInput setting the field to what is typed, after the field's debounce, validated as a set of a bound field is. The field is bound by its owner's LiveSchema (l.Field(&p.Q, ui.Bind{})) or a bind: tag; any other is an error at render.
type Badge ¶ added in v0.15.0
type Badge struct {
// Variant is the tone: Default, Primary, Success, Danger, Warning or Info.
Variant Variant
// Soft tints the badge (a light background with coloured text) instead of
// filling it.
Soft bool
Class string
Children Node
}
Badge is a small status pill:
<ui.Badge variant={ui.Success}>Signed</ui.Badge>
<ui.Badge variant={ui.Danger} soft>Failed</ui.Badge>
type BadgeProps
deprecated
added in
v0.15.0
type BadgeProps = Badge
BadgeProps is Badge, by its former name.
Deprecated: use Badge: ui.Badge{…}, or <ui.Badge …> in a template.
type Bind ¶ added in v0.24.0
Bind lets the component set the field (live.q.set(v)); a set waits Debounce for more before it is sent: DefaultDebounce when zero, no time when negative.
func (Bind) Apply ¶ added in v1.0.0
func (b Bind) Apply(o *FieldOptions)
type Binding ¶ added in v0.24.0
type Binding struct {
Init any // its value, as rendered
Expr string // its expression: JSON, with deps as {"$": i}
Deps []any // the states it reads, and the server's values it uses
}
Binding is a JSX expression that reads states: an attribute's value (hidden={!open}), a child ({count}), a ui.Show's when. The compiler writes it as BindExpr; the page renders it with the value Init, and the browser evaluates it again whenever a state it reads changes.
func BindExpr ¶ added in v1.0.0
BindExpr is a binding of an expression of states, as the compiler writes hidden={!open}: BindExpr(!open.Get(), `["!",{"$":0}]`, open).
The expression is JSON: a literal (a string, number, bool or null), a dep {"$": i} — a state, with "p" naming a field path, or a value of the server's — or an operation ["op", operands…]: "!", "neg", "&&", "||", "==", "!=", "<", "<=", ">", ">=", "+", "-", "len", or "class" over an object of class names and expressions.
type Boundary ¶
Boundary renders Children or, when one of them fails, Fallback(err) in place of everything they produced.
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.
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 Button ¶ added in v0.15.0
type Button struct {
// ID names the element, e.g. for a JS command to target it.
ID string
// Variant is the tone: Default, Primary, Success, Danger, Warning, Info or
// Ghost.
Variant Variant
// Size is SizeMd (default), SizeSm or SizeLg.
Size Size
// Icon is an optional icon shown before the label, e.g. ui.Icon("plus").
Icon Node
// IconOnly drops the label's spacing for a square icon button; give it a
// Title for its accessible name.
IconOnly bool
// Loading forces the busy state: a spinner in place of the icon, and the
// button disabled. A live button left to its own busy state (see On) needs
// nothing here — it goes busy while its event is in flight.
Loading bool
// Disabled renders the button disabled.
Disabled bool
// Type is "button" (default), "submit" or "reset".
Type string
// Form is the id of the form a submit button submits when it sits outside
// it.
Form string
// On is what a click does: a ui.JS chain or a live event handler (a func,
// as an on… attribute takes). A live click goes busy until its reply, so a
// click button shows the spinner on its own.
On any
// Href makes the button a link (an a element). Nav follows it over a live
// connection (ui.Link's navigation) instead of a full load.
Href string
// Title is the element's title/tooltip and, for an icon-only button, its
// accessible name.
Title string
Class string
// Attrs are any extra attributes.
Attrs []Attr
Children Node
}
Button is a token-styled button, or a link when Href is set:
<ui.Button variant={ui.Primary} icon={ui.Icon("plus")}>New</ui.Button>
<ui.Button on={c.Save}>Save</ui.Button> // spins while saving
<ui.Button href="/books" nav>Back</ui.Button>
A click handler (On) goes busy until its reply, so the spinner shows itself; Loading forces it for a server-controlled state.
type ButtonProps
deprecated
added in
v0.15.0
type ButtonProps = Button
ButtonProps is Button, by its former name.
Deprecated: use Button: ui.Button{…}, or <ui.Button …> in a template.
type Card ¶ added in v0.15.0
type Card struct {
// Title is the header's left content; a string becomes a heading, any
// other Node is placed as is.
Title Node
// Header is the header's right slot, for actions (ui.Actions) or a badge.
Header Node
// NoPad drops the body's padding, e.g. for a flush DataTable.
NoPad bool
Class string
Children Node
}
Card is a bordered surface with an optional header (a title on the left, actions on the right) and a body:
<ui.Card title={ui.Text("Members")}>
<slot:header><ui.Button variant={ui.Primary}>Invite</ui.Button></slot:header>
{table}
</ui.Card>
or in Go, ui.Card{Title: ui.Text("Members"), Children: table}.
type Changed ¶ added in v0.30.0
type Changed struct {
// contains filtered or unexported fields
}
Changed is what a set of the component changed, as the page's OnChange hook gets it: the bound fields the set holds.
type Checkbox ¶ added in v0.15.0
type Checkbox Field
Checkbox is a single boolean field; its label sits beside the box.
type Class ¶ added in v0.24.0
Class is a class attribute of names switched on and off: each name (or space-separated names) is there when its value is true. Its values may read states: class={ui.Class{"bg-brand": tab == "env"}}.
type Classes ¶ added in v1.0.0
Classes is a class attribute whose names may be switched by states: each value a bool or a bool state (ui.Class holds bools only).
class={cls} // cls := ui.Classes{"menu": true, "is-open": open}
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
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
DismissToastRef hides the toast named ref.
func OpenModal ¶ added in v0.14.0
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
ScrollTo scrolls the page until target is in view.
Example:
<button onClick={ui.JS.ScrollTo(ui.Ref("comments"))}>Comments</button>
func (Commands) Set ¶ added in v0.24.0
Set is the command setting state s to v, which must be of its type (a number converts to a number state's type).
Example:
<button onClick={tab.Set("env").Set(open, false)}>Environment</button>
func (Commands) SetAttr ¶ added in v0.2.0
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
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
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
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
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
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
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) Set ¶ added in v0.24.0
func (o CommandsOn) Set(s AnyState, v any) CommandsOn
Set is the command setting state s to v (see Commands.Set); the target plays no part.
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 ¶
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.
A tag sets its props on the instance each time it renders: a parent owns the exported fields of the components it renders. A routed page's tag (Routed, what web.Live renders) has no parent: the page owns its exported fields once mounted, so the tag rendered again sets none of them, and a new tag in its place, a patch to another URL of the route, sets only URL, the fields its URL binds.
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 (Condition) Not ¶ added in v0.9.0
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>
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 DataTable ¶ added in v0.14.0
type DataTable[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 RowSelected func(T) bool OnSelect func(T) any OnSelectAll any AllSelected bool SomeSelected bool // Index adds a row-number column numbered from the page's first row. Index bool Empty Node EmptyIcon Node // Flush drops the table's border so it sits flush in a Card. Flush bool Class string // Toolbar is extra controls shown in the bar beside the search box // (filters, a "New" button). Toolbar Node // Tabs, when set, are shown in the bar above the table. Tabs 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 columns={cols} page={p.page.Get()} search={p.query.Get()}
onSearch={p.Search} onSort={p.SortBy} onPage={p.GoTo}/>
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 DataTableProps
deprecated
added in
v0.14.0
type Defer ¶ added in v1.0.0
type Defer string
Defer leaves the field out of the page's first render: the group it names loads it after, by the loader LiveSchema's Loads gives the group.
func (Defer) Apply ¶ added in v1.0.0
func (d Defer) Apply(o *FieldOptions)
type DeferredLoad ¶ added in v0.30.0
type DeferredLoad struct {
Group string
// contains filtered or unexported fields
}
DeferredLoad is a deferred group of a page, started: Run loads it on a copy of the page taken when it started, on any goroutine; Apply, where the page's events run, gives the page the group's fields, or records the loader's error for them.
func StartDeferred ¶ added in v0.30.0
func StartDeferred(c Stateful) []*DeferredLoad
StartDeferred starts the deferred groups of c, a live page backed by its island, not started yet (none when c is no such page): package live runs each once the page joins, and applies it where its events run.
func (*DeferredLoad) Apply ¶ added in v0.30.0
func (d *DeferredLoad) Apply(text func(error) string)
Apply gives the page what Run loaded, or records its error: text, when not nil, is the error's message for the browser (else ErrorOf's).
func (*DeferredLoad) Err ¶ added in v0.30.0
func (d *DeferredLoad) Err() error
Err is what Run returned.
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 ¶
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.
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"`
Data json.RawMessage `json:"data,omitempty"` // an island emit's payload (arbitrary JSON)
}
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.
type Field ¶ added in v0.15.0
type Field struct {
// Name is the control's name, matching the form struct's form: tag.
Name string
// Label is shown above the control; omitted when empty.
Label string
// Type is the HTML input type ("text" default, "email", "number", "date",
// "time", "url", "tel"); the dedicated kinds set it for password,
// textarea, select and checkbox.
Type string
// Value is the control's value; for a checkbox, "true" ticks it.
Value string
// Options are a select's choices.
Options []Option
// Error is the field's message; when set the control is marked invalid.
// The host supplies it (its own validation), since ui does not import the
// runtime that tracks errors.
Error string
// Help is a hint shown under the control.
Help string
Placeholder string
Required bool
Disabled bool
// Rows is a textarea's height; 3 when 0.
Rows int
// Min, Max and Step bound a number or date control.
Min, Max, Step string
Autocomplete string
Class string
// Attrs are extra attributes on the control.
Attrs []Attr
// contains filtered or unexported fields
}
Field is a form field: its control, label, help and error. It renders the control its Type names, an HTML input type ("text" by default); Input, Password, Textarea, Select and Checkbox are the fields of each kind:
<ui.Field name="age" label="Age" type="number" min="18"/> <ui.Input name="email" label="Email" type="email" required/>
type FieldAttr ¶ added in v1.0.0
type FieldAttr interface{ Apply(*FieldOptions) }
A FieldAttr configures a live page's field: Bind, URL, Defer, and the rules of package validate. Attributes apply in order, a later one's set members over an earlier one's.
type FieldOptions ¶ added in v1.0.0
type FieldOptions struct {
Bind bool // the component may set it
Debounce time.Duration // how long a set waits for more before it is sent
URL string // the query parameter the page's address keeps it in
Defer string // the group it loads in after the first render
Validate []string // rules, as a validate tag writes them: "required", "max=50"
}
FieldOptions is what a page's field attributes say of it.
func FieldOptionsOf ¶ added in v1.0.0
func FieldOptionsOf(t reflect.Type, f reflect.StructField) FieldOptions
FieldOptionsOf is what the page t's LiveSchema says of its field f: zero when it says nothing. Package web reads a field's URL from it.
type FieldProps
deprecated
added in
v0.15.0
type FieldProps = Field
FieldProps is Field, by its former name.
Deprecated: use Field, or the kind of field: ui.Input{…}, or <ui.Input …> in a template.
type Form ¶ added in v0.15.0
type Form struct {
ID string
// OnSubmit runs when the form is submitted; over a live connection it
// receives the fields bound to its struct, and the form shows its busy
// state until the reply.
OnSubmit any
// OnChange runs as fields change (oninput), for live validation; leave it
// nil for none.
OnChange any
// Method and Action are the plain-HTML fallback for a form that posts
// without a live connection; Method defaults to "post".
Method string
Action string
// Error is a form-level message shown as a danger Alert above the fields.
Error string
// CSRF is an optional hidden token field. Vuka's CSRF is origin-based
// (net/http's CrossOriginProtection), so a form needs no token by default
// and this is usually nil.
CSRF Node
Class string
Children Node
}
Form is a token-styled form wired for live submit and change handlers:
<ui.Form onSubmit={p.Save} error={p.formError}>
<ui.Input name="name" label="Name" value={p.name} required error={p.errs["name"]}/>
<ui.Password name="password" label="Password" required/>
<ui.Submit>Save</ui.Submit>
</ui.Form>
A live OnSubmit gets the fields bound to its struct (their name attributes match the struct's form: tags); without a connection the form posts to Action as ordinary HTML.
The On… handlers are live event handlers (a func taking a form:-tagged struct, as an on… attribute takes) or ui.JS chains, passed the same way DataTable takes its handlers — the ui library is imported by the web runtime, so it never imports it back, and a form's errors are supplied by the host (see Field.Error and Form.Error) rather than read from the runtime.
type Frame ¶
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.
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) 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 Image ¶ added in v0.23.0
type Image struct {
Src string
Srcset string
Sizes string
Alt string
Width int
Height int
// Class is added to the <img> (sizing, rounding, the caller's utilities).
Class string
// Priority marks the page's largest image: it loads eagerly with a high
// fetch priority. Use it once per page.
Priority bool
// Eager loads an above-the-fold image immediately, without raising its
// priority. Leave both off for below-the-fold images (the default lazy).
Eager bool
// Plain drops the placeholder, for a transparent image (a logo) the
// shimmer would show through.
Plain bool
// Overlay is content laid over the image, which then acts as a backdrop.
Overlay Node
// Scrim darkens the bottom of the image under the Overlay so text on it
// stays legible over any picture.
Scrim bool
// WrapClass is added to the positioning wrapper the Overlay needs.
WrapClass string
}
Image is a network-friendly <img>: lazy, responsive, reserved and decoded off-thread, with a shimmer placeholder. With Overlay set it wraps the image as a backdrop for content laid over it:
<ui.Image src="/hero.webp" srcset={set} sizes="100vw" width={1600} height={600}
priority scrim overlay={heading}/>
The defaults suit a slow network: the image lazy-loads, reserves its box from Width/Height so nothing shifts while it streams in, decodes off the main thread, and shows a shimmer placeholder until it paints.
type ImageProps
deprecated
added in
v0.23.0
type ImageProps = Image
ImageProps is Image, by its former name.
Deprecated: use Image: ui.Image{…}, or <ui.Image …> in a template.
type Input ¶ added in v0.15.0
type Input Field
Input is a single-line text field (Type sets the HTML input type):
<ui.Input name="email" label="Email" type="email" required/>
type Invalid ¶ added in v0.28.0
Invalid is the error Validate answers with: each field's path → its message.
func (Invalid) FieldErrors ¶ added in v0.28.0
func (Invalid) PublicMessage ¶ added in v0.28.0
func (Invalid) StatusCode ¶ added in v0.28.0
type IslandDecorator ¶ added in v1.0.0
IslandDecorator is what Island returns: a type decorator, which registers the type it is given as an island, and an option of a route serving the type as a page backed by its island, which applies it to the page's type.
func Island ¶ added in v0.19.0
func Island(args ...any) IslandDecorator
Island is the @ui.Island type decorator. Above a struct type it registers that type as an island whose props are its exported fields, as RegisterIsland does in Go. Written bare, the vuka command finds the component as islands/[<module>/]<Type>.<ext> under the frontend root; @ui.Island("islands/Chart.vue") names it instead. The framework is inferred from the file extension (.vue, .tsx/.jsx, .svelte, else vanilla .ts/.js).
After the path come options: Strategy, the default hydration strategy used when a tag gives no client:* directive, and Layout, the layout of the page the type backs when it is routed as one (@web.Live, @web.Get):
@ui.Island(ui.Layout(layouts.Page("Orders")))
@ui.Island("islands/Chart.vue", ui.Strategy("load"))
A second string is a strategy too: @ui.Island("", "load").
Beside a route decorator (@web.Live, @web.Get) it is the route's option, as in Go: app.Live("/board", NewBoard, ui.Island(ui.Layout(page))).
func (IslandDecorator) Attrs ¶ added in v1.0.0
func (d IslandDecorator) Attrs() []any
Attrs makes the decorator a route's option: it is its one attribute.
type IslandError ¶ added in v0.25.0
type IslandError struct {
Status int `json:"status,omitempty"`
Message string `json:"message"`
Fields map[string]string `json:"fields,omitempty"`
}
IslandError is a failed call as the component's live.error reads it: a status, a message and, for an error naming fields (FieldErrors), each field's message. An error that isn't public (PublicMessage) shows as "error".
func ErrorOf ¶ added in v0.25.0
func ErrorOf(err error) *IslandError
ErrorOf is err as the component reads it.
type IslandField ¶ added in v0.26.0
type IslandField struct {
Handle string // the wire name, first letter lower-cased
Wire string // the prop's key: its json name, else the Go name
Index int
Type reflect.Type
Bind bool // bind: the component may set it
Debounce time.Duration // how long a set waits for more before it is sent
Defer string // defer: the group it loads in after the first render; "" when it doesn't
// contains filtered or unexported fields
}
IslandField is a prop of a page-backed island as its component reads it through useLive(): live.<Handle>.get(), .value, and .set(v) when Bind.
func IslandFields ¶ added in v0.26.0
func IslandFields(t reflect.Type) ([]IslandField, error)
IslandFields are the props of t (an island's struct, or a pointer to one) that get a handle: the exported fields that are plain values — not the slot, a function, a JS chain or a state. A field tagged bind:"name" is bound; name is its handle (or its wire name), debounce=500 (milliseconds, or a duration: 1s) sets its wait.
type IslandMethod ¶ added in v0.25.0
type IslandMethod struct {
Name string
Method reflect.Method
Args []reflect.Type
// contains filtered or unexported fields
}
IslandMethod is an exported method of a page-backed island that its component may call: its wire name (the method's, first letter lower-cased) and its arguments' types (a leading context.Context and an error result left out).
func IslandMethods ¶ added in v0.25.0
func IslandMethods(t reflect.Type) []IslandMethod
IslandMethods are the methods of t (a pointer to an island's struct) its component may call: the exported ones that aren't a live component's lifecycle (Render, Mount, Update, Info) or ui.Live's, return nothing or an error (or a value and an error), and take JSON arguments.
func (IslandMethod) Call ¶ added in v0.25.0
func (m IslandMethod) Call(ctx context.Context, x reflect.Value, args json.RawMessage) error
Call calls the method on x (a pointer to the island's struct) with args as the JSON array the component sent. Each argument is validated first (Validate): a struct's fields are named by their own paths (years, level.code), a slice's by index (0.code); any failing, the method doesn't run and Call answers Invalid.
type IslandOpt ¶ added in v0.19.0
type IslandOpt func(*islandConfig)
IslandOpt configures a MountIsland call: a hydration strategy, a slot, or a fallback. The transpiler emits these from a tag's client:* directive, its children, and a <ui.Template fallback>.
func CallAt ¶ added in v0.25.0
CallAt makes a page-backed island's methods calls to url, a stateless page's: the component posts the method, its arguments and its props with sig (the server's signature of them) and is updated with the props the call leaves. Package web writes it.
func Callback ¶ added in v0.25.0
Callback passes a function prop: prop is its wire name (onSelect), fn a live view method or other handler (calling the function in the browser pushes it, with the function's first argument as its payload) or a JS chain (calling it runs the commands). The compiler writes it for an attribute of a function-typed prop: <Chart onSelect={p.Zoom}/>.
func ClientOnly ¶ added in v0.19.0
func ClientOnly() IslandOpt
ClientOnly never server-renders the island (client:only): the fallback shows until the client mounts it fresh.
func Emit ¶ added in v0.21.0
Emit binds one of the island component's emits to a live-view handler: the transpiler emits it for an on<Emit> attribute on the tag. When the mounted component emits name, the handler runs on the server with the emit's payload (a struct/*T handler param is bound from the emitted JSON). handler is an On-style value (a func, usually a view method).
func Fallback ¶ added in v0.19.0
Fallback sets what shows until the island hydrates (and the SSR target under SSR). Distinct from the component's Slot.
func Idle ¶ added in v0.19.0
func Idle() IslandOpt
Idle hydrates on requestIdleCallback (client:idle).
func IslandErr ¶ added in v0.25.0
func IslandErr(err *IslandError) IslandOpt
IslandErr shows err as the island's last failed call (data-vk-err).
func Load ¶ added in v0.19.0
func Load() IslandOpt
Load hydrates the island immediately on page load (client:load).
func Once ¶ added in v0.25.0
func Once() IslandOpt
Once keeps the island's props as first rendered: a live re-render whose props changed doesn't update the mounted component (the once attribute on a tag). Without it an island is live: changed props reach the component's update, with no remount.
func SSR ¶ added in v0.19.0
func SSR() IslandOpt
SSR opts the island into a server-rendered initial HTML via the build's SSR sidecar (server:defer); the client then hydrates it. Phase 4.
func Slot ¶ added in v0.19.0
Slot sets the island's slot — the component's own children, handed to the framework on mount. Distinct from a Fallback.
func StateProp ¶ added in v0.25.0
StateProp passes a client state as a prop: the component gets its value, is updated when it changes, and its writes (a Vue model's update:<prop>, a React set<Prop>, a Svelte $bindable) set the state — and whatever reads it on the page. A ui.Derived is passed one way. The compiler writes it for a ui.State attribute of an island tag: <Counter count={n}/>.
type IslandOption ¶ added in v0.29.0
type IslandOption interface {
// contains filtered or unexported methods
}
IslandOption is an option of @ui.Island: Layout or Strategy.
func Layout ¶ added in v0.29.0
func Layout(layouts ...any) IslandOption
Layout is the layout of the page an @ui.Island type backs, when it is routed as one (@web.Live, @web.Get): the page is layout(component). Placed in another page, the island ignores it. A layout is a func(page ui.Node) ui.Node or a func(ctx context.Context, page ui.Node) ui.Node — a LayoutFunc, which reads the request. Several nest, the first outermost: Layout(document, shell) is document(shell(component)).
It wins over the route's web.Layout and the app's web.LiveLayout.
func Strategy ¶ added in v0.29.0
func Strategy(s string) IslandOption
Strategy sets an island's default hydration strategy, used when a tag gives no client:* directive: "load", "idle", "visible" (the default), "media" or "only".
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 LayoutFunc ¶ added in v0.29.0
LayoutFunc is a layout reading the request: the signed-in user, the path (from ctx, as a page's code reads them), the page's title (PageTitle).
func IslandLayout ¶ added in v0.29.0
func IslandLayout(t reflect.Type) LayoutFunc
IslandLayout is the layout @ui.Island's Layout gives the page t (an island's struct, or a pointer to one) backs: nil when it gives none.
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 ¶
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) Loads ¶ added in v1.1.0
Loads sets the loader of the deferred group from the page's constructor, a method expression as OnMount takes: (*Dashboard).loadLists.
func (*Live) OnChange ¶ added in v1.1.0
OnChange sets the hook that runs after the component sets bound fields, from the page's constructor: a method expression taking the page and optionally a context.Context and a Changed, returning nothing or an error.
func (*Live) OnMount ¶ added in v1.1.0
OnMount sets the page's mount hook from its constructor: a method expression, (*Login).mount, taking the page and optionally a context.Context, returning nothing or an error. It runs as LiveSchema's Mount does.
func NewLogin() *Login {
l := &Login{}
l.OnMount((*Login).mount)
return l
}
The hook is an unexported method: the browser calls the page's exported ones. The hooks are the page type's: the first instance to declare one sets it, and an instance declaring another for the same type is an error (E0336). A page built without its constructor has the hooks its type already set.
func (*Live) PushEvent ¶ added in v0.7.0
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
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
PushNavigate moves the page to href once the reply to the current event (or message) is applied, as JS.Navigate does.
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 ¶
LiveInstance is a session's side of a component instance. Package live implements it.
type LiveSchema ¶ added in v1.0.0
type LiveSchema struct {
// contains filtered or unexported fields
}
LiveSchema is what a live page declares beyond its Go types: attributes of its fields and the hooks the runtime calls, as values. A page declares them in a LiveSchema method:
type Dashboard struct {
ui.Live
Q string
Rows []Task
Total int
}
func (d *Dashboard) LiveSchema(l *ui.LiveSchema) {
l.Field(&d.Q, ui.Bind{Debounce: 300 * time.Millisecond}, ui.URL("q"), validate.Max(100))
l.Field(&d.Rows, ui.Defer("lists"))
l.Field(&d.Total, ui.Defer("lists"))
l.Loads("lists", d.loadLists)
l.OnChange(d.changed)
l.Mount(d.mount)
}
A field is named by its address, so a rename is checked by the compiler, and a hook by its method value, so its signature is. The runtime calls LiveSchema on each page it runs: the hooks are that page's methods. They may be unexported; a page's exported methods are what its component calls, the hooks excepted.
In Vuka the same values are attributes: Q string @ui.Bind{…} @ui.URL("q") on the field, @ui.Mount, @ui.OnChange and @ui.Loads("lists") on the method; the compiler writes the LiveSchema method.
func (*LiveSchema) Field ¶ added in v1.0.0
func (l *LiveSchema) Field(ptr any, attrs ...FieldAttr)
Field adds attributes to the field ptr points to, one of the page's own fields.
func (*LiveSchema) Loads ¶ added in v1.0.0
func (l *LiveSchema) Loads(group string, fn func(ctx context.Context) error)
Loads sets the loader of the deferred group: it runs after the page's first render, on a copy of the page, and sets the group's fields.
type Loads ¶ added in v0.30.0
type Loads struct {
// contains filtered or unexported fields
}
Loads is the state of a page's deferred groups: loading, loaded, or failed with the error its component reads (live.stats.error).
func LoadsFrom ¶ added in v0.30.0
LoadsFrom is the state of the deferred groups of t (an island's struct) whose page was rendered with props, its props JSON: a group whose fields it holds is loaded. A stateless page keeps it in its signed props.
func (*Loads) JSON ¶ added in v0.30.0
JSON is the page's data-vk-defer for t: the wire names still pending ("p") and each failed field's error ("e"); nil when t defers nothing.
type Modal ¶ added in v0.14.0
type Modal 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
// Icon is an optional icon shown in a tile before the title, e.g.
// ui.Icon("check-circle").
Icon Node
// Subtitle is optional muted text under the title.
Subtitle string
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", "" / "md" (default), "lg" or "xl".
Size string
Class string
Children 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 ref="edit" title={ui.Text("Edit")}>…</ui.Modal>
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 ref="edit" open={m.open} onClose={m.Close}>…</ui.Modal>
Opening traps focus (PushFocus then FocusFirst); closing restores it (PopFocus). Escape and a backdrop click close a dismissible modal.
type ModalProps
deprecated
added in
v0.14.0
type ModalProps = Modal
ModalProps is Modal, by its former name.
Deprecated: use Modal: ui.Modal{…}, or <ui.Modal …> in a template.
type Node ¶
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 Actions ¶ added in v0.15.0
Actions is a right-aligned row of buttons, for a modal footer or a card header:
{ui.Actions(ui.Cancel(m.Close), ui.Button{Variant: ui.Primary, On: m.Save, Children: ui.Text("Save")})}
func Cancel ¶ added in v0.15.0
Cancel is a neutral button that dismisses a modal or form. On is what it does: a ui.JS chain (ui.CloseModal) or a live handler. The label is "Cancel" unless the first label is given.
func Child ¶
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 Ctx ¶ added in v1.0.0
Ctx is the node build makes of the context it is rendered with, there: a tag of a component taking ctx first, <Admin title="x"/> for func Admin(ctx context.Context, p AdminProps), is ui.Ctx(func(ctx context.Context) ui.Node { return Admin(ctx, p) }). It renders, diffs and keys as that node does. build runs for each render with its current context; do not retain that context in component state or mutate application state while rendering. Live components that evaluate Ctx are not skipped based only on props and Assigns: their output can also depend on identity, permissions or locale. Context values are server-side until build explicitly renders them.
func Each ¶ added in v1.0.0
Each is a list of what fn makes of each item, as a {for} block is: under a live session its items diff by their keys (a key attribute on an item's first element, or ui.Key on a component).
ui.Each(orders, OrderRow)
func ErrorBoundary ¶
ErrorBoundary renders children, or — when one of them fails — fallback(err) in place of everything they wrote.
func FT ¶ added in v0.13.0
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 HTML ¶ added in v1.0.0
HTML is src, markup with labelled holes, filled with args: one value for each label, in the order the labels first appear. A label is the Go expression its value is written as, so the call reads like the markup:
func OrderRow(o Order) ui.Node {
return ui.HTML(`
<tr key={o.ID} class="row" class:late={o.Late}>
<td>{o.Ref}</td>
<td class="tabular-nums">{o.Total | money}</td>
</tr>`, o.ID, o.Late, o.Ref, o.Total)
}
src is parsed once, on its first render, and kept: write it as a constant. A hole takes what its place allows, and a value of another kind fails the render naming the hole and its line:
- a child, between tags, {x}: a Node, []Node (a list, like ui.Each), a string or number (escaped text), an error (its message), nil (nothing), a ui.State (its value, kept current by the browser), a stateful component (&Counter{…}, or ui.Key(k, &Counter{…})), an island's props (Chart{…}, or ui.Mount(Chart{…}, opts…));
- text, inside title or textarea: a string or number;
- an attribute's value, class={x} or class="{x}": what a JSX attribute takes — a string, number, bool (false omits it, true writes it bare), nil, a ui.Class, ui.Classes or ui.Style on class and style, a ui.State (an expression of states too: open.Not()); an on… attribute takes a handler (a func, ui.On(…), JS commands);
- part of a value, href="/orders/{id}": a string or number;
- an attribute set, <input {attrs...}>: a ui.Attr, []ui.Attr or templ.Attributes (ui.BindAttr gives one);
- a toggled class, class:active={on}: a bool or a ui.State[bool].
A label appearing twice is one value. Blocks are Go producing nodes — ui.Each, ui.If, a []ui.Node — and components their calls, each in a hole: {rows}, {ui.Card{Title: t}}. {/* … */} is a comment.
The markup is strict: every element is closed (<br> and the other void elements need not be, and <x/> closes any), names are letters, digits and - _ : . and holes can't name a tag or an attribute, or sit in a comment. {{ is a literal {; inside script and style braces are text. Text follows JSX: lines are trimmed where they meet a line break and blank lines dropped, so indentation adds nothing; inside pre and textarea it is kept as written. Entities in text and attribute values are decoded and escaped again on output. A mistake fails the render, naming the line.
func Icon ¶ added in v0.15.0
Icon renders a named icon from the built-in set as an inline SVG, coloured with the current text colour. An extra class or two can be passed. An unknown name renders an empty SVG marked with the name, so a typo shows up in tests rather than silently vanishing.
func If ¶ added in v1.0.0
If is n when cond holds, else nothing, as an {if} block is. n is built either way; when it can only be built while cond holds, use a Go if.
func IslandPage ¶ added in v0.25.0
IslandPage is the markup of a page backed by its island: x (a pointer to the @ui.Island struct) mounted on load, its methods bound for its component — on a live page, each a handler the live session runs, and one for the component's sets of bound fields — its fields' handles (data-vk-fields) and the last failed call's error (data-vk-err).
func JSON ¶ added in v1.0.0
JSON is v as JSON for a script: {json(v)} in an inline script. Marshal's escaping of <, > and & keeps it from ending the script.
func Key ¶ added in v1.0.0
Key is a stateful component with a key, as a key attribute on its tag is: the instances in one place are told apart by their keys, unkeyed ones by their order.
ui.Each(items, func(it Item) ui.Node { return ui.Key(it.ID, &Counter{Label: it.Name}) })
func Link ¶ added in v0.4.0
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 Mount ¶ added in v1.0.0
Mount is an island placed with options: in a template's child hole, ui.HTML(`<div>{chart}</div>`, ui.Mount(Chart{Points: pts}, ui.Idle(), ui.Fallback(spinner))). The hole gives it its site; props alone, with no options, mount the same.
func MountIsland ¶ added in v0.19.0
MountIsland renders the <vk-island> host the client loader hydrates. The transpiler emits it for a tag whose type carries @ui.Island; site is a stable id for the island's placement (the live-view diff and ctx.ref rely on it not changing across renders), and props is the type's value (its exported fields are serialized as JSON for the client).
func ResolveContext ¶ added in v1.4.0
ResolveContext evaluates leading Ctx nodes with this render's context. Renderers use it before inspecting a root, preserving frame trees and root attributes. A live host can implement ContextRead() to prevent state-only reuse of output that depends on context. No context is retained in the node.
func RootAttrs ¶
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 Show ¶ added in v0.24.0
Show renders its children always, and shows them in the browser only while When holds, as Vue's v-show does. They are in a <vk-show> element (display: contents), hidden while When doesn't hold.
Transitions are the children's CSS: while hidden they have data-closed; appearing, data-enter; disappearing, data-leave; and they are hidden once their transitions or animations end. With Tailwind:
<ui.Show when={open}>
<div class="transition duration-150 data-closed:opacity-0 data-leave:duration-100">…</div>
</ui.Show>
A child with the popover attribute is shown with showPopover, in the top layer, and hidden with hidePopover, with the same phases.
func Spinner ¶ added in v0.15.0
func Spinner() Node
Spinner is the busy indicator Button and the form controls use: a spinning ring drawn in CSS, so it needs no script.
func States ¶ added in v1.0.0
States are a component's states as its script reaches them — ctx.state("open") — each ui.State field of the struct v (or *v), exported or not, by its json name or its name with its first letter lower-cased: a reference to the state the browser keeps. Nil when v has none. A template whose script calls ctx.state writes it on its root as data-vk-s.
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 Template ¶ added in v0.19.0
Template marks a named region slot inside a <ui.Island> wrapper — e.g. <ui.Template fallback>…</ui.Template> gives the island's pre-hydration fallback. The transpiler consumes these tags (they render no element of their own); this declaration only lets the tag resolve. Calling it directly renders nothing.
func TileGrid ¶ added in v0.15.0
TileGrid lays tiles out in a responsive grid (four across on a wide screen, collapsing to two then one):
ui.TileGrid(tileA, tileB, tileC, tileD)
func WithChildren ¶
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 Option ¶ added in v0.15.0
type Option struct{ Value, Label string }
Option is one choice of a Select.
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
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]) From ¶ added in v0.14.0
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
To is the 1-based number of this page's last item; 0 when the page has no items.
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
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 Password ¶ added in v0.15.0
type Password Field
Password is a masked text field.
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 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
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) 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) 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) 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.
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 Select ¶ added in v0.15.0
type Select Field
Select is a dropdown over Options.
type Setter ¶ added in v1.0.0
Setter is the handler of a bind:value input: it sets a page's bind: field as SetBound does. Package live renders the page again after it, and keeps what it set as the page's props.
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 ShowProps ¶ added in v0.24.0
ShowProps are what Show takes: When, a bool, a State[bool] or an expression of states (the compiler writes a Binding), and the children it shows.
type State ¶ added in v0.24.0
type State[T any] struct { // contains filtered or unexported fields }
State is a value the browser keeps: a menu's open flag, the tab picked, a filter's text. Commands change it at once, with no round trip, and the parts of the page that read it follow.
In a .vuka file, ui.State(v) declares one; the compiler gives each declaration its place, so two components using the same variable name never share a state. Declared in a component's function it is that instance's own (a component rendered ten times has ten); declared at package level it is the page's, one value every component reads.
open := ui.State(false)
<button onClick={open.Toggle()} aria-expanded={open}>Menu</button>
<ul hidden={!open}>…</ul>
Writes are commands, chained with the rest of ui.JS: Set, Toggle (a State[bool]), Inc and Dec (numbers), Reset. Reads are expressions the browser evaluates: in JSX attributes, text and ui.Class, plain Go expressions the compiler writes with State's methods (open.Not(), tab.Eq("env"), see Not); the server renders them with the initial value, so the page is right before any script runs.
A struct state's fields are states of their own: f.Q.Set("x") changes one field, and what reads f.Q follows only f.Q. A state passed as a prop is the same state; Get passes its value.
The server knows a state's initial value only (Get); what the browser changed stays in the browser. A component pushes changes with PushJS: c.PushJS(tab.Set("env")).
func At ¶ added in v1.0.0
At is the field at path (Go field names, dotted) of a struct state: a state of its own, which Set writes alone and what reads it follows alone, as f.Q is in a .vuka file.
q := ui.At[string](f, "Q") hi := ui.At[int](f, "Range.Hi")
func Derived ¶ added in v0.24.0
Derived names an expression of states for reuse, read wherever a state is: in a .vuka file, ui.Derived(!open && tab == "env"), which the compiler writes as open.Not().And(tab.Eq("env")). In Go, Derived(v) is a state that never changes: an operand for an expression starting with a value, ui.Derived("Hello, ").Plus(name).
func NewDerived ¶ added in v0.24.0
NewDerived is a derived state: value is what it renders with, expr and deps its expression, as BindExpr takes them.
func NewState ¶ added in v0.24.0
NewState is a state declared at site, a name unique in the program: what ui.State(initial) in a .vuka file becomes. Each value NewState returns is a state of its own; the browser knows it by site, the component instance rendering it and how many of site's states that instance rendered before.
func PageState ¶ added in v0.24.0
PageState is a state the whole page shares, declared at site: what a package-level ui.State(initial) becomes. Every component reading it reads one value.
func StateField ¶ added in v0.24.0
StateField is the field name of a struct state, sample its value as rendered (f.Get().Q), which also gives its type. At is the same with the type named: At[string](f, "Q").
func UsePageState ¶ added in v1.0.0
UsePageState is a state the whole page shares, declared where it is called: what a package-level ui.State(initial) is in a .vuka file.
var theme = ui.UsePageState("light")
func UseState ¶ added in v1.0.0
UseState is a state declared where it is called, what ui.State(initial) in a component's function is in a .vuka file: each component instance rendering it has its own.
open := ui.UseState(false)
func (State[T]) Get ¶ added in v0.24.0
func (s State[T]) Get() T
Get is the state's value as the server renders it: its initial value. Passed as a prop, it gives the child the value rather than the state.
func (State[T]) Inc ¶ added in v0.24.0
Inc is the command adding one to a number state; Dec subtracts one. The compiler refuses them on any other state.
Example:
<button onClick={n.Inc()}>+</button>
func (State[T]) Reset ¶ added in v0.24.0
Reset is the command setting the state back to its initial value.
Example:
<button onClick={f.Reset()}>Clear filters</button>
type StateHost ¶ added in v0.24.0
StateHost names the states rendered under a live host: package live's scope keys them by the instance rendering them. A host that isn't one keys them by site and a counter.
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.
type Style ¶
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 Submit ¶ added in v0.15.0
type Submit Button
Submit is a form's submit button: the Button in its primary variant, type submit. It shows its busy state while the live form waits for the submit's reply. Set Form to submit a form it sits outside (a dialog footer):
<ui.Submit>Save</ui.Submit>
type Tab ¶ added in v0.15.0
type Tab struct {
Label string
// Icon is an optional named icon before the label, e.g. "users".
Icon string
// Count, when set, shows as a badge beside the label (see ui.Count).
Count *int
// Href makes the tab a link. Patch asks the live page to re-bind the same
// route with the new URL rather than mount afresh.
Href string
Patch bool
// On is a live event handler the tab calls when it has no Href.
On any
// Active marks the current tab.
Active bool
ID string
}
Tab is one tab of a Tabs bar. It is driven either by Href (navigation) or by On (a live event handler); set one.
type Table ¶ added in v0.14.0
type Table[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. With OnSelect the boxes are // live (ticked by RowSelected, toggled through OnSelect); without it they // are plain form checkboxes named SelectName (default "selected") with the // row's RowKey as value, for a form or handler to read. Selectable bool SelectName string // RowSelected is a live checkbox's ticked state, and highlights the row. RowSelected func(T) bool // OnSelect is the live handler a row's checkbox calls on change; it // receives the row and returns the handler to run. The checkbox fires // onChange with its new ticked state, so the returned handler should take // that bool (func(ctx, bool) or func(bool)) and set the row's selection // to it — reading the real box state, not toggling a server-side guess. OnSelect func(T) any // OnSelectAll is the header checkbox's onChange handler; it takes the new // ticked state (func(ctx, bool) / func(bool)) — select the page when true, // clear it when false. OnSelectAll any // AllSelected ticks the header checkbox; SomeSelected marks it mixed. AllSelected bool SomeSelected bool // Index adds a leading row-number column. IndexFrom is the number before // the first row (0 numbers the first row 1); DataTable sets it from the // page. Index bool IndexFrom int // Empty is shown in place of the body when there are no rows; a default // message is used when nil. EmptyIcon is shown above it. Empty Node EmptyIcon Node // Flush drops the table's outer border and side padding so it sits flush // in a Card (use with Card.NoPad). Flush bool Class string }
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 columns={cols} rows={books} rowKey={func(b Book) any { return b.ID }}/>
with
cols := []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) }},
}
type TableProps
deprecated
added in
v0.14.0
type Tabs ¶ added in v0.15.0
Tabs is a tab bar underlining the active tab; each tab may carry a count:
<ui.Tabs tabs={[]ui.Tab{
{Label: "Placements", Href: "/tasks?type=placements", Active: true, Count: ui.Count(42)},
{Label: "Permits", Href: "/tasks?type=permits", Count: ui.Count(7)},
}}/>
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
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
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
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
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
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
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
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
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
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 (Target) Page ¶ added in v0.9.0
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) 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 Textarea ¶ added in v0.15.0
type Textarea Field
Textarea is a multi-line text field.
type Tile ¶ added in v0.15.0
type Tile struct {
// Label is the caption under the value.
Label string
// Icon is the named icon shown in the tile's badge, e.g. "briefcase".
Icon string
// Value is the figure. A whole number is shown thousands-separated; any
// other value is shown as is.
Value any
// Variant tints the icon badge; Primary by default.
Variant Variant
Class string
}
Tile is a dashboard stat card: an icon badge beside a big number and its label:
<ui.Tile label="Applications" icon="file-text" value={int64(12840)}/>
Lay a row of them out with TileGrid.
type Toast ¶ added in v0.14.0
type Toast 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
}
Toast is one notification. Its tone matches Alert's variants:
<ui.Toast variant={ui.AlertSuccess} title="Saved" timeout={4 * time.Second}/>
type ToastContainer ¶ added in v0.14.0
type ToastContainer 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
}
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>
for _, m := range p.Messages {
<ui.Toast key={m.ID} id={m.ID} variant={ui.AlertSuccess} title={m.Title}/>
}
</ui.ToastContainer>
func (ToastContainer) View ¶ added in v1.0.0
func (t ToastContainer) View() Node
type ToastContainerProps
deprecated
added in
v0.14.0
type ToastContainerProps = ToastContainer
ToastContainerProps is ToastContainer, by its former name.
Deprecated: use ToastContainer: ui.ToastContainer{…}, or <ui.ToastContainer …> in a template.
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
deprecated
added in
v0.14.0
type ToastProps = Toast
ToastProps is Toast, by its former name.
Deprecated: use Toast: ui.Toast{…}, or <ui.Toast …> in a template.
type Tree ¶
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 ¶
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 ¶
OpaqueTree is a frame with no statics of its own around dyns.
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 ¶
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 ¶
TryNode is a (Node, error) component's result as a child: Err fails the render, else Node renders.
type URL ¶ added in v1.0.0
type URL string
URL keeps the field in the page's address, as the query parameter it names: the page reads it on load, and a set changes the address.
func (URL) Apply ¶ added in v1.0.0
func (u URL) Apply(o *FieldOptions)
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
func (c ValueCondition) Eq(v string) Condition
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>
type Variant ¶ added in v0.15.0
type Variant string
Variant is a component's tone, shared by Button and Badge. It maps to the --ui-* colour tokens, not to any framework's class names.
const ( // Default is the neutral, subtle look (Button's resting state). Default Variant = "" Primary Variant = "primary" Success Variant = "success" Danger Variant = "danger" Warning Variant = "warning" Info Variant = "info" // Ghost is a transparent button that only shows its hover state. Ghost Variant = "ghost" )
Source Files
¶
- actions.go
- actions.vuka.html
- alert.go
- alert.vuka.html
- assign.go
- badge.go
- badge.vuka.html
- bindvalue.go
- button.go
- button.vuka.html
- card.go
- card.vuka.html
- context.go
- datatable.go
- datatable.vuka.html
- derive.go
- elbox.go
- field.go
- field.vuka.html
- form.go
- form.vuka.html
- frame.go
- html.go
- http.go
- icon.go
- icon.vuka.html
- image.go
- image.vuka.html
- island.go
- island_defer.go
- island_fields.go
- island_page.go
- js.go
- jsx_test.vuka
- kit.go
- lazyframe.go
- link.go
- live.go
- livehooks.go
- liveschema.go
- modal.go
- modal.vuka.html
- node.go
- page.go
- pagination.go
- props.go
- record.go
- state.go
- table.go
- table.vuka.html
- tabs.go
- tabs.vuka.html
- template.go
- theme.go
- tile.go
- tile.vuka.html
- toast.go
- toast.vuka.html
- toast_container.vuka.html
- tree.go
- update.go
- url.go
- validate.go
- walk.go
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. |
|
Package validate is the rules a live page's field keeps, as attributes of its LiveSchema:
|
Package validate is the rules a live page's field keeps, as attributes of its LiveSchema: |