Documentation
¶
Index ¶
- Constants
- Variables
- func AttachLive(c Stateful, inst LiveInstance)
- func CallHandler(ctx context.Context, fn any, bind func(t reflect.Type) (reflect.Value, error)) error
- func CallHandlerResult(ctx context.Context, fn any, bind func(t reflect.Type) (reflect.Value, error)) (any, error)
- func CallPush(ctx context.Context, fn any, args []json.RawMessage, form url.Values) (any, error)
- func Catch(err *error)
- func CheckHandler(fn any) error
- func CheckHooks(t reflect.Type) error
- func CheckIsland(t reflect.Type) error
- func CheckParts(t reflect.Type, live bool) error
- func CheckPush(fn any) error
- func CheckStateful(c Stateful) error
- func CheckStreams(c Stateful) error
- func CheckValidate(t reflect.Type) error
- func Configure(c Config)
- func Contains(s string) string
- func Count(n int) *int
- func EditURL(ctx context.Context, edit func(url.Values), push bool) bool
- func EncodeJS(ctx context.Context, ch JSChain) ([]byte, error)
- func EventName(attr string) string
- func EventQuery(ctx context.Context) url.Values
- func Failed(p any) (error, bool)
- func FieldPath(field any, outer ...any) (string, error)
- func FlushedAttrs(s string) string
- func FlushedHTML(s string) string
- func Handler(f func(r *http.Request) (Node, error)) http.Handler
- func HandlerResult(ctx context.Context, fn any, out []reflect.Value) (any, error)
- func Has(n Node) bool
- func HasStreams(c Stateful) bool
- func HasURLFields(c Stateful) bool
- func IconNames() []string
- func IsDeferred(t reflect.Type, i int) bool
- func IsFormField(t reflect.Type) bool
- func IsHook(c any, method string) bool
- func IsIsland(t reflect.Type) bool
- func IsStreamAttrs(s string) bool
- func IsUpdate(m reflect.Method) bool
- func KeyStates(ctx context.Context, props Stateful)
- func KeyText(k any) string
- func LazyValue[T any](ctx context.Context, run func(context.Context) (T, error)) T
- func LoadableURL(u string) bool
- func MergeClasses(classes ...string) string
- func MethodProps[T Stateful](c T, props ...MethodProp) T
- func ModelID(field any, outer ...any) any
- func ModelSelected(v any, field any, outer ...any) bool
- func ModelText(field any, outer ...any) string
- func MountLive(ctx context.Context, c Stateful) error
- func MountPage(ctx context.Context, p any) error
- func Must[T any](v T, err error) T
- func PageParam(ctx context.Context, name string) string
- func PageTitle(ctx context.Context) string
- func PageURL(ctx context.Context) *url.URL
- 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 QueryText(v any) []string
- func QuietError(err error) bool
- func ReadContext(ctx context.Context)
- func ReadVar(ctx context.Context, name string, ver uint64)
- func RedirectOf(err error) (string, bool)
- func RegisterIcon(name, body string)
- func RegisterIsland[T any](args ...any)
- func RegisterOptions(m any)deprecated
- func RegisterPush(m any)
- func SetAwaitDefaults(d AwaitDefaults)
- func SetBound(ctx context.Context, x reflect.Value, data json.RawMessage) error
- func SetMethodProps(c Stateful, props []MethodProp)
- func SettleState(c Stateful)
- func StreamWarnings(c Stateful) []string
- func String(ctx context.Context, n Node) (s string, err error)
- func Suffix(s string) string
- func TemplAttrs(ctx context.Context, base templ.Attributes, attrs ...Attr) templ.Attributes
- 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 WithConfig(ctx context.Context, c Config) context.Context
- func WithFormHost(ctx context.Context, h FormHost) context.Context
- func WithInjector(ctx context.Context, inj Injector) context.Context
- func WithLiveHost(ctx context.Context, h LiveHost) context.Context
- func WithOptionsScope(ctx context.Context, scope string) context.Contextdeprecated
- func WithPageCrumbs(ctx context.Context, crumbs []Crumb) context.Context
- func WithPageTitle(ctx context.Context, title string) context.Context
- func WithPageURL(ctx context.Context, u *url.URL, param func(name string) string) context.Context
- func WithPushScope(ctx context.Context, scope string) context.Context
- func WithURLEditor(ctx context.Context, e URLEditor) context.Context
- func WithVarSource(ctx context.Context, src VarSource) 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 Attr
- type Await
- type AwaitDefaults
- 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 Choices
- 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) Into(target Target, opts ...IntoOption) 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) Once() Commands
- func (c Commands) Optimistic() Commands
- func (c Commands) Options(target Target, handler any, args ...any) Commands
- func (c Commands) Patch(href string) Commands
- func (c Commands) PatchReplace(href string) Commands
- func (c Commands) PopFocus() Commands
- func (c Commands) Prevent() Commands
- func (c Commands) Push(handler any, args ...any) 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 any) Commands
- func (c Commands) SetValue(target Target, v any) Commands
- func (c Commands) Show(target Target, opts ...ShowOption) Commands
- func (c Commands) Stop() Commands
- func (c Commands) Then(chain JSChain) 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) Into(target Target, opts ...IntoOption) 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) Options(handler any, args ...any) CommandsOn
- func (o CommandsOn) Patch(href string) CommandsOn
- func (o CommandsOn) PopFocus() CommandsOn
- func (o CommandsOn) Push(handler any, args ...any) 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 any) CommandsOn
- func (o CommandsOn) SetValue(v any) 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 Config
- type Crumb
- type DataTable
- type DataTablePropsdeprecated
- type Defer
- type DeferError
- type DeferredLoad
- type Deferring
- type Derived
- type DispatchOption
- type Element
- type Error
- type Event
- type EventHandler
- type Field
- type FieldAttr
- type FieldOptions
- type FieldPropsdeprecated
- type FieldRef
- type Fieldset
- type File
- type FileHost
- type FileStore
- type Form
- type FormChoice
- type FormError
- type FormFieldError
- type FormHost
- type FormOutcome
- type FormPropsdeprecated
- type FormRegistrar
- type FormReport
- type FormReporter
- type FormState
- func (s *FormState) Apply(dst any) []string
- func (s *FormState) Changed(field any) bool
- func (s *FormState) Dirty() bool
- func (s *FormState) ErrorOf(field any) string
- func (s *FormState) Errors() []forms.Error
- func (s *FormState) Fail(format string, args ...any) error
- func (s *FormState) Load(record any)
- func (s *FormState) Reset()
- func (s *FormState) Saved() bool
- func (s *FormState) SetError(field any, key string, params ...string)
- func (s *FormState) Submitted() bool
- func (s *FormState) Submitting() bool
- func (s *FormState) Touched(field any) bool
- func (s *FormState) Valid() bool
- type FormStore
- type FormSummary
- type Frame
- type FromExpr
- type Group
- type HTMLRenderer
- type Image
- type ImagePropsdeprecated
- type Injector
- type Input
- type IntoOption
- 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 Kept
- type LayoutFunc
- type LinkActive
- type LinkPrefetch
- type LinkProps
- type Live
- func (l *Live) ID() string
- func (l *Live) LoadErr(group string) error
- func (l *Live) Loading(group string) bool
- 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 MethodProp
- type Modal
- type ModalPropsdeprecated
- type ModelForm
- type ModelSpec
- 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 Keyed(key any, n Node) Node
- func LazyPart(fallback, failed Node, body func(context.Context) Node, group ...string) Node
- func Link(p LinkProps) Node
- func ModelOptions(field any, outer ...any) 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 Part[R, V any](recv R, m func(R, context.Context) (V, error), fallback 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 SlotOr(n, fallback Node) Node
- func Spinner() Node
- func States(v any) Node
- func StyleTag() Node
- func Suspense(fallback, failed Node, body func(ctx context.Context) Node) Node
- func Template(...any) Node
- func Text(v any) Node
- func Textf(format string, args ...any) Node
- func TileGrid(tiles ...Node) Node
- func Try(n Node, err error) Node
- func URLKey(key string, c any) Node
- func WithChildren(c Node, children Node) Node
- type NodeFunc
- type Notified
- type Option
- type OptionGroup
- type OptionsCalldeprecated
- type Page
- type PageHeader
- type PageInfo
- type PageVars
- type ParamError
- type PartFallback
- type Parts
- type PartsOptions
- type Password
- type Phase
- type PushCall
- type PushOption
- type RawHTML
- type Rec
- type Renderer
- type Select
- type Setter
- type Shared
- type ShowOption
- type ShowProps
- type ShowTransition
- type Side
- type Size
- type Skeleton
- type State
- type StateHost
- type StateOption
- type Stateful
- type Stream
- func (s *Stream[T]) AssignDirty() *bool
- func (s *Stream[T]) Block(rows []Node) *StreamBlock
- func (s *Stream[T]) Delete(keys ...any)
- func (s *Stream[T]) Insert(rows ...T)
- func (s *Stream[T]) InsertAt(i int, rows ...T)
- func (s *Stream[T]) Limit(n int) StreamLimit
- func (s *Stream[T]) List(tag string, attrs []Attr, row func(T) Node) Node
- func (s *Stream[T]) Prepend(rows ...T)
- func (s *Stream[T]) Reset(rows ...T)
- func (s *Stream[T]) Rows() []T
- type StreamBatch
- type StreamBlock
- type StreamLimit
- type StreamPusher
- type Style
- type StyleList
- type Submit
- type Summary
- type SummaryItem
- 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 URLDefault
- type URLEditor
- type URLFields
- type UploadError
- type Uploaded
- 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 VarSource
- type Variant
- type Variants
Constants ¶
const ( FileTicketField = "_vk_upload" // the signed ticket the upload of its file presents FileField = "_vk_file" // the file itself, posted without script FileErrorField = "_vk_file_err" // why the upload failed ("max", "accept", "failed"), set by the runtime )
The fields a File field adds to its form, each its path after a dot:
const ( FormIDField = "_vk_form" // the form's identity: its type's name and its key FormFieldsField = "_vk_fields" // the fields it rendered, signed FormUsedField = "_vk_used" // the fields the visitor used, as the runtime marks them FormIdemField = "_vk_idem" // the submit's idempotency key FormCSRFField = "_vk_csrf" // the CSRF token FormSeqField = "_vk_seq" // the runtime's sequence number of a change FormIntentField = "_vk_intent" // a submit button's intent: "update" renders the form again, Save not called FormCheckField = "_vk_check" // a check sent over HTTP: "1" runs the checks only, "submitted" as after a failed submit )
The hidden fields a <ui.Form> carries, which no form field may be named:
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 DefaultFileMax = 10 << 20
DefaultFileMax is the largest file a File field without a max: tag takes.
const DefaultPartLimit = 8
DefaultPartLimit is how many of a page's deferred methods run at once.
const FileTTL = 24 * time.Hour
FileTTL is how long a file sent to a form is kept, and how long a page may send one: long enough for a visitor to finish the form.
const FormKeyTTL = 24 * time.Hour
FormKeyTTL is how long a FormStore made with NewFormStore keeps a key.
const FormRowField = "_vk_row"
FormRowField is the hidden field of a form in a stream row: the row's key.
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 PartsScript = `` /* 536-byte string literal not displayed */
PartsScript is the script Stream starts with: what moves each part into its place as it arrives.
Deprecated: package web no longer appends a page's parts to its response; the runtime moves in the parts StreamParts writes.
const StreamBatchAttr = " data-vk-ops="
StreamBatchAttr starts the attributes a batch adds to a container's: what FlushedAttrs takes off.
const StreamWarnAt = 10000
StreamWarnAt is how many queued rows of a stream without a limit make the session warn about it (in development and tests): a container that isn't rendered while messages arrive queues them all.
const Styles = `` /* 19264-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.html file importing ui lowers its markup 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), states to package uigen (see VukaState); children of components that read them from their context (templ components) go through WithChildren.
const VukaState = "github.com/vuka-lang/ui/v2/uigen"
VukaState marks the package's State as client state the compiler lowers, and names the package its lowering calls: what a .vuka.html file's reads and writes of states become.
Variables ¶
var BrowserVars func(ctx context.Context) any
BrowserVars is the template variables an island's component may read (ctx.value("name") in its mount's context): package web sets it to the variables of the context processors the app lists as web.Browser, as a JSON object by name; nil or an empty object when none.
var ErrFormChecked = errors.New("ui: the form was sent for its checks, not submitted")
ErrFormChecked is what a form's submit answers when it was sent for its checks only (its _vk_check field: a form on a page that isn't live, checked over HTTP as the visitor leaves a field): the checks ran live, as a change's do, and the submit handler didn't.
var ErrFormIntent = errors.New("ui: the form was sent for an intent, not submitted")
ErrFormIntent is what a form's submit answers when a button with an intent sent it ("update": the form renders again, its choices following its new values) rather than a submit of the form: a plain POST answers 200 with the form, Save not called.
var ErrFormInvalid = errors.New("ui: the form has errors")
ErrFormInvalid is what a form's submit answers when the form didn't pass its checks: its errors show in the form, so a live page shows no other error, and a plain POST answers 422 with the form.
var ErrNoFile = errors.New("ui: the field holds no file")
ErrNoFile is what Open answers for a field holding no file.
var ErrOptionsRef = ErrPushRef
ErrOptionsRef is ErrPushRef.
Deprecated: use ErrPushRef.
var ErrPushRef = errors.New("ui: the pushed method isn't one this page calls")
ErrPushRef is the error of a call naming a method the page at its path doesn't render a step for: a reference from another page, forged, or from before a deploy that removed the method.
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 LoadError = ValueCondition{Condition{/* contains filtered or unexported fields */}}
LoadError is a read of the message of the push that failed, for the steps of its OnError: SetText and SetValue take it.
Example:
<button onClick={ui.JS.Push(c.Details, ui.Value(pet.ID), ui.Read()).Into("#details").OnError(ui.JS.SetText("#err", ui.LoadError))}>View</button>
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 CallHandler ¶
func CallHandler(ctx context.Context, fn any, bind func(t reflect.Type) (reflect.Value, error)) error
CallHandler calls an event handler, fn, its parameters filled by type (see Injector): bind gives the event's payload, as a parameter of the type it is asked for. Package live calls it for each event.
func CallHandlerResult ¶ added in v2.15.0
func CallHandlerResult(ctx context.Context, fn any, bind func(t reflect.Type) (reflect.Value, error)) (any, error)
CallHandlerResult is CallHandler for a Push step's handler, which may return a result (see Commands.Push): its reply, as the runtime applies it to the step's target, or nil when fn returns none. The error is fn's.
func CallPush ¶ added in v2.15.0
CallPush calls fn, a live handler, as a Push step with arguments does: its parameters bound from args and form as PushCall.Call binds them, its result encoded as the reply carries it.
func Catch ¶ added in v2.8.0
func Catch(err *error)
Catch, deferred, stops a panic of Must and sets *err to Must's error. Any other panic goes on.
func render(ctx context.Context, n ui.Node, w io.Writer) (err error) {
defer ui.Catch(&err)
return n.Render(ctx, w)
}
func CheckHandler ¶
CheckHandler reports a value an on… attribute can't take: a handler is a func returning nothing or an error, its parameters filled by type (see Injector): a context.Context, the event's payload — its value (a string, number or bool), its form (a struct or pointer to one, or url.Values) or the Event — once, and what the app injects (a pointer or interface: the request, a service). An app checks its pages' handlers' injected parameters when it starts (CheckParams); a call reports one nothing fills.
func CheckHooks ¶
CheckHooks reports what is wrong with the hooks of t (a struct, or a pointer to one): its LiveSchema's mistakes (E0335, E0336), and a method named as earlier releases found a hook by that isn't declared one (E0337). Package web checks a stateless page with it at boot.
func CheckIsland ¶
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 method named as earlier releases found a hook by that isn't declared one.
func CheckParts ¶ added in v2.9.0
CheckParts checks the timing attributes on the methods of t, a page or component type (or a pointer to one): a deferred method takes a context.Context and returns (T, error), has one timing attribute, and is a stateless page's (live is whether t is live). Package web runs it on each page it routes, so a misregistered method fails the app's start.
func CheckPush ¶ added in v2.15.0
CheckPush reports a value a Push step can't take: a func whose parameters are a context.Context (first), the step's arguments (one struct at most) and what the app injects (pointers and interfaces), returning nothing, an error, or a result and maybe an error (see Commands.Push).
func CheckStateful ¶
CheckStateful reports a stateful component that embeds *Live rather than Live, which has no instance to attach.
func CheckStreams ¶ added in v2.17.0
CheckStreams ends a render of c under verification (VUKA_LIVE_VERIFY, on in tests): it fails when the render showed a stream's container again after a render of c that didn't, with no Reset between — the browser dropped the rows with the container.
func CheckValidate ¶
CheckValidate reports a validate tag of t, or of a struct it holds, that isn't one of Validate's rules.
func Configure ¶ added in v2.8.0
func Configure(c Config)
Configure sets how forms render in every page without a Config of its own (WithConfig).
func Contains ¶
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 EditURL ¶ added in v2.4.0
EditURL applies edit to the query of the live page whose event ctx belongs to, as a patch of the page once the event's reply is applied, the other parameters kept; it reports false, doing nothing, outside a live page's event. Package web's Query is the API.
func EncodeJS ¶
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, for a Read, or without a live host, the reference of the method vuka registered (RegisterPush), signed for ctx's page; or left without either when it is neither.
func EventName ¶
EventName is the DOM event an on… attribute names: onClick is click, onKeyDown keydown.
func EventQuery ¶ added in v2.4.0
EventQuery is the query of the live page whose event ctx belongs to, with the edits its code made so far; else the query of the page ctx renders, nil when there is none.
func Failed ¶ added in v2.8.0
Failed reports whether p, a value recover returned, is a panic of Must, and its error: for a recover that handles other panics too.
func FieldPath ¶ added in v2.8.0
FieldPath is the path of the field a pointer names, field pointing into one of the values outer point to (see For): "email", "address.city". Tests name the fields they fill by it.
func FlushedAttrs ¶ added in v2.17.0
FlushedAttrs is a container's stream attributes as rendered (one dynamic of a render tree, starting with data-vk-stream) as they render once the batch is sent: without what the batch added.
func FlushedHTML ¶ added in v2.17.0
FlushedHTML is markup holding stream containers (an instance's render as one piece of HTML) as it renders once their batches are sent: each container without what its batch added to its attributes, and empty.
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 HandlerResult ¶ added in v2.15.0
HandlerResult is the reply to a live handler's call, given its results out: fn's result encoded as a push's reply carries it ({"html"}, …), or nil when fn returns none. The error is fn's.
func Has ¶ added in v2.3.0
Has reports whether a slot was filled: n is a Node with something in it. It is false for nil (a slot the caller left out), a nil pointer or func, and text, raw HTML or a fragment holding only white space; anything else — an element, a template, a component — counts as content without rendering it.
if ui.Has(Actions) {
<footer>{Actions}</footer>
}
func HasStreams ¶ added in v2.17.0
HasStreams reports whether c has a stream field.
func HasURLFields ¶ added in v2.4.0
HasURLFields reports whether c's type keeps fields in the URL.
func IsDeferred ¶ added in v2.17.0
IsDeferred reports whether t's (a pointer to a live component's struct) field i is deferred: the component's own, never set by its tag.
func IsFormField ¶ added in v2.8.0
IsFormField reports whether a component's field of type t holds a form (a struct embedding FormState, or a pointer to one): the component's own state, which a parent's render doesn't set again as it does its other props.
func IsHook ¶
IsHook reports whether method is LiveSchema or one of the hooks c's LiveSchema sets: never called from the browser. Package live asks.
func IsStreamAttrs ¶ added in v2.17.0
IsStreamAttrs reports whether s, a dynamic of a render tree, is a container's stream attributes.
func IsUpdate ¶
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 ¶
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 LazyValue ¶ added in v2.10.0
LazyValue evaluates a deferred binding at its first rendered use. The compiler puts it inside a sync.OnceValue so later uses share its result.
func LoadableURL ¶
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 MergeClasses ¶ added in v2.17.0
MergeClasses joins class lists, a later one winning where two Tailwind utilities set the same thing: MergeClasses("px-4 py-2 text-sm", "px-2") is "py-2 text-sm px-2". Utilities conflict within their group — padding, margin, sizing, colours, display, position, typography, borders, flex and grid, effects — and only under the same variants: hover:bg-red-500 and bg-blue-500 both stay. A side refines a whole: px-2 after p-4 keeps both, p-4 after px-2 drops px-2. Classes that aren't Tailwind's (vk-alert, an app's own) are always kept.
A component taking a Class merges it last, so a caller's class wins over the component's own.
func MethodProps ¶ added in v2.16.0
func MethodProps[T Stateful](c T, props ...MethodProp) T
MethodProps records on a component's tag which of its func props are method values, and returns the tag. Compiled code calls it:
ui.MethodProps(&OrderRow{Order: o, OnCancel: p.Cancel}, ui.Method("OnCancel", p, "Cancel"))
func ModelID ¶ added in v2.8.0
ModelID is the id of the field's first control: <label for={Form.Email}>.
func ModelSelected ¶ added in v2.8.0
ModelSelected reports whether an <option value={v}> of a <select model={…}> is selected.
func ModelText ¶ added in v2.8.0
ModelText is the text of a <textarea model={…}>: the field's value.
func MountLive ¶
MountLive gives c's zero ui.State fields their states, then runs c's mount hook, the one its LiveSchema sets (@ui.Mount), after checking its hooks as MountPage does.
func MountPage ¶
MountPage checks p's hooks (CheckHooks), then runs the mount hook its LiveSchema declares, if any: what package web runs for a stateless page as MountLive does for a stateful component.
func Must ¶ added in v2.8.0
Must is a call in markup returning (T, error), as markup takes it: its T, or — when err isn't nil — a failed render. The compiler writes it around such a call where markup takes one value:
<span>{s.Users()}</span> → ui.HTML(`<span>{ui.Must(s.Users())}</span>`, ui.Must(s.Users()))
The render fails with err as a Load or Mount error fails it: rendering a Node returns err (a page's status from it, its message shown only in development), and nothing the render wrote is sent. Must panics to leave the markup; every render this package and web run, and a live session's, stops the panic and returns err (Catch).
func PageParam ¶ added in v2.4.0
PageParam is the path parameter name of the route of the page ctx renders, "" when it has none of that name.
func PageTitle ¶
PageTitle is the title of the page being rendered, for a layout's <title> and heading: what WithPageTitle set, else "". A layout reads it in its markup, which renders again for every page while the layout stays across navigations; read in its Load it is the title of the page the layout was loaded for.
func PageURL ¶ added in v2.4.0
PageURL is the URL of the page ctx renders (WithPageURL); nil when it carries none.
func Prefix ¶
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 ¶
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, and secrets: a form (a struct embedding FormState), whose values are what the visitor typed, and a field tagged as a password or a one-time code (input:"password", "new-password", "current-password", "one-time-code"), at any depth of the fields' types (a value held in an interface is written as encoding/json writes it). A script reads a form's values from its fields. A .vuka.html template with a component script writes it on its root as data-vk-p, in the page's HTML and in each live patch.
func PropsJSON ¶
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 ¶
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 QueryText ¶ added in v2.4.0
QueryText is v as URL parameter values, as a field @ui.URL keeps formats it: a string as it is, a number or bool as strconv writes it, MarshalText's, each element of a slice; none for a nil pointer.
func QuietError ¶ added in v2.8.0
QuietError reports whether a handler's error shows only in the page (a form's ErrFormInvalid, ErrFormIntent, ErrFormChecked), not as an error message of its own.
func ReadContext ¶ added in v2.4.0
ReadContext records that the render of ctx read something of its context no version follows (a value overridden for part of the page): a live session never keeps that instance's last render on its state alone.
func ReadVar ¶ added in v2.4.0
ReadVar records that the render of ctx read the template variable name at version ver: a live session renders the instance making the read again when the variable's version moves. It does nothing outside a live render.
func RedirectOf ¶ added in v2.8.0
RedirectOf is where err, a handler's error, sends the visitor: a value with a RedirectLocation method, as web.Redirect has.
func RegisterIcon ¶
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 ¶
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.html file's import of a component file (import Counter "./islands/Counter.vue").
func RegisterOptions
deprecated
added in
v2.15.0
func RegisterOptions(m any)
RegisterOptions is RegisterPush, as vuka 2.14's compiler named it for the methods Options steps name.
Deprecated: the compiler calls RegisterPush.
func RegisterPush ¶ added in v2.15.0
func RegisterPush(m any)
RegisterPush makes method m, a method expression ((*Checkout).CitiesOf), callable over HTTP by the Push and Options steps naming it. Vuka's compiler calls it for each method such a step in a page's or component's markup names; an app doesn't.
The method's parameters after the receiver are a context.Context (optional, first), then the step's arguments in order — the parameters that aren't pointers or interfaces, one of them a struct at most — and the dependencies the app injects (pointers and interfaces). It returns nothing, an error, or a result and maybe an error: []Option, []OptionGroup, a Node, a string, number, bool or time.Time, a struct, or Commands. RegisterPush panics on another shape.
func SetAwaitDefaults ¶ added in v2.17.0
func SetAwaitDefaults(d AwaitDefaults)
SetAwaitDefaults sets what every Await of the app shows for a slot its markup leaves out: Pending while a group loads, Error once its loader failed. A nil one keeps the built-in default. Call it once, before the app serves:
ui.SetAwaitDefaults(ui.AwaitDefaults{
Pending: ui.Skeleton{Lines: 3},
Error: func(err error) ui.Node { return ui.Alert{Variant: ui.AlertError, Children: ui.Text(err.Error())} },
})
func SetBound ¶
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. 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 SetMethodProps ¶ added in v2.16.0
func SetMethodProps(c Stateful, props []MethodProp)
SetMethodProps records props on an instance, from the tag that set its props. Package live calls it.
func SettleState ¶
func SettleState(c Stateful)
SettleState marks c's Assigns unchanged, after a render.
func StreamWarnings ¶ added in v2.17.0
StreamWarnings names c's streams that queued more than StreamWarnAt rows that no limit bounds (none set, or InsertAt's rows), each once.
func Suffix ¶
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 TemplAttrs ¶ added in v2.13.0
func TemplAttrs(ctx context.Context, base templ.Attributes, attrs ...Attr) templ.Attributes
TemplAttrs is the templ.Attributes a component whose props have an Attributes field (templUI's, shadcn-templ's) takes from its tag: base, the tag's attributes={…}, with attrs, the tag's attributes that aren't fields (aria-label, data-x, role, onClick). Each renders as it would on an element in ctx: an on… handler as the live event it binds (data-vk-on-click), JS commands as data-vk-js-<event>, a class list as a string. An on… entry of base holding a handler binds the same way. The generated code of a tag calls it; base is not modified.
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 ¶
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 ¶
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 ¶
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 ¶
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 WithConfig ¶ added in v2.8.0
WithConfig is ctx rendering forms as c says.
func WithFormHost ¶ added in v2.8.0
WithFormHost is ctx whose forms h serves.
func WithInjector ¶
WithInjector is ctx carrying inj, which fills the hooks' and handlers' parameters of the pages rendered and run with it.
func WithLiveHost ¶
WithLiveHost is ctx carrying h.
func WithPageCrumbs ¶ added in v2.2.0
WithPageCrumbs is ctx carrying the breadcrumbs of the page being rendered. Package web sets them for a page whose pointer has Crumbs() []ui.Crumb, when it reads its Title.
func WithPageTitle ¶
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.
func WithPageURL ¶ added in v2.4.0
WithPageURL is ctx carrying the URL of the page being rendered and its route's path parameters (param, nil when it has none): what the @ui.URL fields of the components it renders read. Package web sets it for every request it serves.
func WithPushScope ¶ added in v2.15.0
WithPushScope is ctx rendering a page whose Push and Options steps are signed for scope: the route the page is served under ("/orgs/{org}"), so a reference stays good while a live page moves to other parameters of it. Without one, the page's path (PageURL) is the scope. Package web sets it for every route.
func WithURLEditor ¶ added in v2.4.0
WithURLEditor is ctx carrying e, the session whose event ctx's code runs for.
func WithVarSource ¶ added in v2.4.0
WithVarSource is ctx whose renders read their template variables from src.
Types ¶
type Alert ¶
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
type AlertProps = Alert
AlertProps is Alert, by its former name.
Deprecated: use Alert: ui.Alert{…}, or <ui.Alert …> in a template.
type AlertVariant ¶
type AlertVariant string
AlertVariant is an Alert's tone.
const ( AlertInfo AlertVariant = "info" AlertSuccess AlertVariant = "success" AlertWarning AlertVariant = "warning" AlertError AlertVariant = "error" )
type AnyState ¶
type AnyState interface {
// contains filtered or unexported methods
}
AnyState is a State of any type: what Commands.Set takes.
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 ¶
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:
<components.Button attrs={[]ui.Attr{
ui.BindAttr("aria-expanded", open),
}} />
An aria-* attribute writes a bool as "true" or "false"; any other bool attribute is there while true.
func BindValue ¶
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. pace, when given, times the sets in place of the field's debounce: JS.Throttle(time.Second), JS.Debounce(0) for every key.
func Model ¶ added in v2.8.0
Model is the attributes of an <input>, <textarea> or <select> carrying model={Form.Email}, which the compiler writes as ui.Model(spec, &p.Form.Email, &p.Form): its name, id and value, the type, inputmode and autocomplete its Go type, name and tags give, aria-describedby linking the field's hint and error, aria-invalid once its error shows. A radio or a checkbox of a group is checked when the field is (or holds) its value. The element's own attributes win: Model writes none it sets (spec.Own).
model on a field of a page that isn't in a form binds the field as bind:value does.
type Await ¶ added in v2.17.0
type Await struct {
Of Deferring
Key string
Pending Node
Error func(err error) Node
Children func() Node
}
Await is the section of a live component's markup showing one of its deferred groups — the fields @ui.Defer("orders") marks:
<ui.Await key="orders">
<slot:pending><OrdersSkeleton rows={10} /></slot:pending>
<slot:error let={err}>Couldn't load the orders: {err.Error()}</slot:error>
for _, o := range orders {
<OrderRow order={o} />
}
</ui.Await>
It is the branches a component would write itself, rendered and patched as they are:
if Loading("orders") { … } else if err := LoadErr("orders"); err != nil { … } else { … }
Pending shows while the group loads, Error once its loader failed, and Children once its fields are set; Children runs only then. A slot left out shows the app's default (SetAwaitDefaults), else what a <ui.Suspense> shows. In markup the compiler sets Of to the component whose markup it is; in Go, set it to the component.
type AwaitDefaults ¶ added in v2.17.0
AwaitDefaults are what an Await shows for a slot its markup leaves out.
type Badge ¶
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
type BadgeProps = Badge
BadgeProps is Badge, by its former name.
Deprecated: use Badge: ui.Badge{…}, or <ui.Badge …> in a template.
type Bind ¶
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 ¶
func (b Bind) Apply(o *FieldOptions)
type Binding ¶
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 ¶
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 ¶
type BusyArg interface {
// contains filtered or unexported methods
}
BusyArg is what Busy takes: the targets to mark busy, and ui.Timeout.
type Button ¶
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
type ButtonProps = Button
ButtonProps is Button, by its former name.
Deprecated: use Button: ui.Button{…}, or <ui.Button …> in a template.
type Card ¶
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 ¶
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 ¶
type Checkbox Field
Checkbox is a single boolean field; its label sits beside the box.
type Choices ¶ added in v2.8.0
Choices are the controls of a field with choices (<Field>Choices): a radio per choice, or a checkbox per choice for a slice field, each with its label, for markup laying the field out itself:
<fieldset aria-describedby="plan-hint">
<legend>Plan</legend>
<ui.Error for={Form.Plan}/>
<ui.Choices for={Form.Plan}/>
</fieldset>
The first control's id is the field's, which the error summary links to.
type Class ¶
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 ¶
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 ¶
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.
In a template each <slot:column> inside the tag is one Column, in order: its attributes set the fields (a quoted header is text) and its content, with let naming the row, is Cell:
<ui.DataTable page={Page} onPage={GoTo}>
<slot:column header="Title" let={b}><b>{b.Title}</b></slot:column>
<slot:column header="Pages" align="right" let={b}>{b.Pages}</slot:column>
</ui.DataTable>
A <slot:header> inside a <slot:column> gives a header with markup.
type Commands ¶
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 ¶
CloseModal hides the modal named ref and restores the focus OpenModal remembered.
func DismissToast ¶
func DismissToast() Commands
DismissToast hides the toast the event came from (the close button's), no round trip.
func DismissToastRef ¶
DismissToastRef hides the toast named ref.
func OpenModal ¶
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 ¶
ShowToast reveals the toast named ref (one pre-rendered hidden in the container), for a browser-only notification.
func (Commands) AddClass ¶
AddClass adds CSS classes to target.
Example:
<button onClick={ui.JS.AddClass(ui.Ref("menu"), "open", "shadow")}>Menu</button>
func (Commands) Busy ¶
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 ¶
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 ¶
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 ¶
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 ¶
CopyText copies text to the clipboard.
Example:
<button onClick={ui.JS.CopyText(post.URL)}>Copy link</button>
func (Commands) Debounce ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) Into ¶ added in v2.15.0
func (c Commands) Into(target Target, opts ...IntoOption) Commands
Into puts the result of the last Push before it into target instead of the element the event is on; opts (Append, Prepend) add a Node result to target's content instead of replacing it. Panics with no Push before it.
Example:
<button onClick={ui.JS.Push(c.Older, ui.Value(pet.ID), ui.Read()).Into("#posts", ui.Append())}>Load more</button>
func (Commands) Key ¶
Key stops the chain unless the event is a press of one of keys, named as KeyboardEvent.key names them: "Enter", "Escape", "a". A key may name the modifiers held with it, joined by +: "ctrl+Enter", "shift+alt+Tab" (ctrl, shift, alt, meta); others held don't count. 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>
<textarea onKeyDown={ui.JS.Key("ctrl+Enter").Push(c.Send)}></textarea>
func (Commands) Navigate ¶
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 ¶
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 ¶
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 ¶
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) Once ¶ added in v2.17.0
Once runs the steps after it the first time the event fires on the element only; later events run the steps before it alone.
Example:
<button onClick={ui.JS.Once().Push(c.Follow)}>Follow</button>
func (Commands) Optimistic ¶ added in v2.17.0
Optimistic makes the chain's state writes after it predictions of its pushes: each push that fails puts back the states the chain wrote before it, in the reverse order of the writes, before its error shows. Without it a failed push leaves the states as written. An on… attribute's .optimistic modifier is the step first: onClick.optimistic={liked = !liked; Like()}.
Example:
<button onClick={ui.JS.Optimistic().Set(liked, true).Push(c.Like)}>♥</button>
func (Commands) Options ¶ added in v2.15.0
Options loads the options of target, a select, from handler: a method of the page or of a component on it, called with args — values, or element reads such as ui.This.Value(), made when the step runs. It is Push(handler, args…, Read()).Into(target): a read over HTTP to the page's own URL, so it needs no connection and leaves a live page's state alone.
func (p *Checkout) CitiesOf(ctx context.Context, country string, geo *Geo) ([]ui.Option, error)
The method returns []Option, or []OptionGroup for <optgroup>s, and maybe an error. The reply replaces target's options — a leading option whose value is "" (a placeholder) stays — and keeps the value if it is still offered, else clears it; then target fires change, so a select loading another's options from its own chains on. A failure (the method's error, a reply that doesn't come in time) runs OnError after it, else is logged and leaves the options as they were.
Example:
<select name="country" onChange={ui.JS.Options(ui.Sel("#city"), c.CitiesOf, ui.This.Value())}>…</select>
<select name="country" onChange={ui.JS.Options(ui.Ref("city"), c.CitiesOf, ui.This.Value()).OnError(ui.JS.Show(ui.Ref("cities-error")))}>…</select>
func (Commands) Patch ¶
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) PatchReplace ¶ added in v2.4.0
PatchReplace is Patch taking the current history entry's place instead of adding one: what a write of the page's URL state (an @ui.URL field, web's Query) does, so that back leaves the page rather than stepping through its tabs.
func (Commands) PopFocus ¶
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) Prevent ¶ added in v2.17.0
Prevent keeps the browser from doing what the event would: following a link, submitting a form, typing a key (Event.preventDefault).
Example:
<a href="/orders" onClick={ui.JS.Prevent().Show(ui.Ref("menu"))}>Orders</a>
func (Commands) Push ¶
Push calls handler on the server: a method of the page or of a component on it, or on a live page any handler (a closure, a func prop). Where it runs follows from the page:
- on a live page, on its instance over the page's socket, as onClick={handler} would: it reads and changes the fields, and the page renders again;
- on a page that isn't live, or with Read on any page, on a fresh copy of the page over HTTP to the page's own URL (a POST carrying the CSRF token, a GET with Read): its path and query fields bound, its dependencies injected, the page's guards and the app's middleware run but not its Load. Only methods vuka's compiler registered for a step (RegisterPush) can be called so.
args fill the handler's parameters in order — those that aren't a context.Context (first) or pointers and interfaces (injected): Go values from the render, or element reads made when the event fires (ui.This.Value(), ui.Sel("#qty").Value(), ui.This.Checked()). A read's text converts to the parameter's type; one that won't fails the push. With no argument for a handler taking one value, it gets the element's value; one struct parameter given no argument gets the enclosing form's fields, by their form names. Options (Read, Cache, Value, Timeout, KeepOnError) may go anywhere among args.
What the handler returns besides an error goes Into a target — the element itself unless Into names another: []Option or []OptionGroup replace a select's options; a Node its content (Append, Prepend add instead); a string, number, bool or time.Time a field's value, or another element's text; a struct fills the controls of its fields' names inside the target; Commands run. On a live page, what a push put in a place stays until the server renders that place differently.
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. A later push into a target wins over an earlier one still on its way.
Example:
<input name="q" onInput={ui.JS.Debounce(150*time.Millisecond).Push(c.Search)} />
<select name="country" onChange={ui.JS.Push(c.RegionsOf, ui.This.Value(), ui.Read()).Into("#region")}>…</select>
<button onClick={ui.JS.Push(c.Details, ui.Value(pet.ID), ui.Read()).Into("#details")}>View</button>
func (Commands) PushFocus ¶
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 ¶
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 ¶
RemoveClass removes CSS classes from target.
Example:
<button onClick={ui.JS.RemoveClass(ui.Ref("menu"), "hidden")}>Menu</button>
func (Commands) ScrollTo ¶
ScrollTo scrolls the page until target is in view.
Example:
<button onClick={ui.JS.ScrollTo(ui.Ref("comments"))}>Comments</button>
func (Commands) Set ¶
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 ¶
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 ¶
SetText replaces target's content with text: a string, or a read made when the step runs (ui.Sel("#q").Value(), ui.LoadError in an OnError). 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>
<button onClick={ui.JS.Push(c.Save).OnError(ui.JS.SetText("#err", ui.LoadError))}>Save</button>
func (Commands) SetValue ¶
SetValue sets a form field's value and fires input and change on it, so its own on… attributes run. The value is a string, a bool (a checkbox's checked state; "true" checks one too), or a read of another element, made when the step runs: ui.Sel("#bill-city").Value(), ui.This.Checked(). A select takes the option of that value, a radio or checkbox is checked when the value is true (or its own value).
Example:
<button onClick={ui.JS.SetValue(ui.Ref("q"), "").Focus(ui.Ref("q"))}>Clear</button>
<input type="checkbox" onChange={ui.JS.If(ui.This.Checked()).SetValue(ui.Sel("#ship-city"), ui.Sel("#bill-city").Value()).End()} />
func (Commands) Show ¶
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) Stop ¶ added in v2.17.0
Stop keeps the event from reaching the elements around this one once its own listeners have run (Event.stopPropagation): an on… attribute of an ancestor doesn't handle it.
Example:
<li onClick={ui.JS.Push(c.Pick, ui.Value(pet.ID))}><button onClick={ui.JS.Stop().Push(func() { c.Delete(pet.ID) })}>Delete</button></li>
func (Commands) Then ¶ added in v2.17.0
Then is the chain with chain's steps after its own.
Example:
<button onClick={ui.JS.Prevent().Then(ui.JS.Show(ui.Ref("dialog")).FocusFirst(ui.Ref("dialog")))}>Edit</button>
func (Commands) Throttle ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) Into ¶ added in v2.15.0
func (o CommandsOn) Into(target Target, opts ...IntoOption) CommandsOn
Into puts the result of the last Push before it into target (see Commands.Into).
Example:
<button onClick={ui.JS.On(ui.Ref("list")).AddClass("opacity-50").Push(c.Details, ui.Value(pet.ID), ui.Read()).Into("#details")}>View</button>
func (CommandsOn) Key ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) Options ¶ added in v2.15.0
func (o CommandsOn) Options(handler any, args ...any) CommandsOn
Options loads the target select's options from handler, a method of the page or of a component on it (see Commands.Options).
Example:
<select name="country" onChange={ui.JS.On(ui.Ref("city")).Options(c.CitiesOf, ui.This.Value())}>…</select>
func (CommandsOn) Patch ¶
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 ¶
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 ¶
func (o CommandsOn) Push(handler any, args ...any) 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
func (o CommandsOn) SetText(text any) 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 ¶
func (o CommandsOn) SetValue(v any) CommandsOn
SetValue sets the target field's value (a string, a bool or a read, as Commands.SetValue takes) and fires input and change on it.
Example:
<button onClick={ui.JS.On(ui.Ref("q")).SetValue("").Focus()}>Clear</button>
func (CommandsOn) Show ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
func (o CommandsOn) When(cond Conditional, chain JSChain) CommandsOn
When runs chain only when cond holds (see Commands.When). The chain names its own targets.
Example:
<input ref="title" onInput={ui.JS.On(ui.Ref("save")).When(ui.Ref("title").Value().Not(), ui.JS.SetAttr(ui.Ref("save"), "disabled", "")).AddClass("checked")} />
type ComponentNode ¶
type ComponentNode struct {
Site string
Key any
Props Stateful
Routed bool
URL []string
URLKey string
}
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. URLKey (a tag's urlKey attribute, ui.URLKey) is the name the instance keeps its @ui.URL fields' parameters under.
type Condition ¶
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 ¶
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 ¶
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 ¶
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 ¶
func (Condition) Not ¶
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 ¶
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 ¶
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 Config ¶ added in v2.8.0
type Config struct {
// MarkRequired marks required fields' labels "(required)" instead of
// optional fields' "(optional)", the default.
MarkRequired bool
// RequiredAttr gives required fields' controls the required attribute.
// Off by default: forms are novalidate, the requirement is in the label,
// and the attribute treats whitespace as a value where the binder trims
// it.
RequiredAttr bool
// BrowserChecks has a struct form's controls carry the rules the
// browser can check exactly as the server does (required, len, min,
// max, email, oneof), with their messages, so a submit sent without a
// live connection shows its errors at once instead of after a round
// trip; the server still checks every submit. Off by default: the
// messages then ride in the page's markup.
BrowserChecks bool
// Messages is the app's message catalogue: its own wording of the
// default messages, its message keys' texts, its labels' translations
// (forms.Messages, forms.Translations). A request's own catalogue
// (forms.WithCatalogue) comes before it, the default English wording
// after.
Messages forms.Catalogue
}
Config is how forms render, app-wide (Configure) or for the pages rendered with a context (WithConfig).
type Crumb ¶ added in v2.2.0
Crumb is a step of a page's breadcrumbs: its label and the link to it, Href "" for the page itself.
func PageCrumbs ¶ added in v2.2.0
PageCrumbs are the breadcrumbs of the page being rendered, for a layout's header: what WithPageCrumbs set, else nil. Like PageTitle, a layout reads them in its markup, which follows the page while the layout stays.
type DataTable ¶
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
type Defer ¶
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 ¶
func (d Defer) Apply(o *FieldOptions)
type DeferError ¶ added in v2.17.0
type DeferError struct {
Group string
Message string
Status int // a web.Error's status; 0 for another error
Err error
}
DeferError is a deferred group's loader's error, as Live.LoadErr gives it: Message is what the visitor may read — a web.Error's message, else "error"; under vuka run the cause's text — and Err the loader's error.
func (*DeferError) Error ¶ added in v2.17.0
func (e *DeferError) Error() string
func (*DeferError) Unwrap ¶ added in v2.17.0
func (e *DeferError) Unwrap() error
type DeferredLoad ¶
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 ¶
func StartDeferred(c Stateful) []*DeferredLoad
StartDeferred starts the deferred groups of c, a live page or component, not started yet: package live runs each once the page joins, and applies it where its events run.
func (*DeferredLoad) Apply ¶
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).
type Deferring ¶ added in v2.17.0
Deferring is a component with deferred groups: a pointer to a struct embedding Live.
type Derived ¶ added in v2.17.0
type Derived[T any] struct { // contains filtered or unexported fields }
Derived is a value the browser computes from states and keeps: a cart's total from its count and price. The browser computes it again when a state it reads changes, and what reads it follows, as with a state; it is never written.
A .vuka.html file declares one as a field, with the expression it is derived from:
type Cart struct {
count ui.State[int]
price ui.State[int]
total ui.Derived[int] @ui.From(count * price)
over ui.Derived[bool] @ui.From(total > 100)
}
<p class:over={over}>{total}</p>
The expression is one markup could bind (states, literals and the operators the browser runs) and may read other Derived fields. The server renders it with the states' initial values.
Get is the value the server renders with.
type DispatchOption ¶
type DispatchOption jsArg
DispatchOption changes the event Dispatch fires: Detail, NoBubble.
func Detail ¶
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 ¶
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 Error ¶ added in v2.8.0
Error is a form field's error message, where the field's markup puts it (label, hint, error, control), when the field shows one:
<label for={Form.Email}>Email</label>
<ui.Error for={Form.Email}/>
<input model={Form.Email}/>
It renders nothing when the field shows no error; the control's aria-describedby links it when it does.
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)
// Args are a Push step's arguments, in order, when it passes any
// (JSON values; a read's text); Form then carries the enclosing
// form's fields when the handler's struct takes them.
Args []json.RawMessage `json:"args,omitempty"`
}
Event is what the browser reports of an event, and what a handler taking a ui.Event receives. Target is the handler's id; Type the DOM event; Value the target element's value (for a checkbox, "true" or "false"); Key the key of a keyboard event; Form the fields of the form a submit event comes from.
type EventHandler ¶
type EventHandler struct{ Fn any }
EventHandler is an on… attribute's expression on an element: onClick={c.Inc}. Under a live session it renders as data-vk-on-<event>="<handler id>" and the session calls Fn when the browser reports the event; without one it renders nothing. A chain of JS commands (Commands, CommandsOn) renders as data-vk-js-<event>, with or without a session; a templ.ComponentScript as templ renders it.
type Field ¶
type Field struct {
// For is a field of a struct form (see Form.For): for={Form.Email}. The
// field group is the field's — its label, hint, error and control, the
// control's name, id, type, value and ARIA links — and the props set
// here override what its tags say.
For any
// 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, where errors are tracked.
Error string
// Help is a hint shown under the control.
Help string
Placeholder string
Required bool
Disabled bool
// OK shows a tick beside a struct form's field (For) once the visitor
// used it and it passes every check: off by default.
OK 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. Given a field of a struct form (For), it renders that field:
<ui.Field for={Form.Email}/>
Otherwise 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 ¶
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 ¶
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; "" with URLBound: the path parameter of the field's name
URLBound bool // @ui.URL: the address keeps it
// URLDefault is the value it takes when the URL has no parameter for
// it (HasURLDefault): @ui.URL("page").Default(1).
URLDefault any
HasURLDefault bool
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 ¶
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
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 FieldRef ¶ added in v2.8.0
type FieldRef struct {
// contains filtered or unexported fields
}
FieldRef names a form, or one field of a form, for a component to render: what a for={…} attribute of <ui.Form>, <ui.Field>, <ui.Error> and <ui.Fieldset> holds. The compiler writes for={Form.Email} as ui.For(&p.Form.Email, &p.Form): a pointer to the field, then pointers to the values holding it, innermost first, one of which is the form (a struct embedding FormState). Go code writes the same:
ui.Field{For: ui.For(&p.Form.Email, &p.Form)}
ui.Form{For: ui.For(&p.Form), OnSubmit: p.Save}
func For ¶ added in v2.8.0
For is a reference to the field field points to, outer pointing to the values holding it (see FieldRef). Given a FieldRef (or a pointer to one) it is that reference: a component whose props hold a Model FieldRef gives its control model={Model}, which names the field its tag's model={…} did.
type Fieldset ¶ added in v2.8.0
Fieldset groups fields under a legend: the fields of a struct field of the form (for={Form.Address}, its fields rendered when it has no children), or the children:
<ui.Fieldset legend="Delivery address">
<ui.Field for={Form.Street}/>
<ui.Field for={Form.City}/>
</ui.Fieldset>
type File ¶ added in v2.17.0
type File struct {
// contains filtered or unexported fields
}
File is a form field holding a file the visitor sends:
type Profile struct {
ui.FormState
Avatar ui.File `accept:"image/*" max:"5MB" validate:"required"`
}
The browser sends the file as soon as the visitor chooses it, over HTTP with a progress bar, its size enforced while it streams; the form then carries a signed reference to it instead of the file, so validating never sends it again and a failed submit keeps it ("photo.jpg ✓ Change"). Without script the form posts as multipart and the first post stores the file. The submit handler reads it with Open.
accept: lists what the field takes, as the HTML attribute does ("image/*", ".pdf", "application/pdf"), matched against the file's name, its declared type and the type its first bytes show; it guides the visitor and isn't a security check. max: is its largest size ("5MB", "500KB"), DefaultFileMax when absent. Files are kept in the app's FileStore for FileTTL.
func (File) ContentType ¶ added in v2.17.0
ContentType is the file's type, as its first bytes show it, else as the browser declared it.
func (File) Name ¶ added in v2.17.0
Name is the file's name as the visitor's device gave it: shown back to them, never a path to write to.
type FileHost ¶ added in v2.17.0
type FileHost interface {
FileStore() FileStore
}
A FileHost is a FormHost that names the app's FileStore.
type FileStore ¶ added in v2.17.0
type FileStore interface {
// Put stores what r reads and names it.
Put(r io.Reader) (id string, err error)
// Open reads the file named id; an error when it is no longer kept.
Open(id string) (io.ReadCloser, error)
// Delete removes the file named id.
Delete(id string) error
}
A FileStore keeps the files sent to forms until their forms are submitted. The default keeps them in a directory of this machine: an app with several replicas gives them a store they share (WithFileStore in package web), else a submit reaching another replica than its upload did asks the visitor to choose the file again.
func DirFileStore ¶ added in v2.17.0
DirFileStore is a FileStore keeping files in dir, removing those older than FileTTL as it stores more.
type Form ¶
type Form struct {
// For is the form a struct form renders: for={Form}, a struct embedding
// FormState (the compiler writes ui.For(&p.Form)).
For any
// Key tells forms of one type on a page apart (a list's inline-edit
// forms): their submits, errors and ids. The compiler binds a key={…}
// attribute to it.
Key any
// Validate is when a struct form's checks run: "" as the visitor uses
// each field and on submit, "submit" only on submit (a question per
// page), "off" never (Save checks it itself).
Validate string
// Submit is what a submit sent while one is in flight does: "prevent"
// (the default) drops it, "abort" sends it and ignores the first's
// reply, "allow" sends it.
Submit string
// SubmitLabel is the submit button's text in a childless struct form;
// "Save" by default.
SubmitLabel string
// NoSummary leaves out the error summary a struct form shows at its top
// after a failed submit: focus goes to the first field in error instead.
NoSummary bool
// ConfirmLeave has the browser ask before the visitor leaves the page
// — closing it, following a link, going back — while the form has
// changes not saved: values differing from the ones it was loaded
// with (FormState.Dirty), or typed and not yet sent.
ConfirmLeave bool
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. A struct form in a stream row submits with a
// Push of a method of the stream's owner taking the form,
// ui.JS.Push(Rename, t.ID): its errors come back as the form's report,
// put in place without rendering the row.
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
// Attrs are any other attributes of the <form> element: autocomplete,
// data-*, aria-*. Written on the tag, <ui.Form autocomplete="off">, an
// attribute that isn't a field lands here.
Attrs []Attr
Children Node
}
Form is a token-styled form. Given the form it renders (For, a struct embedding FormState), it binds, checks and submits it itself:
<ui.Form for={Form} onSubmit={Save}/>
renders every field of the form and a submit button, and Save — taking the form, its dependencies injected — runs only once every rule and Clean method passed; errors show in the form and its error summary. With children, the markup is the page's (<ui.Field for>, model={…}). Without a live connection the form posts to the page, which answers 422 with the form and its errors, or 303 once Save succeeded. See the forms guide.
Without For it is a plain 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 FormChoice ¶ added in v2.15.0
FormChoice is one option of a field's choices, as a FormReport carries it.
type FormError ¶ added in v2.8.0
FormError is one error CheckForm finds: the error, and its message as a visitor reads it, the field's label in it.
func CheckForm ¶ added in v2.8.0
CheckForm runs a form's checks once, as a submit does: each field's validate: rules, then the Clean<Field> method of each field passing them, then the form's Clean method, the methods' dependencies from ctx's Injector (WithInjector). form points to a struct: one embedding FormState, or any struct with the same tags and methods, such as the input of a GraphQL mutation, which shares the form an HTML page submits. It returns every error with its message — the rules' in field order, then the Clean methods' — none when the form passes. err is a check that failed to run: a Clean method returning an error that isn't a forms.Error.
type FormFieldError ¶ added in v2.14.0
type FormFieldError struct {
Path string `json:"path"`
ID string `json:"id"` // the control's id (a radio group's first); the error's is ID + "-error"
Key string `json:"key"` // the message's key (data-vk-error)
Text string `json:"text"`
}
FormFieldError is a field's error as its render shows it.
type FormHost ¶ added in v2.8.0
type FormHost interface {
// FormToken is the CSRF token a form carries in its _vk_csrf field;
// "" for none.
FormToken(ctx context.Context) string
// FormKey signs the list of fields a form rendered (_vk_fields), so a
// plain POST can't claim others: the same on every replica.
FormKey() []byte
// FormStore keeps submits' outcomes by idempotency key; nil for the
// default, in this process.
FormStore() FormStore
}
A FormHost is what serves a page's forms: package web puts one in the context of every request and live page (WithFormHost).
type FormOutcome ¶ added in v2.8.0
FormOutcome is what a submit came to: Done once its handler returned without an error, Redirect where it sent the visitor.
type FormRegistrar ¶ added in v2.8.0
A FormRegistrar is a live host that keeps the submit handlers of the forms a render has, by their identity, for a plain POST of one (package live).
type FormReport ¶ added in v2.14.0
type FormReport struct {
// Form is the form's identity (its data-vk-form).
Form string `json:"form"`
// Errors are the fields showing an error, in the fields' order.
Errors []FormFieldError `json:"errors"`
// Summary is the error summary, when the form shows one.
Summary *FormSummary `json:"summary"`
// Idem is the idempotency key the next submit carries.
Idem string `json:"idem"`
// Words are the summary's title and an error's hidden prefix
// ("problem", "error"), in the visitor's language.
Words map[string]string `json:"words"`
// Choices are the options of the fields whose choices depend on others
// (depends:), by path, as the render computed them from the values
// sent: the runtime puts them in those fields' selects.
Choices map[string][]FormChoice `json:"choices,omitempty"`
}
FormReport is what a struct form's render showed of its errors.
type FormReporter ¶ added in v2.14.0
type FormReporter interface {
FormReport(ctx context.Context, r FormReport)
}
A FormReporter is a FormHost told what each struct form's render showed of its errors: package web answers a check or a submit sent over HTTP with it (application/json), so the runtime puts the errors in place without touching the fields.
type FormState ¶ added in v2.8.0
type FormState struct {
// contains filtered or unexported fields
}
FormState, embedded in a struct, makes the struct a form: its exported fields are the values a visitor edits — the only ones a submit binds — and FormState keeps what the form knows about them: their errors, which fields the visitor has used, whether the form was submitted.
type Signup struct {
ui.FormState
Name string `label:"Full name" validate:"required,max=80"`
Email string `validate:"required,email" help:"We'll send a confirmation link"`
}
A field's state is looked up by a pointer to it, so a rename is a compile error rather than a silent miss: f.ErrorOf(&f.Email), f.Touched(&f.Email). A page holding the form renders it with <ui.Form for={Form}>, and the handler its onSubmit names runs only once every rule and Clean method passed. Copies of a form share its state.
func (*FormState) Apply ¶ added in v2.8.0
Apply sets dst's fields — dst a pointer to a struct, the record the form edits — from the form's fields of the same Go names: only the fields the form declares, and of those, the ones its last submit rendered. It returns the Go names of the fields it set, the columns to save.
func (*FormState) Changed ¶ added in v2.8.0
Changed reports whether the field's value differs from the one the form was loaded with (Load), or first rendered with; a successful submit makes its values the new ones.
func (*FormState) Dirty ¶ added in v2.8.0
Dirty reports whether any field differs from the values the form was loaded with (Load), or first rendered with; a successful submit makes its values the new ones.
func (*FormState) ErrorOf ¶ added in v2.8.0
ErrorOf is the message of the error the field shows, "" when it shows none: f.ErrorOf(&f.Email). A field shows its error once the visitor has used it, or the form was submitted (see the forms guide's timing table).
func (*FormState) Errors ¶ added in v2.8.0
Errors are the errors the form shows, the form's own first, then its fields' in their order: what its error summary lists.
func (*FormState) Fail ¶ added in v2.8.0
Fail sets an error of the form as a whole, shown in the error summary, and returns it, for a submit handler to return:
if err := users.Create(ctx, f.Email); err != nil {
return p.Form.Fail("We couldn't create your account. Try again later")
}
It stays until the next submit.
func (*FormState) Load ¶ added in v2.8.0
Load sets the form's fields from record's — a struct, or a pointer to one, such as the database record the form edits — and makes them the values Dirty and Changed compare with and Reset goes back to. A field takes the record's field of the same Go name (Email, Address.City) when its type is the same kind of value: a string's, a number's, a bool's, a slice of them, a time; a pointer stands for its value. The form's errors and what the visitor used of it start afresh, and the browser's fields take the new values.
Called in Mount, before the form first renders, it takes effect as the form is attached to its page, once Mount returned.
func (*FormState) Reset ¶ added in v2.8.0
func (s *FormState) Reset()
Reset puts back the values the form was loaded with (Load), or first rendered with, and clears its errors; the browser's fields take them, a focused one too.
func (*FormState) Saved ¶ added in v2.8.0
Saved reports whether the form's last submit succeeded in the last 2 seconds: for a "Saved" note beside its button. A live page shows the form again when the time is up.
func (*FormState) SetError ¶ added in v2.8.0
SetError gives the field an error that shows at once and stays until the field's value changes: f.SetError(&f.Email, "That address is already registered"). key is the message, or a message key; params are its placeholders' values, name then value ("n", "80").
func (*FormState) Submitted ¶ added in v2.8.0
Submitted reports whether the visitor submitted the form and it failed: every error shows until a submit succeeds.
func (*FormState) Submitting ¶ added in v2.8.0
Submitting reports whether a submit of the form is being handled: true while its submit handler runs.
type FormStore ¶ added in v2.8.0
type FormStore interface {
// Begin claims key for a submit about to run its handler; ok is false
// when a submit with the key began before, out being what it came to
// (out.Done false while it still runs).
Begin(key string) (out FormOutcome, ok bool)
// Finish records the outcome of the submit that claimed key.
Finish(key string, out FormOutcome)
// Abandon frees key: the submit didn't pass its checks (a 422), so the
// visitor may correct the form and send it again.
Abandon(key string)
}
A FormStore keeps what came of each submit, by its idempotency key: a form carries a key per render, so a submit sent twice — the back button, a retry after a lost reply — gets the first one's outcome instead of running again.
func NewFormStore ¶ added in v2.8.0
func NewFormStore() FormStore
NewFormStore is a FormStore in memory, keeping each key for FormKeyTTL. An app with several replicas keeps keys where they all see them.
type FormSummary ¶ added in v2.14.0
type FormSummary struct {
Title string `json:"title"`
Items []SummaryItem `json:"items"`
}
FormSummary is a form's error summary: its title, then each error, linking to its field's control (Href "" for the form's own).
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 FromExpr ¶ added in v2.17.0
type FromExpr struct{}
FromExpr is what From returns: a field attribute the compiler reads.
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 ¶
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
type ImageProps = Image
ImageProps is Image, by its former name.
Deprecated: use Image: ui.Image{…}, or <ui.Image …> in a template.
type Injector ¶
type Injector interface {
// Inject is how to fill a parameter of type t, called with the
// hook's or handler's context; nil when the injector doesn't fill t.
Inject(t reflect.Type) func(ctx context.Context) (reflect.Value, error)
}
An Injector fills the parameters of a page's hooks and event handlers that the call itself doesn't: the request, the signed-in user, the app's services. A hook or handler declares what it needs by type, and the runtime fills each parameter from the one source its type names:
context.Context the session's or request's context ui.Event the event (a handler) url.Values the form's fields, as sent (a handler) a struct, or pointer to one the form's fields bound to its fields (a handler) a string, number or bool the event's value, parsed (a handler) ui.Changed the fields set (an OnChange hook) anything the Injector fills the Injector's value
The Injector is asked first, after the context: a type it fills is never bound from the event. The app serving a page puts its Injector in the context its renders and sessions run with (WithInjector); package web does, giving the request, its identity types and every type registered with app.Service or web.Provide. CheckParams reports, before anything is served, the parameters of a page's hooks and handlers nothing fills.
func InjectorOf ¶
InjectorOf is the Injector ctx carries; nil when none.
type Input ¶
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 IntoOption ¶ added in v2.15.0
type IntoOption func(*push)
IntoOption changes how Into puts a result's markup in its target: Append, Prepend.
func Append ¶ added in v2.15.0
func Append() IntoOption
Append adds a Node result after the target's content instead of replacing it.
Example:
<button onClick={ui.JS.Push(c.Older, ui.Value(pet.ID), ui.Read()).Into("#posts", ui.Append())}>Load more</button>
func Prepend ¶ added in v2.15.0
func Prepend() IntoOption
Prepend adds a Node result before the target's content instead of replacing it.
Example:
<button onClick={ui.JS.Push(c.Newer, ui.Value(pet.ID), ui.Read()).Into("#posts", ui.Prepend())}>Newer</button>
type Invalid ¶
Invalid is the error Validate answers with: each field's path → its message.
func (Invalid) FieldErrors ¶
func (Invalid) PublicMessage ¶
func (Invalid) StatusCode ¶
type IslandDecorator ¶
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 ¶
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:
@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").
On a page's route it is the route's option: ui.Island(ui.Layout(page)).
func (IslandDecorator) Attrs ¶
func (d IslandDecorator) Attrs() []any
Attrs makes the decorator a route's option: it is its one attribute.
type IslandError ¶
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".
type IslandField ¶
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 ¶
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 ¶
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 ¶
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, Update, Info), hooks or ui.Live's, return nothing or an error (or a value and an error), and take JSON arguments.
func (IslandMethod) Call ¶
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 ¶
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 ¶
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 ¶
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 ¶
func ClientOnly() IslandOpt
ClientOnly never server-renders the island (client:only): the fallback shows until the client mounts it fresh.
func Emit ¶
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 ¶
Fallback sets what shows until the island hydrates (and the SSR target under SSR). Distinct from the component's Slot.
func IslandErr ¶
func IslandErr(err *IslandError) IslandOpt
IslandErr shows err as the island's last failed call (data-vk-err).
func Once ¶
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 ¶
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 ¶
Slot sets the island's slot — the component's own children, handed to the framework on mount. Distinct from a Fallback.
func StateProp ¶
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. An expression of states is passed one way. The compiler writes it for a ui.State attribute of an island tag: <Counter count={n}/>.
type IslandOption ¶
type IslandOption interface {
// contains filtered or unexported methods
}
IslandOption is an option of @ui.Island: Layout or Strategy.
func Layout ¶
func Layout(layouts ...any) IslandOption
Layout is the layout of the page an @ui.Island type backs, when it is routed as one: 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 ¶
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 ¶
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 Kept ¶ added in v2.17.0
type Kept struct {
// contains filtered or unexported fields
}
Kept is what Keep returns.
func Keep ¶ added in v2.17.0
Keep keeps a state in the browser's localStorage under key: the value stored wins over the one rendered when the page loads, and every write is stored. A private window, or storage the browser refuses, leaves it an ordinary state.
theme ui.State[string] @ui.Keep("theme")
The value is the visitor's and JSON: never trust it on the server.
type LayoutFunc ¶
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 ¶
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 LinkActive ¶ added in v2.1.0
type LinkActive string
LinkActive is how a link's href matches the current address: Link's Active.
const ( // ActiveExact: the address's path is the link's. ActiveExact LinkActive = "exact" // ActivePrefix: the address's path is the link's or below it, // /books/7 for /books. ActivePrefix LinkActive = "prefix" )
type LinkPrefetch ¶ added in v2.1.0
type LinkPrefetch string
LinkPrefetch is when the runtime fetches a link's page before it is followed: Link's Prefetch. By default it does on hover, focus or touch.
const ( // PrefetchOff: never before the link is followed. PrefetchOff LinkPrefetch = "off" // PrefetchViewport: as soon as the link is in view. PrefetchViewport LinkPrefetch = "viewport" )
type LinkProps ¶
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
// Reload leaves the link to the browser: it loads the page as a new
// document, never moving the page in place (data-vk-reload).
Reload 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
// Active marks the link as the current page's in the browser:
// aria-current="page", and ActiveClass, while the address matches Href
// — ActiveExact the same path, ActivePrefix the path or one below it.
// The runtime sets them as the page loads and after every navigation,
// so a layout's menu needs no server render to follow the page. An
// element around active links marked data-vk-active-within gets the
// attribute's value "true" while it holds the current link, "" when it
// doesn't, and a <details> so marked opens when the current link comes
// to be inside it — a menu's group opens on the current page, and stays
// as the visitor leaves it, open or closed:
//
// <details data-vk-active-within>
// <summary>Orders</summary>
// <ui.Link href="/orders/open" active="prefix">Open</ui.Link>
// </details>
Active LinkActive
// ActiveClass is a class the runtime adds to an active link, and
// removes when it is no longer active.
ActiveClass string
// Prefetch, PrefetchOff, asks the runtime not to fetch the link's page
// before it is followed; PrefetchViewport fetches it as soon as the
// link is in view.
Prefetch LinkPrefetch
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) LoadErr ¶ added in v2.17.0
LoadErr is the error the deferred group's loader returned, a *DeferError: its Error is what the visitor may read — a web.Error's message, else "error"; under vuka run the cause's text — and it unwraps to the loader's error. Nil while the group loads and once it has loaded.
func (*Live) Loading ¶ added in v2.17.0
Loading reports whether the deferred group — the name @ui.Defer gives it, ui.Defer("stats") — is still loading: from the first render until its loader returns. Once it has, the group's fields are set (Loading is false) or its loader failed (LoadErr). Its markup shows a placeholder meanwhile:
if Loading("stats") {
<ui.Skeleton lines={3} />
} else if err := LoadErr("stats"); err != nil {
<p role="alert">{err.Error()}</p>
} else {
<Tiles stats={stats} />
}
A component rendered without a live session loads its groups before it renders, so it is never loading. A group it doesn't defer fails the render (E0325).
func (*Live) PushEvent ¶
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 ¶
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 ¶
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 ¶
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 person writes them as attributes in the page's source — @ui.Bind, @ui.URL("q") and @ui.Defer("lists") on a field, @ui.Mount, @ui.OnChange and @ui.Loads("lists") on a method — and the compiler writes them into the page's LiveSchema method:
type Dashboard struct {
ui.Live
Q string @ui.Bind{Debounce: 300 * time.Millisecond} @ui.URL("q")
Rows []Task @ui.Defer("lists")
}
@ui.Loads("lists")
func (d *Dashboard) loadLists(ctx context.Context) error { … }
@ui.Mount
func (d *Dashboard) mount(ctx context.Context) error { … }
is, in the generated Go,
func (d *Dashboard) LiveSchema(l *ui.LiveSchema) {
l.Field(&d.Q, ui.Bind{Debounce: 300 * time.Millisecond}, ui.URL("q"))
l.Field(&d.Rows, ui.Defer("lists"))
l.Loads("lists", d.loadLists)
l.Mount(d.mount)
}
LiveSchema is exported so that generated code, ejected code included, builds with go build; it is the compiler's output, not an API to write by hand, and vukavet reports a LiveSchema method a person wrote (W0306). A field is named by its address and a hook by its method value, so the Go compiler checks both. The runtime calls LiveSchema on each page it runs: the hooks are that page's methods, never ones its component calls.
func (*LiveSchema) Field ¶
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 ¶
func (l *LiveSchema) Loads(group string, fn any)
Loads sets the loader of the deferred group, a method of the page as Mount takes: it runs after the page's first render, on a copy of the page, and sets the group's fields.
func (*LiveSchema) Mount ¶
func (l *LiveSchema) Mount(fn any)
Mount sets the hook that runs when the page mounts, after its props are set and before its first render: a method of the page, d.mount, returning nothing or an error, its parameters filled by type — a context.Context, and what the app's Injector fills (the request, the signed-in user, a service).
func (*LiveSchema) OnChange ¶
func (l *LiveSchema) OnChange(fn any)
OnChange sets the hook that runs after the component sets bound fields: a method of the page as Mount takes, which may take a Changed naming them too.
type Loads ¶
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, or LoadErr in its markup).
func LoadsFrom ¶
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 ¶
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 MethodProp ¶ added in v2.16.0
type MethodProp struct {
Field string // the prop's field
Recv any // the receiver the method value is bound to
Method string
}
MethodProp says what a stateful component's func prop was set to when its tag passes a method value (onCancel={p.Cancel}): the method Method bound to the receiver Recv. A Go method value is a new closure each time it's evaluated and can't be compared, so the compiler records this beside it; a live session counts two renders passing the same method on the same receiver as the prop being unchanged.
func Method ¶ added in v2.16.0
func Method(field string, recv any, method string) MethodProp
Method records that the prop field is recv's method named method. Compiled code calls it: Recv must be the receiver the value is really bound to.
func MethodPropsOf ¶ added in v2.16.0
func MethodPropsOf(c Stateful) []MethodProp
MethodPropsOf is what MethodProps recorded on c. Package live calls it.
type Modal ¶
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
type ModalProps = Modal
ModalProps is Modal, by its former name.
Deprecated: use Modal: ui.Modal{…}, or <ui.Modal …> in a template.
type ModelForm ¶ added in v2.8.0
type ModelForm[T any] struct { FormState // Value is the model the form edits; its fields FormOf named are the // form's. Value T // contains filtered or unexported fields }
ModelForm is a form editing some fields of a model — a database record's struct, or any other — without a struct of its own: FormOf makes one. Value holds the model; the form is the fields FormOf names, each with the model's tags (validate:, label:, …), in the order named:
type Edit struct {
ui.Live
ID int64
Form *ui.ModelForm[models.User]
}
@ui.Mount
func (e *Edit) load(ctx context.Context, db *DB) error {
u, err := models.Users(db).Get(ctx, e.ID)
if err != nil {
return err
}
e.Form = ui.FormOf[models.User]("Name", "Email")
e.Form.Load(u)
return nil
}
func (e *Edit) Save(ctx context.Context, f *ui.ModelForm[models.User], db *DB) error {
u, err := models.Users(db).Get(ctx, e.ID)
if err != nil {
return err
}
return f.Apply(&u).Save(ctx, db)
}
Markup names its fields through Value: model={Form.Value.Email}, <ui.Field for={Form.Value.Name}/>; their paths and ids are the model's field names ("email", "user-email"). A submit binds only the fields named, so a model's other columns — its id, its owner — are never the visitor's to set. The model's Clean, Clean<Field> and <Field>Choices methods, if it has any, are the form's.
func FormOf ¶ added in v2.8.0
FormOf is a form editing the fields of T named, by their Go names ("Name", "Address.City"): there is no "every field", so a column added to the model later is never a submit's to set until the form names it. A name T has no field of is an error the form's render shows (and that vuka's compiler reports at the call, with the field it most likely meant).
type ModelSpec ¶ added in v2.8.0
type ModelSpec struct {
Tag string
Type string
Value any
HasValue bool
Mods string // comma-separated
Own string // space-separated attribute names
}
ModelSpec is what the compiler knows of an element carrying model={…}: its tag, its own type and value attributes (a radio's, a checkbox's in a group), the model's modifiers (model.lazy, model.raw, model.number) and the attributes it sets itself, which Model leaves to it.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
HTML is src, markup with labelled holes, filled with args: one value for each label, in the order the labels first appear. It is what the compiler writes for a .vuka.html file's markup (vukavet reports a hand-written call). A label is the Go expression its value is written as, so the call reads like the markup:
func (o OrderRow) View() 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: 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, as the compiler writes it); 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 Keyed ¶ added in v2.1.0
Keyed renders n with key scoping the stateful components in it, as an element's key attribute scopes those inside the element, and adds no markup: on a live page, a component in n keeps its instance across renders while key is the same, and mounts afresh when key changes, though its tag is in the same place. The handlers in n are named by it too, as those inside a keyed element are.
func LazyPart ¶ added in v2.10.0
LazyPart renders inline until a deferred binding is read. At that point the element becomes a part, its render continuing in the background. A render reaching no binding stays inline and starts no deferred work.
func Link ¶
Link is a link the runtime follows in place: a live page over its connection, any other page over HTTP, the new page patched into the document (web's navigation):
<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 <ui.Link href="/books" active="prefix" activeClass="on">Books</ui.Link> current while under /books <ui.Link href="/report" reload>Report</ui.Link> always a page load
It renders an a element with href, marked data-vk-link (data-vk-link="patch" with Patch, data-vk-reload with Reload), so it is an ordinary link wherever the runtime doesn't take it: without JavaScript, on a live 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 ModelOptions ¶ added in v2.8.0
ModelOptions are the options of a <select model={…}> written without any: the field's <Field>Choices, an empty first option when the field has no value yet or may stay empty.
func Mount ¶
Mount is an island placed with options, in a template's child hole: <div>{ui.Mount(Chart{Points: pts}, ui.Idle(), ui.Fallback(spinner))}</div>. The hole gives it its site; props alone, with no options, mount the same.
func MountIsland ¶
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 Part ¶ added in v2.9.0
func Part[R, V any](recv R, m func(R, context.Context) (V, error), fallback Node, render func(V) Node) Node
Part is the part of a page or component that method m's result renders: render's markup once m returns, fallback until then. m is a method expression of the page's or component's type, (*Index).Stats or Index.Stats, returning (V, error), and recv the value it is called on; its attributes say when it runs (Defer). A part whose method fails renders the fallback's Error (PartFallback), else a short message with role="alert"; the rest of the page is unaffected. A nil fallback is an empty <span aria-busy="true">.
One request calls a method once on a receiver, however many parts name it: parts of the same method of the same pointer (or of equal values) share its result.
func ResolveContext ¶
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 ¶
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 SlotOr ¶ added in v2.3.0
SlotOr is a slot with fallback content: n when it was filled (Has), else fallback. A component's markup writes it as the slot's tag holding the fallback, <slot:actions><button>Close</button></slot:actions>.
func Spinner ¶
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 ¶
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 ¶
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 Suspense ¶ added in v2.10.0
Suspense is a boundary of a stateless page: body, the markup of a <ui.Suspense>, renders after the page's first bytes, every call it makes with it, and is sent at once when all of it has returned — one reveal, not piece by piece. fallback shows until then; failed when the body fails (a panic of Must, a deferred method's error), else a short message with role="alert". A nil fallback is an empty <span aria-busy="true">.
ui.Suspense(ui.Skeleton{Lines: 3}, ui.Text("Couldn't load categories."), func(ctx context.Context) ui.Node {
categories := ui.Must(p.GetCategories(ctx))
return ui.El("h3", nil, ui.Textf("%d categories", len(categories)))
})
It is a Part whose method is its body. Inside it a deferred method runs where its part is, held by the boundary's reveal; a boundary inside is a part of its own, sent after the outer one. Where parts don't stream (a live page, a fragment, a test), the body renders in place, failed in its place when it fails.
func Template ¶
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 ¶
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 URLKey ¶ added in v2.4.0
URLKey is the stateful component c (a component, or a ui.Key of one) keeping its @ui.URL fields under key: a tag's urlKey attribute, <Table urlKey="requests" />, whose page parameter becomes "requests.page". Two instances on one page binding the same parameter need keys of their own.
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 Notified ¶ added in v2.17.0
type Notified struct {
// contains filtered or unexported fields
}
Notified is what Notify returns: the handler, and how its calls are paced.
func Notify ¶ added in v2.17.0
Notify marks a ui.State field of a live component whose writes in the browser call handler, a method of the component, with the new value: the compiler reads it.
tab ui.State[string] @ui.Notify(OnTab) q ui.State[string] @ui.Notify(Search).Debounce(300 * time.Millisecond)
A write the server makes (p.tab = "env" in a method) calls nothing: the server knows it.
type OptionGroup ¶ added in v2.15.0
OptionGroup is a labelled group of options, an <optgroup>: a method loading a select's options returns []OptionGroup for grouped choices.
type OptionsCall
deprecated
added in
v2.15.0
type Page ¶
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 ¶
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 ¶
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.
type PageHeader ¶ added in v2.4.0
PageHeader is what the page being rendered says of itself: its title and breadcrumbs, as PageTitle and PageCrumbs read them.
type PageInfo ¶
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 ¶
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 PageVars ¶ added in v2.4.0
type PageVars struct {
Page PageHeader
}
PageVars is PageContext's result: the template variable page.
func PageContext ¶ added in v2.4.0
PageContext is a context processor (package web's ContextProcessors) giving templates the variable page: the page's Title and Crumbs, which a layout's header shows. It reads them as PageTitle and PageCrumbs do.
type ParamError ¶
type ParamError struct {
Page reflect.Type // the page's struct
Method string // the hook's or handler's method: "Add", "mount"
Hook bool // a hook (Mount, OnChange, Loads), not an event handler
Index int // the parameter's position, from 0, the receiver excluded
Type reflect.Type // the parameter's
Dependency bool // a pointer or interface nothing provides
Reason string // "is not provided", "can't come from an event", …
File string // where the method is declared, as the compiler places it
Line int
}
A ParamError is a parameter of a page's hook or event handler nothing fills, as CheckParams reports it.
func CheckParams ¶
func CheckParams(t reflect.Type, inj Injector) []*ParamError
CheckParams reports each parameter of the page t's hooks and event handlers that nothing fills, inj filling what the call doesn't. A hook (what its LiveSchema sets) is reported for any parameter; an event handler — an exported method returning nothing or an error, but its lifecycle's (Render, Mount, Update, Info) and those promoted from what it embeds — for a pointer or interface nothing provides, when the rest of its parameters fit an event (a method taking two values is one the page's own Go calls, and an on… attribute naming it fails as it renders). An app checks its pages with it before serving them. A page backed by its island, whose methods take JSON arguments, isn't checked.
func (*ParamError) Error ¶
func (e *ParamError) Error() string
type PartFallback ¶ added in v2.9.0
type PartFallback struct{ Pending, Error Node }
PartFallback is what a part shows while its method runs (Pending) and when it fails (Error): Part's fallback, for one with an error of its own. It renders as Pending.
type Parts ¶ added in v2.9.0
type Parts struct {
// contains filtered or unexported fields
}
Parts are the deferred parts of a page rendered for one request: what WithParts puts in its context. The page renders with each part's fallback in a slot, each method starting as the render meets its first part; Stream then writes each part as it arrives.
func WithParts ¶ added in v2.9.0
WithParts is ctx for rendering a page whose deferred parts stream: a part renders its fallback, its method starting at once (o.Limit at a time), in a context canceled when ctx is or Stop is called. Stream writes the parts.
func (*Parts) Stop ¶ added in v2.9.0
func (p *Parts) Stop()
Stop cancels the methods still running: for a page whose parts won't be written (rendered again by a live session, failed), or written already.
func (*Parts) Stream
deprecated
added in
v2.9.0
Stream writes PartsScript and flushes, then each part to w once its method has returned — those of a group (Defer("stats")) together, in the order the page met them — flushing after each batch: a <template data-vk-part> holding its markup and the call of the script moving it into place. A part whose markup meets another part's method running gets that part's slot, filled later in the stream. It returns when every part is written, or the request's context is done; then it stops the methods still running.
Deprecated: use StreamParts, whose parts the runtime moves into place with no inline script, in a response of their own.
func (*Parts) StreamParts ¶ added in v2.13.0
StreamParts writes the parts a request for a page's parts asks for (PartsOptions.Want), as Stream does but on their own, with no script: each a <template data-vk-part="id"> holding its markup and the comment <!--vk-parts:id--> ending it, which the runtime moves into place — those of a group together, in the order the page met them, flushing after each batch. A part asked for that the page no longer has (its markup changed since) is written as failed. It returns when every part is written, or the request's context is done; then it stops the methods still running.
type PartsOptions ¶ added in v2.9.0
type PartsOptions struct {
// Limit is how many methods run at once: DefaultPartLimit when zero.
Limit int
// Pending leaves the methods unrun: the page shows its fallbacks only
// (a HEAD request, a test of the page's first paint).
Pending bool
// Observe, if set, is called as each method starts, with its context
// and name ("Index.Stats"); the context it returns is the one the
// method gets, and done is called when it returns.
Observe func(ctx context.Context, name string) (context.Context, func(err error))
// ErrorText is the message of a part whose method fails and that has
// no Error fallback: "" for the default.
ErrorText func(error) string
// Written, if set, is called as each part is written, with its
// method's name and error (or its markup's): nil for one that rendered.
Written func(name string, err error)
// Want, if set, is the parts a request for a page's parts asks for, by
// their ids (the page's <!--vk-part:id--> marks): only their methods
// run, and StreamParts writes only them, and the parts their markup
// holds. A part the render no longer meets is written as failed.
Want []string
}
PartsOptions are how a page's deferred methods run.
type Password ¶
type Password Field
Password is a masked text field.
type Phase ¶ added in v2.17.0
type Phase struct {
// contains filtered or unexported fields
}
Phase is one side of Animate's transition: classes while it runs (during), at its start (from) and at its end (to).
type PushCall ¶ added in v2.15.0
type PushCall struct {
// contains filtered or unexported fields
}
A PushCall is a call a Push or Options step sends to its page: the method it names and the arguments it read. Package web answers it.
func ParsePushCall ¶ added in v2.15.0
ParsePushCall reads the call of a step sent to a page: ref, the method's reference the page rendered; args, the JSON array of its arguments; form, the JSON object of the enclosing form's fields ({"name": ["value"]}), or "". The reference must be signed with ctx's form key for the page's scope: ctx's (WithPushScope), else its path (PageURL) (ErrPushRef).
func (*PushCall) Cache ¶ added in v2.15.0
Cache is how long the browser may keep the call's reply (ui.Cache); 0 when it may not.
func (*PushCall) Call ¶ added in v2.15.0
Call calls the method on recv, a pointer to a Receiver(): its arguments bound from the call's (a string read into a number or bool parsed as a URL parameter is; a struct from the form when the call passes none for it), its dependencies from ctx's Injector. The result is the reply's JSON, as the runtime applies it to the step's target: {"options"}, {"html"}, {"value"}, {"fields"}, {"js"}, or {} for none.
type PushOption ¶
type PushOption func(*push)
PushOption changes a Push: Value, Read, Cache, Timeout, KeepOnError. A Push tells its options from its arguments by their type, so they may go anywhere among them.
func Cache ¶ added in v2.15.0
func Cache(d time.Duration) PushOption
Cache lets the browser keep a read's reply for d and answer the same call, the same arguments, from it. It makes the Push a read (Read); without it a reply is never kept.
Example:
<select name="country" onChange={ui.JS.Push(c.RegionsOf, ui.This.Value(), ui.Cache(time.Hour)).Into("#region")}>…</select>
func KeepOnError ¶
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 Read ¶ added in v2.15.0
func Read() PushOption
Read makes a Push a read: an HTTP GET to the page's URL, on a fresh copy of the page, rather than a POST (a page that isn't live) or an event on the page's socket (a live one). A read takes nothing but its arguments and changes nothing, so it can run beside the page's events and, with Cache, come from the browser's cache.
Example:
<select name="country" onChange={ui.JS.Push(c.RegionsOf, ui.This.Value(), ui.Read()).Into("#region")}>…</select>
func Timeout ¶
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 ¶
func Value(v any) PushOption
Value sends v to the handler in place of the element's value: its first argument. 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
type Select Field
Select is a dropdown over Options.
type Setter ¶
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 Shared ¶ added in v2.17.0
type Shared struct{}
Shared sends a state's writes to the page's other tabs, which apply them as their own (their watches run): with Keep, a choice made in one tab shows in every tab.
sidebar ui.State[bool] @ui.Keep("sidebar") @ui.Shared
type ShowOption ¶
type ShowOption jsArg
ShowOption changes how Show, Hide, Toggle and Transition work: Display, Transition, Time.
func Display ¶
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 ¶
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 ¶
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 ¶
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 ShowTransition ¶ added in v2.17.0
type ShowTransition struct {
// contains filtered or unexported fields
}
ShowTransition is how a show attribute's element appears and disappears: Fade, Scale, Slide, or Animate's classes.
func Animate ¶ added in v2.17.0
func Animate(d time.Duration, phases ...Phase) ShowTransition
Animate is a transition of classes, d long:
transition={ui.Animate(200*time.Millisecond,
ui.Enter("transition duration-200", "opacity-0 scale-95", "opacity-100 scale-100"),
ui.Leave("transition duration-150", "opacity-100", "opacity-0"))}
func Fade ¶ added in v2.17.0
func Fade(d time.Duration) ShowTransition
Fade fades the element in and out over d.
func Scale ¶ added in v2.17.0
func Scale(d time.Duration) ShowTransition
Scale fades the element in and out over d, growing it from 95%.
func Slide ¶ added in v2.17.0
func Slide(from Side, d time.Duration) ShowTransition
Slide slides the element in from side, fading, and back out, over d.
func (ShowTransition) MarshalJSON ¶ added in v2.17.0
func (t ShowTransition) MarshalJSON() ([]byte, error)
type Skeleton ¶ added in v2.13.0
type Skeleton struct {
// Lines stacks that many lines of text, the last one shorter; 0 is a
// single bone, sized by Class.
Lines int
// Class is added to the bone's classes, or to the lines' wrapper.
Class string
// Attrs are any extra attributes.
Attrs []Attr
}
Skeleton is a placeholder bone, the shape of content still loading — the fallback of a deferred part or a <ui.Suspense>:
<ui.Fallback for={posts}><ui.Skeleton lines={3}/></ui.Fallback>
<ui.Skeleton class="h-32"/>
or in Go, ui.Skeleton{Lines: 3}. It is muted and pulses (not under prefers-reduced-motion), and hidden from assistive technology.
type State ¶
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. A write changes it at once, with no round trip, and the parts of the page that read it follow.
A .vuka.html file declares one as a field of its struct, or at package level for one value the whole page shares:
type Menu struct {
open ui.State[bool]
}
<button aria-expanded={open} onClick={open = !open}>Menu</button>
<ul hidden={!open}>…</ul>
Markup reads a state as a plain variable, in expressions the browser evaluates again when it changes; an on… attribute writes one by assignment (open = !open, tab = "env", n++), which the compiler writes as a chain of JS commands. A method of a live component writes one the same way (p.tab = "env"), and the compiler pushes the command to the page. The server renders a state with its initial value, so the page is right before any script runs.
Get is the value the server renders with; Set is the command setting it, for chains built in Go (ui.JS.Set(s, v) is the same). A state passed as a prop is the same state; Get passes its value.
type StateHost ¶
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 StateOption ¶ added in v2.17.0
type StateOption interface {
// contains filtered or unexported methods
}
StateOption is a field attribute of a ui.State the compiler applies once the state is given: Notify, Keep, Shared.
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 Stream ¶ added in v2.17.0
type Stream[T any] struct { // contains filtered or unexported fields }
Stream is a list a live page sends and then forgets: an unexported field of a live shape (messages ui.Stream[Message]) whose methods queue operations — insert these rows, delete that key, start over — that the next reply carries. Once the reply is written the session drops them, and the browser keeps the rows, applying each batch of operations once, by key. Between replies a stream costs the server a few words, however many rows the browser holds.
A row's key is the key attribute of the row's element, as for any keyed loop; the browser matches rows by the key's text (fmt.Sprint's), so Delete takes the key's value and the server never needs the row. Its markup is a loop over Rows() that is the only content of its element, the container:
<ul class="log">
for _, m := range messages.Rows() {
<li key={m.ID}>{m.Text} <button onClick={ui.JS.Push(Remove, m.ID)}>Delete</button></li>
}
</ul>
or, in Go, List. A row's server handler is a Push of a method of the stream's owner with the row's values as arguments: it names the method, not the row, so a row rendered an hour ago still works. A live component in a row, a closure or a plain method value as a row's handler fail the render. A <ui.Form for> in a row submits as a Push of a method taking the form; failing its checks, it answers with the form's report, which the browser puts in place on that row's form.
The container's onViewportTop and onViewportBottom are ordinary handlers the browser calls when its first or last row comes into view, the event's value that row's key — the edge the browser holds, which the server doesn't track: an infinite list, in either direction.
A stream is tracked state, as an Assign is: a component whose state is all tracked renders again when one of its streams has operations queued, and is skipped otherwise. The server can't count, sort or filter what the browser holds; keep counts in fields beside the stream. The zero Stream is ready to use.
func (*Stream[T]) AssignDirty ¶ added in v2.17.0
AssignDirty is the stream's changed mark: set while it has operations queued.
func (*Stream[T]) Block ¶ added in v2.17.0
func (s *Stream[T]) Block(rows []Node) *StreamBlock
Block is the stream's rows block for this render: rows are what the stream's loop rendered, one per row of Rows, in its order. Its Attrs go on the container, the element it is the only content of. The compiler writes it; Go writes List.
func (*Stream[T]) Delete ¶ added in v2.17.0
Delete queues the removal of the rows with these keys; a key the browser doesn't hold is ignored. A key is matched by its text, as fmt.Sprint writes it.
func (*Stream[T]) Insert ¶ added in v2.17.0
func (s *Stream[T]) Insert(rows ...T)
Insert queues rows at the end; a row whose key the browser already holds is morphed in place instead, and stays where it is. Insert is how a row is updated.
func (*Stream[T]) InsertAt ¶ added in v2.17.0
InsertAt queues rows before the browser's row i (from 0), in the order given; past the last row, at the end, and a negative i is 0. A row whose key the browser holds is morphed in place instead, and stays where it is. A limit trims from the end, as for Prepend: InsertAt(0, rows...) is Prepend(rows...).
func (*Stream[T]) Limit ¶ added in v2.17.0
func (s *Stream[T]) Limit(n int) StreamLimit
Limit is the most rows the browser keeps (0, the default: no limit). A batch adding rows trims from the end away from where they went in: Insert trims from the start, Prepend and InsertAt from the end. A row replaced in place trims nothing. It takes effect at the next batch.
The limit it returns fixes the end it trims instead, wherever rows go in: a newest-first feed keeps its newest rows at the top whether it prepends what arrives or inserts older rows at the bottom.
f.events.Limit(50).TrimEnd()
func (*Stream[T]) List ¶ added in v2.17.0
List is the stream's container: an element tag with attrs and the stream's attributes, holding the queued rows, each what row makes of it — one element with a key. It is what a stream's markup lowers to.
c.messages.List("ul", []ui.Attr{{Name: "class", Value: "log"}}, func(m Message) ui.Node {
return ui.El("li", []ui.Attr{{Name: "key", Value: m.ID}}, ui.Text(m.Text))
})
func (*Stream[T]) Prepend ¶ added in v2.17.0
func (s *Stream[T]) Prepend(rows ...T)
Prepend queues rows at the start, in the order given; a row whose key the browser holds is morphed in place instead.
func (*Stream[T]) Reset ¶ added in v2.17.0
func (s *Stream[T]) Reset(rows ...T)
Reset queues replacing every row the browser holds with rows, in order: those whose keys it holds are morphed in place, the others go. With a limit, only the first limit rows are kept — the last, when the limit trims the start (TrimStart).
func (*Stream[T]) Rows ¶ added in v2.17.0
func (s *Stream[T]) Rows() []T
Rows is the rows queued since the last reply, in the order their operations apply (a Prepend's or an InsertAt's last row first, each going before the one queued after it): what the next render sends. A stream's loop ranges over it, and nothing else may read it — it isn't what the browser shows.
type StreamBatch ¶ added in v2.17.0
type StreamBatch struct {
Name string
Batch string
Reset bool
Inserts, Deletes int
Limit int
Trim string // the end the limit trims, when TrimStart or TrimEnd fixed it: "start", "end"
}
StreamBatch is what a stream's batch did, for a development toolbar.
func FlushStreams ¶ added in v2.17.0
func FlushStreams(c Stateful) []StreamBatch
FlushStreams ends the batches of c's streams that its last render sent, once the reply carrying them is written: their operations are dropped, and the next render starts the next batch. A stream whose container that render didn't show keeps its operations. It returns what each flushed batch did.
type StreamBlock ¶ added in v2.17.0
type StreamBlock struct {
// contains filtered or unexported fields
}
StreamBlock is a stream's rows in one render (Stream.Block): the batch of operations its container applies, and the rows they insert.
func (*StreamBlock) Attrs ¶ added in v2.17.0
func (b *StreamBlock) Attrs() []Attr
Attrs is the container's stream attributes: data-vk-stream (the field's name), data-vk-batch (generation.number), data-vk-limit, and, when the render has operations, data-vk-ops — with, for a batch starting with a reset, the rows it leaves (data-vk-rows, data-vk-empty). The attributes a batch adds come last, from data-vk-ops on: the session takes them off the render it keeps once the reply is written.
type StreamLimit ¶ added in v2.17.0
type StreamLimit struct {
// contains filtered or unexported fields
}
StreamLimit is a stream's limit as Limit set it, to fix the end it trims.
func (StreamLimit) TrimEnd ¶ added in v2.17.0
func (l StreamLimit) TrimEnd()
TrimEnd has the limit trim the stream's end (its last rows), wherever a batch's rows went in: rows inserted at the end of a full stream are dropped, unless the browser holds their keys already.
func (StreamLimit) TrimStart ¶ added in v2.17.0
func (l StreamLimit) TrimStart()
TrimStart has the limit trim the stream's start (its first rows), wherever a batch's rows went in. A Reset with more rows than the limit keeps the last.
type StreamPusher ¶ added in v2.17.0
StreamPusher is a live host that names a Push in a stream row by the method it calls, which its owner's instance takes by name: the row holds no handler. Package live implements it.
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 ¶
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 Summary ¶ added in v2.8.0
type Summary struct {
// For is the form, when the summary is outside its <ui.Form>.
For any
// Title is the heading; "There is a problem" by default.
Title string
Class string
}
Summary is a form's error summary, which a failed submit shows: "There is a problem", then each error, linking to its field's control, in the words the field shows. <ui.Form for> puts one at the top of the form; a <ui.Summary/> inside it puts it there instead. The browser moves focus to it, and the page's title starts "Error: ".
type SummaryItem ¶ added in v2.14.0
SummaryItem is one line of an error summary.
type Tab ¶
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 ¶
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
type Tabs ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
func (Target) Page ¶
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 ¶
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 ¶
type Textarea Field
Textarea is a multi-line text field.
type Tile ¶
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 ¶
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 ¶
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 ¶
func (c ToastContainer) View() Node
type ToastContainerProps
deprecated
type ToastContainerProps = ToastContainer
ToastContainerProps is ToastContainer, by its former name.
Deprecated: use ToastContainer: ui.ToastContainer{…}, or <ui.ToastContainer …> in a template.
type ToastPosition ¶
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
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 ¶
type TreeList struct {
Items []*Tree
Keys []string
// Stream marks a stream's rows block (Stream.Block): the batch of one
// render, which the session empties once the reply carrying it is
// written, so the next render diffs against no rows.
Stream bool
}
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 ¶
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. On a component, the field is filled from the URL as it renders and whenever the URL changes, and an event assigning it writes the URL (see URLFields). A bare @ui.URL, URL(""), binds the route's path parameter of the field's name; Default gives the value it takes when the URL has no parameter for it.
func (URL) Apply ¶
func (u URL) Apply(o *FieldOptions)
func (URL) Default ¶ added in v2.4.0
func (u URL) Default(v any) URLDefault
Default is the URL attribute with the value the field takes when the URL has no parameter for it: @ui.URL("page").Default(1).
type URLDefault ¶ added in v2.4.0
URLDefault is @ui.URL("page").Default(1): the URL attribute with the value the field takes when the URL has no parameter for it. A field holding its default leaves the parameter out of the URL.
func (URLDefault) Apply ¶ added in v2.4.0
func (d URLDefault) Apply(o *FieldOptions)
type URLEditor ¶ added in v2.4.0
type URLEditor interface {
// EditURL applies edit to the page's query; push adds a history entry
// instead of taking the current one's place.
EditURL(edit func(url.Values), push bool)
// Query is the page's query as its event sees it: with the edits made
// so far.
Query() url.Values
}
URLEditor changes the URL of a live page from one of its events: its session, which a handler's context carries (WithURLEditor). Package live implements it.
type URLFields ¶ added in v2.4.0
type URLFields struct {
// contains filtered or unexported fields
}
URLFields keeps a live component instance's @ui.URL fields in step with its page's URL: package live holds one per instance and calls Fill as its tag renders, Snapshot before an event and Changes after it.
func (*URLFields) Changes ¶ added in v2.4.0
Changes writes into q the URL-bound fields of c the event changed since Snapshot, under prefix, and reports whether there was one: a field holding its default (or the zero value, without one) leaves its parameter out. A prop the parent passes (tag) and a path parameter are never written.
func (*URLFields) Fill ¶ added in v2.4.0
func (u *URLFields) Fill(ctx context.Context, c, tag Stateful, prefix string, routed bool, q url.Values) bool
Fill sets c's URL-bound fields from the URL (its query q, and the path parameters of ctx's page) where the URL changed since the last Fill, or every one the first time; a prop the parent passes in tag (not its zero value) is the parent's, and on a routed page (routed) the page's exported fields are the route's to bind. A prop the parent leaves out is set every time: the tag's render reset it. It reports whether it changed a field.
type UploadError ¶ added in v2.17.0
An UploadError is why Upload refused a file: Rule is "max" (too large), "accept" (not what the field takes) or "failed" (the ticket isn't valid, or storing failed); Status the HTTP status saying so.
func (*UploadError) Error ¶ added in v2.17.0
func (e *UploadError) Error() string
func (*UploadError) Unwrap ¶ added in v2.17.0
func (e *UploadError) Unwrap() error
type Uploaded ¶ added in v2.17.0
An Uploaded is a file Upload stored: the reference its field takes, its name and size.
func Upload ¶ added in v2.17.0
func Upload(ctx context.Context, ticket, name, contentType string, body io.Reader) (Uploaded, error)
Upload stores a file sent for a File field, what body reads, presented with the ticket the field rendered (its _vk_upload field), the name and type the browser gave it. It reads no more than the field's largest size and one byte: a larger file is refused as it streams. Package web answers uploads with it.
type ValueCondition ¶
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 ¶
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 ¶
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 ¶
func (c ValueCondition) MarshalJSON() ([]byte, error)
func (ValueCondition) Not ¶
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 ¶
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 ¶
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 VarSource ¶ added in v2.4.0
type VarSource interface {
// VarVersion is the version of the variable name as a read with ctx
// would find it now: the same version for the same value. It may run
// the variable's processor again when what that processor read
// changed.
VarVersion(ctx context.Context, name string) uint64
}
VarSource is what keeps a render's template variables: package web's store of its context processors' results. A live session asks it, before keeping an instance's last render, for the current version of each variable that render read.
func VarSourceOf ¶ added in v2.4.0
VarSourceOf is the VarSource of ctx, nil when it has none.
type Variant ¶
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" )
type Variants ¶ added in v2.17.0
type Variants struct {
Base string
Variants map[string]map[string]string
Defaults map[string]string
}
Variants are a component's classes by its props, as cva writes them: Base always, and for each variant the classes of the value it is given, or its default.
var alert = ui.Variants{
Base: "flex items-start gap-2 rounded-lg border px-4 py-3 text-sm",
Variants: map[string]map[string]string{
"tone": {"error": "border-red-200 bg-red-50 text-red-800", "info": "border-border bg-gray-50"},
},
Defaults: map[string]string{"tone": "info"},
}
<div class={alert.Class("tone", Tone, "class", Class)}>
Class merges them (MergeClasses): a variant's utility wins over Base's in its group, and the classes given as "class", the caller's, over both.
func (Variants) Class ¶ added in v2.17.0
Class is the classes for the values given, name then value — "tone", Tone — with "class" naming classes added last, the caller's. A variant given no value, or "", takes its default, else adds nothing. A name that isn't a variant, or a value it doesn't have, fails the render (E0371).
Source Files
¶
- actions.go
- alert.go
- alert.vuka.html
- assign.go
- await.go
- badge.go
- badge.vuka.html
- bindvalue.go
- button.go
- button.vuka.html
- card.go
- card.vuka.html
- classes.go
- context.go
- datatable.go
- datatable.vuka.html
- derive.go
- elbox.go
- field.go
- field.vuka.html
- file.go
- form.go
- form.vuka.html
- formattrs.go
- formbind.go
- formcheck.go
- formcomp.go
- formctl.go
- formedit.go
- formmodel.go
- formref.go
- formstate.go
- formtype.go
- formvalidate.go
- frame.go
- html.go
- http.go
- icon.go
- image.go
- image.vuka.html
- inject.go
- island.go
- island_defer.go
- island_fields.go
- island_page.go
- js.go
- kit.go
- lazy.go
- lazyframe.go
- link.go
- live.go
- livehooks.go
- liveschema.go
- methodprops.go
- modal.go
- modal.vuka.html
- must.go
- node.go
- options.go
- page.go
- pagination.go
- part.go
- props.go
- push.go
- record.go
- showattr.go
- skeleton.vuka.html
- slot.go
- state.go
- stream.go
- streamform.go
- suspense.go
- table.go
- table.vuka.html
- tabs.go
- tabs.vuka.html
- template.go
- templattrs.go
- theme.go
- tile.go
- tile.vuka.html
- toast.go
- toast.vuka.html
- toast_container.vuka.html
- tree.go
- uigen_bridge.go
- update.go
- url.go
- urlstate.go
- validate.go
- variants.go
- vars.go
- walk.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package forms is the error model of vuka's forms: what is wrong with a field or a whole form, as data — its path, the rule it broke, the rule's parameters and a message key — and the one function that turns an error into the words a visitor reads.
|
Package forms is the error model of vuka's forms: what is wrong with a field or a whole form, as data — its path, the rule it broke, the rule's parameters and a message key — and the one function that turns an error into the words a visitor reads. |
|
internal
|
|
|
bridge
Package bridge is how package uigen reaches what package ui keeps unexported: ui sets these when it is initialised.
|
Package bridge is how package uigen reaches what package ui keeps unexported: ui sets these when it is initialised. |
|
tmpltest
Package tmpltest holds the components ui's template tests render: each written in a .vuka.html file, compiled with ui as their target.
|
Package tmpltest holds the components ui's template tests render: each written in a .vuka.html file, compiled with ui as their target. |
|
track
Package track holds the server state a live session tracks.
|
Package track holds the server state a live session tracks. |
|
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 uigen is what the vuka compiler's output calls for client state and tracked server state: the operations a .vuka.html file's reads and writes of states lower to.
|
Package uigen is what the vuka compiler's output calls for client state and tracked server state: the operations a .vuka.html file's reads and writes of states lower to. |
|
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: |