Documentation
¶
Overview ¶
Package view renders templ components from nexus handlers and makes them reactive without a JavaScript build. State lives in components; markup that reads a signal stays current in the browser; on* attributes take actions; a component that reads a signal on the server re-renders there.
templ Counter() {
{{ count := view.State(ctx, 0) }}
<button onclick={ count.Set(count.Get() + 1) }>+1</button>
<p>Clicked { count.Get() } times</p>
}
nexus.Run(cfg, view.Page("GET", "/", Counter))
nexus dev and nexus build compile the templates — the reactive parts to JavaScript — with no configuration; the files stay plain templ for editors. The generator is package viewgen.
Index ¶
- Constants
- Variables
- func Assets(prefix string, handler http.Handler, gates ...nexus.RestOption) nexus.Option
- func Attrs(static templ.Attributes, parts ...templ.OrderedAttributes) templ.Attributes
- func Behaviors() templ.Component
- func Bind(name, id string, caps Caps, value any) templ.OrderedAttributes
- func Broadcast(ctx context.Context, topic string, data any) int
- func CSRF() templ.Component
- func CancelUpload(u *Upload, ref string) templ.ComponentScript
- func Change(method any) templ.ComponentScript
- func ChangeTo(recv any, name string) templ.ComponentScript
- func Commands(ops ...JSOp) string
- func Component[T any](id string, props any) templ.Component
- func ContextProcessor(fn any) nexus.Option
- func CurrentURL(ctx context.Context) *url.URL
- func Do(fn func(e Event)) templ.ComponentScript
- func Enter(ctx context.Context, name string) context.Context
- func Expose[T any]() nexus.Option
- func FromContext[T any](ctx context.Context) T
- func HTML() nexus.RestOption
- func IslandServer(url string) nexus.Option
- func JS(ops ...JSOp) templ.ComponentScript
- func Link(href string, attrs ...templ.Attributes) templ.Component
- func LiveKey(t reflect.Type) string
- func NewIsland[P any](name string) func(props P, opts ...IslandOption) templ.Component
- func OnAttr(event, id string, caps Caps, _ templ.ComponentScript) templ.OrderedAttributes
- func Page(method, path string, component func() templ.Component, ...) *nexus.Route
- func RegisterTwins(m map[string]string)
- func RenderForm(f AnyForm, extras ...any) templ.Component
- func RuntimeJS() string
- func Script() templ.Component
- func ScriptAttr(event templ.ComponentScript) string
- func Send(method any, args ...any) templ.ComponentScript
- func SendTo(recv any, name string, args ...any) templ.ComponentScript
- func Shard(component any, opts ...nexus.RestOption) nexus.Option
- func ShardEnd(component any, args []any, reads []any) templ.Component
- func ShardStart() templ.Component
- func Submit(method any) templ.ComponentScript
- func SubmitTo(recv any, name string) templ.ComponentScript
- func Text(id string, caps Caps, value any) templ.Component
- func UpdateComponent[T any](ctx context.Context, id string, props any) error
- func Use[T any](ctx context.Context) T
- func UseRelay(r Relay) nexus.Option
- func Value(v any) templ.Attributes
- func When(id string, caps Caps, show bool) templ.Component
- type AnyForm
- type Assign
- type Caps
- type Choice
- type Condition
- type Element
- type ElementEq
- type ElementIs
- type ElementRead
- type Event
- type EventTarget
- type Form
- func (f Form) Changed(field string) bool
- func (f Form) ChoicesFor(ctx context.Context, field string) []Choice
- func (f Form) Dirty() bool
- func (f Form) Error() string
- func (f Form) F(name string) FormField
- func (f Form) FieldNames() []string
- func (f *Form) Load(v any)
- func (f *Form) Reset()
- func (f Form) Submitted() bool
- func (f *Form) Update(fn func())
- func (f Form) Valid() bool
- type FormErrors
- type FormField
- type FormOption
- type IslandOption
- type JSOp
- func AddClass(classes string, sel Element, opts ...JSOption) JSOp
- func Confirm(message string) JSOp
- func Copy(sel Element, opts ...JSOption) JSOp
- func CopyText(text string) JSOp
- func Debounce(d time.Duration) JSOp
- func Dispatch(event string, sel Element, opts ...JSOption) JSOp
- func Else() JSOp
- func ElseIf(cond Condition, opts ...JSOption) JSOp
- func Exec(attr string, sel Element, opts ...JSOption) JSOp
- func Focus(sel Element, opts ...JSOption) JSOp
- func FocusFirst(sel Element, opts ...JSOption) JSOp
- func Hide(sel Element, opts ...JSOption) JSOp
- func If(cond Condition, opts ...JSOption) JSOp
- func PopFocus() JSOp
- func Push(method any, args ...any) JSOp
- func PushFocus(sel Element, opts ...JSOption) JSOp
- func PushTo(recv any, name string, args ...any) JSOp
- func Reload() JSOp
- func RemoveAttr(name string, sel Element, opts ...JSOption) JSOp
- func RemoveClass(classes string, sel Element, opts ...JSOption) JSOp
- func ScrollTo(sel Element, opts ...JSOption) JSOp
- func SetAttr(name, value string, sel Element, opts ...JSOption) JSOp
- func SetCookie(name, value string, opts ...JSOption) JSOp
- func SetValue(value string, sel Element, opts ...JSOption) JSOp
- func Show(sel Element, opts ...JSOption) JSOp
- func Throttle(d time.Duration) JSOp
- func Toggle(sel Element, opts ...JSOption) JSOp
- func ToggleAttr(name, value string, sel Element, opts ...JSOption) JSOp
- func ToggleClass(classes string, sel Element, opts ...JSOption) JSOp
- func Transition(classes string, sel Element, opts ...JSOption) JSOp
- func (o JSOp) AddClass(classes string, sel Element, opts ...JSOption) JSOp
- func (o JSOp) Confirm(message string) JSOp
- func (o JSOp) Copy(sel Element, opts ...JSOption) JSOp
- func (o JSOp) CopyText(text string) JSOp
- func (o JSOp) Debounce(d time.Duration) JSOp
- func (o JSOp) Dispatch(event string, sel Element, opts ...JSOption) JSOp
- func (o JSOp) Else() JSOp
- func (o JSOp) ElseIf(cond Condition, opts ...JSOption) JSOp
- func (o JSOp) Exec(attr string, sel Element, opts ...JSOption) JSOp
- func (o JSOp) Focus(sel Element, opts ...JSOption) JSOp
- func (o JSOp) FocusFirst(sel Element, opts ...JSOption) JSOp
- func (o JSOp) Hide(sel Element, opts ...JSOption) JSOp
- func (o JSOp) If(cond Condition, opts ...JSOption) JSOp
- func (o JSOp) PopFocus() JSOp
- func (o JSOp) Push(method any, args ...any) JSOp
- func (o JSOp) PushFocus(sel Element, opts ...JSOption) JSOp
- func (o JSOp) PushTo(recv any, name string, args ...any) JSOp
- func (o JSOp) Reload() JSOp
- func (o JSOp) RemoveAttr(name string, sel Element, opts ...JSOption) JSOp
- func (o JSOp) RemoveClass(classes string, sel Element, opts ...JSOption) JSOp
- func (o JSOp) ScrollTo(sel Element, opts ...JSOption) JSOp
- func (o JSOp) SetAttr(name, value string, sel Element, opts ...JSOption) JSOp
- func (o JSOp) SetCookie(name, value string, opts ...JSOption) JSOp
- func (o JSOp) SetValue(value string, sel Element, opts ...JSOption) JSOp
- func (o JSOp) Show(sel Element, opts ...JSOption) JSOp
- func (o JSOp) Then(next ...JSOp) JSOp
- func (o JSOp) Throttle(d time.Duration) JSOp
- func (o JSOp) Toggle(sel Element, opts ...JSOption) JSOp
- func (o JSOp) ToggleAttr(name, value string, sel Element, opts ...JSOption) JSOp
- func (o JSOp) ToggleClass(classes string, sel Element, opts ...JSOption) JSOp
- func (o JSOp) Transition(classes string, sel Element, opts ...JSOption) JSOp
- type JSOption
- type LiveRouter
- type LiveView
- func (v *LiveView) Connected() bool
- func (v *LiveView) Flash(kind string) string
- func (v *LiveView) ID() string
- func (v *LiveView) PushEvent(name string, payload any)
- func (v *LiveView) PushJS(ops ...JSOp)
- func (v *LiveView) PushNavigate(href string)
- func (v *LiveView) PushPatch(href string)
- func (v *LiveView) PutFlash(kind, msg string)
- func (v *LiveView) Subscribe(topics ...string)
- func (v *LiveView) Track(topic, key string, meta any)
- func (v *LiveView) Untrack(topic, key string)
- type MemoryRelay
- type Message
- type Presence
- type PresenceDiff
- type PresenceMeta
- type Rec
- type Relay
- type Signal
- type Stream
- func (s *Stream[T]) Attrs() templ.Attributes
- func (s *Stream[T]) Configure(id func(T) string)
- func (s *Stream[T]) Delete(items ...T)
- func (s *Stream[T]) DeleteID(id string)
- func (s *Stream[T]) ID(item T) string
- func (s *Stream[T]) Insert(items ...T)
- func (s *Stream[T]) InsertAt(i int, item T)
- func (s *Stream[T]) Items() []T
- func (s *Stream[T]) Limit(n int)
- func (s *Stream[T]) Prepend(items ...T)
- func (s *Stream[T]) Reset(items ...T)
- type Targetdeprecated
- type ThisElementdeprecated
- type ThisValuedeprecated
- type Upload
- type UploadConfig
- type UploadEntry
Constants ¶
const DefaultIslandServer = "http://127.0.0.1:13715"
DefaultIslandServer is where SSR islands render unless IslandServer says otherwise: the port node web/dist/ssr/islands.js listens on by default.
const LiveTag = "view.live"
LiveTag is the registry.Endpoint.Tags key on a live page's GET route; its value is LiveKey of the page's type. It is how tools (viewtest.Mount) find where a live page is served.
Variables ¶
var LiveIdleTrim = 2 * time.Minute
LiveIdleTrim is how long a live page may sit without events or pushes before the server lets go of the render tree it keeps for diffing; the next reply then carries the whole tree. An idle tab costs its connection and its state, not a copy of its page.
var PresenceTTL = 30 * time.Second
PresenceTTL is how long a replica's presences last without word from it.
var ResumeGrace = 30 * time.Second
ResumeGrace is how long a page's state waits for its connection to come back.
Functions ¶
func Assets ¶
Assets serves handler under prefix — how a component library's files (templUI's /templui/js/, say) or a built stylesheet reach the browser:
mux := http.NewServeMux()
utils.SetupScriptRoutes(mux, dev) // templUI's script routes
view.Assets("/templui/js/", mux)
view.Assets("/assets/", http.FileServerFS(assetsFS))
The handler sees the request's full path. Assets are public — a sign-in page needs its stylesheet — so they skip auth's deny-by-default; gate one that isn't with gates (auth.Required()).
func Attrs ¶
func Attrs(static templ.Attributes, parts ...templ.OrderedAttributes) templ.Attributes
Attrs merges compiled attributes into a templ.Attributes — what a templ.Attributes{…} literal with reactive entries compiles to, so a component library's Props.Attributes can carry actions and bindings.
func Behaviors ¶ added in v2.23.0
Behaviors loads behaviors.js: what a page's markup asks for with data-nx attributes and no styling — a box filtering a list, a "select all" box, a form's submit enabled once it is valid. Put it after Script:
@view.Script() @view.Behaviors()
func Bind ¶
func Bind(name, id string, caps Caps, value any) templ.OrderedAttributes
Bind renders an attribute that reads a signal: its server value plus the compiled expression that keeps it current.
func Broadcast ¶
Broadcast sends data to every live page subscribed to topic — from an event, a handler, a job, anywhere. Each page runs its Info and re-renders. It reports how many pages on this replica it reached; with a Relay (UseRelay) the pages of the other replicas get it too.
func CSRF ¶ added in v2.22.0
CSRF is the hidden field that carries the request's CSRF token in a form posted over plain HTTP — a sign-in page, a page without the view runtime:
<form method="post" action={ SignIn.URL(ctx) }>
@view.CSRF()
…
</form>
It renders nothing when CSRF is off. A live page's forms need none: the runtime adds the token as they submit.
func CancelUpload ¶ added in v2.16.0
func CancelUpload(u *Upload, ref string) templ.ComponentScript
CancelUpload is an event for an on* attribute: it stops the entry ref of u — on its way or done — and removes it.
func Change ¶
func Change(method any) templ.ComponentScript
Change sends the form's fields to method as they change (debounced), for validation as the user types — on a form's oninput or onchange:
<form onsubmit={ view.Submit(b.Add) } oninput={ view.Change(b.Validate) }>
func Commands ¶ added in v2.22.0
Commands is ops for an attribute Exec reads: data-cancel={ view.Commands(…) }.
func Component ¶ added in v2.16.0
Component places the live view T in a live view's template: id tells it apart from the others of its type there, and props are what its Mount and Update take (nil when they take none).
@view.Component[*Cart]("cart", CartProps{User: p.User.Get()})
A T that takes dependencies is registered with view.Live[T] — with a path, or "" to embed it only; one that takes none needs nothing.
func ContextProcessor ¶ added in v2.25.0
ContextProcessor registers fn as the source of a value every template can read with FromContext — what the layout needs on every page (the signed-in user's name, unread counts, the navigation), computed on the server from the request, as Django's context processors are:
type Layout struct {
User string
Unread int
}
view.ContextProcessor(func(ctx context.Context, inbox *Inbox) (Layout, error) {
u := auth.Current(ctx)
return Layout{User: u.ID, Unread: inbox.Unread(ctx, u.ID)}, nil
})
{{ l := view.FromContext[Layout](ctx) }}
<span>{ l.User }</span>
fn takes ctx — the request's, or a live page's connection's, with the visitor's identity — then any dependencies the app's DI container provides, and returns the value, with or without an error. Its result type names it: one processor per type. It runs at most once per render, and only when a template reads it; an error fails the render.
func CurrentURL ¶ added in v2.26.0
CurrentURL is the URL of the page ctx renders: the request's for a page, the one the browser shows for a live page — kept current as view.Link or PushPatch patches it — and for a shard's re-render, the page it sits on. Breadcrumbs, an active menu entry or a context processor read it:
view.ContextProcessor(func(ctx context.Context) Crumbs {
return crumbsFor(view.CurrentURL(ctx).Path)
})
It is a copy, empty when ctx renders no page.
func Do ¶
func Do(fn func(e Event)) templ.ComponentScript
Do is an action written as a Go function — for one that reads the event or takes more than one step:
oninput={ view.Do(func(e view.Event) { q.Set(e.Target.Value) }) }
The Go compiler type-checks fn; the generator compiles it to JavaScript. It never runs on the server.
func Enter ¶
Enter opens a component's scope. Generated code calls it at the top of every component in a file that imports this package.
func Expose ¶
Expose makes a DI value available to templates through Use:
nexus.Run(cfg, nexus.Provide(NewPetStore), view.Expose[*PetStore](), …)
func FromContext ¶ added in v2.25.0
FromContext is the value of T's ContextProcessor for this render. It panics when no processor returns T, and when the processor fails.
func HTML ¶
func HTML() nexus.RestOption
HTML renders a handler's templ.Component result as the page — for a handler that builds its component from request data:
nexus.AsRest("GET", "/pets/:id", NewPetPage, view.HTML())
func IslandServer ¶
IslandServer sets the address of the islands server SSR islands render on (DefaultIslandServer when unset) — for one on another port or host:
nexus.Boot(view.IslandServer("http://127.0.0.1:14000"))
The server reads its port from NEXUS_ISLANDS_PORT.
func JS ¶ added in v2.22.0
func JS(ops ...JSOp) templ.ComponentScript
JS is a list of commands the browser runs on an event, in order, without a round trip unless one of them is Push — Phoenix LiveView's JS commands. Commands chain, each step a method of the one before:
<button onclick={ view.JS(view.Show("#confirm").Focus("#confirm-ok")) }>Delete</button>
<button onclick={ view.JS(view.Confirm("Delete it?").Hide("#confirm").Push(p.Delete, row.ID)) }>Yes</button>
A chain is a value: extending it never changes it, so a shared start is safe to build on (closing := view.Hide("#m").PopFocus(); closing.Push(…)). Separate commands as arguments, view.JS(a, b), run the same as a.Then(b).
What a command changes survives the live page's re-renders: the page keeps an element shown, a class added or an attribute set until the server renders that attribute differently, which then wins.
func Link ¶
func Link(href string, attrs ...templ.Attributes) templ.Component
Link is an in-app link: following it replaces the page without reloading the document — the new page is fetched, patched into the current one, live pages connect and disconnect as needed, and the address bar and the back button work as usual. A modified click (a new tab) or a link to another site behaves as a plain link.
@view.Link("/board") {
Adoption board
}
@view.Link("/pets", templ.Attributes{"class": "underline"}) {
Pets
}
The href is sanitized like templ's own URLs (no javascript:).
func LiveKey ¶
LiveKey names a live page's type T (a pointer to a struct) in LiveTag: its package path and type name.
func NewIsland ¶
func NewIsland[P any](name string) func(props P, opts ...IslandOption) templ.Component
NewIsland declares an island: a component of the project's Vite frontend that templ pages mount — a Vue (.vue) or React (.tsx, .jsx) component, or a module exporting mount(el, props), under web/src/islands, named by its path there without the extension. Declare it once, at package level:
var Chart = view.NewIsland[ChartProps]("Chart")
and place it like a component; its children are rendered on the server and stay until the island mounts:
@Chart(ChartProps{Points: pts}, view.Visible()) {
<div class="h-64 animate-pulse"></div>
}
P must encode to a JSON object; the client SDK types it for the component as NexusIslandProps["Chart"]. Its *view.Signal fields stay live in the browser: the island gets the value, and is updated when the signal changes. A Vue island sets one back with emit('update:field', v) (defineModel), a React island with props.setField(v).
An island mounts as soon as the page loads, or later with Idle, Visible or Media, and SSR renders it on the server too. On a live page a re-render with new props updates the mounted island rather than remounting it, and in-app navigation unmounts islands that leave the page.
The loader comes from the Vite dev server while one runs (nexus dev), and from the build's manifest otherwise; the frontend is the one nexus.Frontend serves. Without one — no frontend, or a build without this island — the children stay, the reason is logged once and set as the element's data-error, and the page still renders: in a Go test, say.
func OnAttr ¶
func OnAttr(event, id string, caps Caps, _ templ.ComponentScript) templ.OrderedAttributes
OnAttr renders a compiled action for an on* attribute.
func Page ¶
func Page(method, path string, component func() templ.Component, opts ...nexus.RestOption) *nexus.Route
Page serves a component at method + path:
view.Page("GET", "/", Home, auth.Required())
The route is named after the component (Home → "home"), and the returned handle builds its URL: view.Page(…).URL(ctx).
func RegisterTwins ¶
RegisterTwins adds compiled expressions, keyed by id. Generated code calls it from init.
func RenderForm ¶ added in v2.22.0
RenderForm renders a Form's form element — its fields are the children — wired to the page. The first method among extras is the submit (it runs only when every rule passes); without one, the form's own Save method takes it. A second method is the change method — the form is then checked as the user types, as with view.LiveValidation — and the other extras are view.ConfirmLeave, view.FormAttrs or a templ.Attributes. The kit's ui.Form wraps it; use it directly for markup of your own.
func RuntimeJS ¶
func RuntimeJS() string
RuntimeJS is the browser runtime, for tests that run compiled expressions outside a browser.
func Script ¶
Script loads the browser runtime and the page's compiled expressions. Put it in the document head:
<head>
@view.Script()
</head>
func ScriptAttr ¶
func ScriptAttr(event templ.ComponentScript) string
ScriptAttr is a live event (Send, Submit, Change) as attribute text, for an attribute map: templ renders a script only on an element's own on* attribute, so the generator rewrites templ.Attributes{"onclick": view.Send(…)} to use this.
func Send ¶
func Send(method any, args ...any) templ.ComponentScript
Send is an event for an on* attribute: it calls method — a method value of the live page, such as l.Cancel — on the server with args.
<button onclick={ view.Send(l.Cancel, o.ID) }>cancel</button>
args are encoded when the page renders; the server decodes them into the method's argument parameters.
func SendTo ¶
func SendTo(recv any, name string, args ...any) templ.ComponentScript
SendTo is Send for the method named name on recv, for a live page whose type is generic: Go builds a generic type's method values as closures that don't carry the method's name, so Send can't read it. It panics, as Send does, when recv has no such method.
<button onclick={ view.SendTo(p, "Edit", row.ID) }>edit</button>
func Shard ¶
func Shard(component any, opts ...nexus.RestOption) nexus.Option
Shard registers a component the server re-renders when a signal it reads on the server changes — one whose {{ }} code, for loops or component arguments read a signal:
templ PetResults(q *view.Signal[string]) {
{{ pets := view.Use[*PetStore](ctx).Search(q.Get()) }}
…
}
nexus.Run(cfg, view.Shard(PetResults, auth.Required()), …)
Its endpoint is a nexus op: opts gate it exactly as they gate any route. The page's own gates do not run for it, and its arguments and signals arrive from the browser — validate them. The generator refuses a component that reads a signal on the server without a registration.
func ShardEnd ¶
ShardEnd closes a shard component's output with what the browser needs to re-render it: the component, its place on the page, its arguments, the signals it reads on the server, and the signals it owns. Generated code calls it last.
func ShardStart ¶
ShardStart opens a shard component's output. Generated code calls it first in a component registered with Shard.
func Submit ¶
func Submit(method any) templ.ComponentScript
Submit is a form's onsubmit on a live page: the browser sends the form's fields to method, whose last parameter is a struct bound from them with `form:"name"` tags — as a REST form binds — or url.Values, the fields as sent, for a page whose form isn't one struct (a generic editor binds them itself).
<form onsubmit={ view.Submit(b.Add) }>
The struct's validate: tags are checked first. If they fail, or method returns an InvalidInput error (nexus.Invalid()), the page re-renders with them (view.Errors) and the form keeps what was typed; on success the form resets to its server-rendered values.
func SubmitTo ¶
func SubmitTo(recv any, name string) templ.ComponentScript
SubmitTo and ChangeTo are Submit and Change for the method named name on recv, for a live page whose type is generic (see SendTo).
func UpdateComponent ¶ added in v2.16.0
UpdateComponent gives the live view T embedded as id on the page that ctx is an event (or Info) of new props: its Update runs (or Mount, without one) and the page re-renders. The page's template passes its own props again on the next render that changes them.
func Use ¶
Use returns a value from the app's DI container, for a template's server code. A service comes back as is:
{{ pets := view.Use[*PetStore](ctx).Search(q.Get()) }}
A state struct — one with *view.Signal fields — is per page: Use returns a copy for this page whose signals every component shares, starting from the DI instance's values (or, in a shard re-render, the browser's):
type Search struct{ Query *view.Signal[string] }
func NewSearch() *Search { return &Search{Query: view.Initial("")} }
{{ q := view.Use[*Search](ctx).Query }}
The generator exposes every type a template Uses.
func UseRelay ¶ added in v2.15.0
UseRelay makes this app's broadcasts reach the live pages of every replica sharing r:
nexus.Boot(view.UseRelay(viewrelay.New(viewrelay.Config{URL: os.Getenv("REDIS_URL")})), …)
Each broadcast is delivered to this replica's pages at once, as without a relay, and published for the others; a replica ignores its own. Data crosses replicas as JSON: read it with Message.Decode, which works for both. Broadcast still counts only the pages on this replica.
func Value ¶
func Value(v any) templ.Attributes
Value marks a form field server-owned and gives it v as its value: when it hasn't focus, the field shows the server's value after every render, even one that didn't change it — by default a field keeps what the user typed until the server's value changes. Spread it on an input, a select (the option whose value is v is chosen) or a textarea (v is its text):
<input name="title" { view.Value(b.Title)... }/>
<select name="sort" { view.Value(b.Sort)... }> … </select>
<textarea name="notes" { view.Value(b.Notes)... }></textarea>
A nil v is "".
Types ¶
type AnyForm ¶ added in v2.22.0
type AnyForm interface {
F(name string) FormField
FieldNames() []string
ChoicesFor(ctx context.Context, field string) []Choice
Dirty() bool
Valid() bool
Submitted() bool
Error() string
// contains filtered or unexported methods
}
AnyForm is any view.Form, whatever its struct — what the kit's ui.Form takes, and what a page that embeds a Form is itself.
type Assign ¶ added in v2.16.0
type Assign[T any] struct { // contains filtered or unexported fields }
Assign is a piece of a live page's state, as LiveView's assigns are: the page sets it, Render reads it, and the page knows what changed.
type Orders struct {
Status view.Assign[string]
Rows view.Assign[[]Order]
}
func (p *Orders) Filter(ctx context.Context, svc *OrderService, status string) error {
p.Status.Set(status)
p.Rows.Set(svc.List(ctx, status))
return nil
}
templ (p *Orders) Render() {
<h1>Orders · { p.Status.Get() }</h1>
for _, o := range p.Rows.Get() { @OrderRow(o) }
}
A page whose fields are all Assigns (signals may sit beside them) renders only what changed: a part of the template is skipped when none of the Assigns it read last time has changed since, and it doesn't run at all. Render must depend on Assigns alone — not on plain fields, services or the clock — for that to hold; under nexus dev and in tests every skipping render is checked against a full one and a difference is reported.
A page with any other field renders everything, as before — unless the field is tagged view:"-": one Render doesn't read, or that doesn't change once the page is mounted (a configuration pointer, permissions read in Mount). Its zero value is ready to use; Set and Update are for the page's own goroutine — Mount, Params, Info and events.
func (*Assign[T]) Get ¶ added in v2.16.0
func (a *Assign[T]) Get() T
Get returns the value. In Render it notes that this part of the page depends on it.
type Caps ¶
Caps holds the values a compiled expression reads from its surroundings. The generator fills it in; the browser receives each value as it was at render time (a signal as a live reference). Everything in it is visible to the browser, so never let a reactive expression read a secret.
type Choice ¶ added in v2.22.0
Choice is one option of a select field — what a <Field>Choices method returns.
type Condition ¶ added in v2.24.0
type Condition interface {
// contains filtered or unexported methods
}
Condition is what view.If and view.ElseIf test: an Element (it holds when the selector matches anything), a read of one (Checked, Value, Attr), a read's Eq, or Element.Is.
type Element ¶ added in v2.24.0
type Element string
Element is an element of the page, named by a CSS selector: a JS command's target, a value read as an event is sent, and a condition. A selector written in place is one: view.Show("#menu"). Build one from a string with El, or use This for the element the event is on.
view.Toggle("#menu") // a target
view.Send(p.Search, view.El("#q").Value()) // read as the event is sent
view.If(view.El("#agree").Checked()).Push(p.Continue) // a condition
func El ¶ added in v2.24.0
El is the element sel matches — every one, for a command; the first, for a read. Use it for a selector built at render time: view.Show(view.El("#row-" + id)).
func This ¶ added in v2.23.0
func This() Element
This is the element whose event is running — JavaScript's this in its on… attribute (for a command pushed from the server with PushJS, the live view's root):
<input type="checkbox" onchange={ view.Send(p.Toggle, row.ID, view.This().Checked()) }/>
<button onclick={ view.JS(view.AddClass("pressed", view.This()).Push(p.Save)) }>Save</button>
On a form's oninput, this is the form, not the field typed into; send a form's fields with view.Change.
func (Element) Attr ¶ added in v2.24.0
func (e Element) Attr(name string) ElementRead
Attr is the element's attribute name as a string, null when it has none (a pointer parameter is then nil). A number parameter takes it too. As a condition it holds when the element has the attribute.
func (Element) Checked ¶ added in v2.24.0
func (e Element) Checked() ElementRead
Checked is whether a checkbox or radio is checked, as a bool. As a condition it holds when it is.
func (Element) Is ¶ added in v2.24.0
Is is a condition: the element matches the CSS selector css — ":checked", ":placeholder-shown", ".open", "[aria-expanded=true]".
view.If(view.This().Is(":checked")).Show("#extra").Else().Hide("#extra")
func (Element) Value ¶ added in v2.24.0
func (e Element) Value() ElementRead
Value is the element's value as a string, read as the event is sent: what an input, select or textarea holds. A number parameter takes it too. As a condition it holds when the value isn't empty.
type ElementEq ¶ added in v2.25.0
type ElementEq struct {
// contains filtered or unexported fields
}
ElementEq is the condition that a read equals a value; see ElementRead.Eq.
type ElementIs ¶ added in v2.24.0
type ElementIs struct {
// contains filtered or unexported fields
}
ElementIs is the condition that an element matches a CSS selector; see Element.Is.
type ElementRead ¶ added in v2.24.0
type ElementRead struct {
// contains filtered or unexported fields
}
ElementRead is a value read from an element as the event is sent — an event argument of view.Send, view.SendTo or view.Push — and a condition of view.If; see Element.Value.
func (ElementRead) Eq ¶ added in v2.25.0
func (r ElementRead) Eq(value string) ElementEq
Eq is the condition that the read equals value, compared as text: an attribute's value (one the element lacks never equals), a field's value, or "true"/"false" for Checked.
view.If(view.This().Attr("aria-pressed").Eq("true")).
SetAttr("aria-pressed", "false", view.This()).
Else().SetAttr("aria-pressed", "true", view.This())
func (ElementRead) MarshalJSON ¶ added in v2.24.0
func (r ElementRead) MarshalJSON() ([]byte, error)
MarshalJSON writes the marker the runtime replaces with the value read.
type Event ¶
type Event struct {
Target EventTarget
Key string
}
Event is the DOM event an action written with Do receives.
type EventTarget ¶
EventTarget is the element the event fired on.
type Form ¶ added in v2.22.0
type Form struct {
// contains filtered or unexported fields
}
Form makes a struct a live page's form when embedded — the struct is the whole declaration, as a Django form class is. Its tags say what the fields are:
type UserForm struct {
view.Form
Name string `form:"name" label:"Full name" validate:"required"`
Email string `form:"email" validate:"required,email"`
RoleID uint `form:"roleId" label:"Role"`
}
`form:` names a field (others are skipped), `validate:` checks it, `label:` (else the Go name, spaced), `help:`, `placeholder:` and `span:` (width in a 12-column row) say how it shows, and `input:` picks the control where the Go type isn't enough (password, textarea, switch, hidden). Optional methods on the struct complete the declaration:
// Choices of a field — Django's ModelChoiceField: the field renders
// as a select. The receiver is the form's current values, so choices
// may depend on other fields; services come via view.Use.
func (f UserForm) RoleIDChoices(ctx context.Context) []view.Choice {
return view.Use[*RoleService](ctx).Choices(ctx)
}
// Validate — Django's clean(): runs after the tag rules, as the user
// types on a live form and always before the submit, which therefore
// only ever sees valid values.
func (f UserForm) Validate(ctx context.Context) error {
if f.Name == f.Email {
return nexus.Invalid().Field("email", "an e-mail is not a name")
}
return nil
}
// Init — Django's initial: runs once, before the page's Mount.
func (f *UserForm) Init(ctx context.Context) { f.Active = true }
// Save takes the submit when ui.Form is given no method.
func (f *UserForm) Save(ctx context.Context) error { … }
The page holds the form — a field, or embedded — and its fields are the values, read and written directly; the kit renders it (ui.Form):
type Users struct {
view.LiveView
Edit UserForm
}
func (p *Users) Open(ctx context.Context, id uint) error { p.Edit.Load(userRecord(id)); return nil }
func (p *Users) Save(ctx context.Context, f UserForm) error { … } // f passed every rule
templ (p *Users) Render() {
@ui.Form(p.Edit, p.Save)
}
The form keeps what the browser has — the values the user typed, laid over the loaded ones, so a field the page doesn't render keeps its value. A field's error shows once the user has left it, every field's after a submit. A successful submit resets the form to the values it was loaded with; Load and Reset replace what the fields show even where the user typed. A form is tracked like an Assign.
func (Form) Changed ¶ added in v2.22.0
Changed reports whether the change the page is handling — the change method's, or the submit's — altered field.
func (Form) ChoicesFor ¶ added in v2.22.0
ChoicesFor are the choices of the field: what its <Field>Choices method says, given the form's current values; nil without one.
func (Form) Dirty ¶ added in v2.22.0
Dirty reports whether the form's values differ from what it was loaded with.
func (Form) Error ¶ added in v2.22.0
Error is the form's own error, not any field's — a nexus.Invalid().Global from Validate or the submit event.
func (Form) F ¶ added in v2.22.0
F is the field of the form named name (its form: name, or its Go name): what to call it, its value as the form holds it, and its error when it should show. An unknown name is an error naming the fields there are — and, for a form the view compiler can see, a generate-time one.
func (Form) FieldNames ¶ added in v2.22.0
FieldNames lists the form's fields, in the struct's order.
func (*Form) Load ¶ added in v2.22.0
Load gives the form the values to edit, as fresh: no errors, nothing touched, and the fields show these values even where the user typed. v is a value of the struct the Form is embedded in.
func (*Form) Reset ¶ added in v2.22.0
func (f *Form) Reset()
Reset puts back the values the form was loaded with.
func (Form) Submitted ¶ added in v2.22.0
Submitted reports whether a submit failed since the form was loaded.
func (*Form) Update ¶ added in v2.22.0
func (f *Form) Update(fn func())
Update changes the form's values — read them directly, change them here, so the page re-renders what depends on them:
p.Edit.Update(func() { p.Edit.DesignationID = 0 })
The fields show the new values, except one the user is typing in.
type FormErrors ¶
type FormErrors struct {
// contains filtered or unexported fields
}
FormErrors are the validation errors of the event that last ran, for Render to show beside the fields.
func Errors ¶
func Errors(ctx context.Context) FormErrors
Errors returns the validation errors of the page's last event — its InvalidInput error's field map — empty when it succeeded.
if msg := view.Errors(ctx).Field("name"); msg != "" { <p class="error">{ msg }</p> }
func (FormErrors) Field ¶
func (f FormErrors) Field(name string) string
Field is the first message for a field, or "".
func (FormErrors) Global ¶
func (f FormErrors) Global() string
Global is the first message not tied to a field, or "".
type FormField ¶ added in v2.22.0
type FormField struct {
Form string // the form's id
Name string // the form: name the field is sent by
ID string
Label string
Help, Placeholder string
// Kind is the control: input, textarea, checkbox, switch, multiselect —
// and an input renders as a select when the field has choices.
Kind string
Type string // an input's type: text, email, number, date, password, hidden
Span int // width in a 12-column row; 0 is the full row
Value string
Values []string // a multiselect's
Checked bool // a checkbox's
Required bool
Error string // shown once the user left the field, or after a submit
// HasChoices says the form declares choices for the field
// (<Field>Choices); a component gets them with ChoicesFor.
HasChoices bool
}
FormField is one field of a Form, ready for a component to render.
type FormOption ¶ added in v2.22.0
type FormOption interface {
// contains filtered or unexported methods
}
FormOption tunes the form element RenderForm renders.
var LiveValidation FormOption = liveOpt{}
LiveValidation makes the form check its values as the user types: each change goes to the form, and errors show as fields are left. Passing a change method instead does the same and runs the method. The kit names it ui.Live.
func ConfirmLeave ¶ added in v2.22.0
func ConfirmLeave(message ...string) FormOption
ConfirmLeave asks before leaving the page — in-app navigation, or closing the tab — while the form has changes that aren't saved. message is the question (browsers word their own for a closing tab).
func FormAttrs ¶ added in v2.22.0
func FormAttrs(a templ.Attributes) FormOption
FormAttrs adds attributes to the form element.
type IslandOption ¶
type IslandOption func(*island)
IslandOption says when an island mounts, and whether the server renders it.
func Media ¶
func Media(query string) IslandOption
Media mounts the island once the media query matches:
view.Media("(min-width: 768px)")
func SSR ¶
func SSR() IslandOption
SSR renders the island on the server too, so its HTML is in the page before any JavaScript runs (search engines, slow phones); the browser then hydrates it. The server is the bundle nexus build writes when vite.config has nexus({ islands: { ssr: true } }) — run it beside the binary with node web/dist/ssr/islands.js. Under nexus dev, and whenever that server does not answer, the island renders in the browser only.
func Visible ¶
func Visible() IslandOption
Visible mounts the island when it is about to scroll into view.
type JSOp ¶ added in v2.22.0
type JSOp struct {
// contains filtered or unexported fields
}
JSOp is a command of JS, or a chain of them.
func AddClass ¶ added in v2.22.0
AddClass adds classes (space-separated) to the elements sel matches.
func Confirm ¶ added in v2.23.0
Confirm asks message with the browser's confirm dialog; the commands after it run only when the user agrees:
view.JS(view.Confirm("Delete this user?").Push(p.Delete, u.ID))
func Copy ¶ added in v2.23.0
Copy puts on the clipboard the value of the field sel matches, else its text. The element the event is on carries data-copied for a moment after, for CSS to show it.
func Debounce ¶ added in v2.23.0
Debounce runs the steps after it once the event has stopped firing for d: each new event restarts the wait, so a box typed into sends once the typing pauses. Steps before it run at once.
<input oninput={ view.JS(view.Debounce(300*time.Millisecond).Push(p.Search, view.This().Value())) }/>
A debounced chain still waiting inside a form runs before that form's submit, so the submit never overtakes it.
func Dispatch ¶ added in v2.22.0
Dispatch fires a DOM CustomEvent named event on the elements sel matches, bubbling unless NoBubble, with Detail — for islands, scripts and widgets.
func Else ¶ added in v2.24.0
func Else() JSOp
Else starts the steps that run when no condition of the If before it holds; see If.
func Exec ¶ added in v2.22.0
Exec runs the commands held in attribute attr of the elements sel matches — written with Commands, or any live script (view.Send) — as if their own event fired. A dialog keeps its closing steps once, in data-cancel, and its close button, Esc and backdrop all Exec them.
func FocusFirst ¶ added in v2.22.0
FocusFirst focuses the first focusable element inside the first element sel matches — a dialog's first field: an [autofocus] one when there is, and never one marked data-nx-nofocus (a dialog's close button).
func If ¶ added in v2.24.0
If runs the steps after it only when cond holds, up to an ElseIf or Else; when it fails, the first ElseIf whose cond holds runs its steps, else the steps after Else. cond is about an Element, found as a target is (scoped by Closest, Inner or Within): a read of it — Checked, a non-empty Value, an Attr it has — its match of a CSS selector (Is), or the Element itself, which holds when its selector matches anything:
view.If(view.El("#agree").Checked()).Push(p.Continue)
view.If(view.This().Is(":checked")).Show("#extra").Else().Hide("#extra")
view.If(view.El(".row.selected"), view.Within("table")).Push(p.Bulk).
ElseIf(view.This().Is(".primary")).Push(p.All).
Else().Transition("shake", view.This())
The condition reads the page when the chain gets to it — after a Debounce, once the pause is over — never a reply: Push sends and goes on, so what depends on the server's answer is pushed back by the event (PushJS). An If reaches to the end of the chain, or its ElseIf or Else; an If inside a branch takes the ElseIf and Else after it. Steps that always run go before the If.
func PopFocus ¶ added in v2.22.0
func PopFocus() JSOp
PopFocus focuses the element PushFocus remembered last, and forgets it.
func Push ¶ added in v2.22.0
Push is Send as a command: it calls method — a method value of the live page — on the server with args.
func PushFocus ¶ added in v2.22.0
PushFocus remembers the first element sel matches (view.This(): the button opening a dialog) for PopFocus.
func PushTo ¶ added in v2.22.0
PushTo is SendTo as a command, for a live page whose type is generic.
func Reload ¶ added in v2.25.0
func Reload() JSOp
Reload loads the page again — after SetCookie, so the server renders it with the new cookie.
func RemoveAttr ¶ added in v2.22.0
RemoveAttr removes an attribute from the elements sel matches.
func RemoveClass ¶ added in v2.22.0
RemoveClass removes classes from the elements sel matches.
func SetCookie ¶ added in v2.25.0
SetCookie sets a cookie in the browser — a preference the server reads on the next request, such as a language or a theme: Path=/, SameSite=Lax, Secure on an https page, and for the browser session unless MaxAge says how long. value is sent percent-encoded (encodeURIComponent).
view.SetCookie("lang", "sw", view.MaxAge(365*24*time.Hour)).Reload()
The page's scripts can read a cookie set here, so it never holds a secret: a sign-in or a token is set by the server, HttpOnly.
func SetValue ¶ added in v2.23.0
SetValue sets the value of the fields sel matches as if the user typed it: their input and change events fire, so a live form or view.Change hears it — clearing a search box, a preset.
func Show ¶ added in v2.22.0
Show shows the elements sel matches: it drops their hidden attribute and their display: none.
func Throttle ¶ added in v2.23.0
Throttle runs the steps after it at most once every d: the first event runs them at once and further ones within d are dropped, except that a field's last input or change still runs them when d is up, so the final value is never lost.
<div onscroll={ view.JS(view.Throttle(200*time.Millisecond).Push(p.Seen)) }>
func Toggle ¶ added in v2.22.0
Toggle shows the elements sel matches that are hidden and hides the rest.
func ToggleAttr ¶ added in v2.22.0
ToggleAttr sets an attribute (to value) on the elements sel matches that lack it and removes it from those that have it: ToggleAttr("open", "", "details").
func ToggleClass ¶ added in v2.22.0
ToggleClass adds each of classes the elements sel matches lack and removes those they have.
func Transition ¶ added in v2.22.0
Transition adds classes to the elements sel matches for a while (Time, 200ms when unset) — a shake, a flash.
func (JSOp) FocusFirst ¶ added in v2.23.0
func (JSOp) RemoveAttr ¶ added in v2.23.0
func (JSOp) RemoveClass ¶ added in v2.23.0
func (JSOp) ToggleAttr ¶ added in v2.23.0
func (JSOp) ToggleClass ¶ added in v2.23.0
type JSOption ¶ added in v2.22.0
JSOption narrows where a command applies or how.
func Animate ¶ added in v2.22.0
Animate makes Show, Hide or Toggle a transition: during are the classes the element has while it runs (transition-all duration-200), from and to its first and last state (opacity-0 → opacity-100 to show; the reverse to hide). Time sets how long it runs.
view.Show("#menu", view.Animate("transition duration-200", "opacity-0", "opacity-100"))
func Closest ¶ added in v2.22.0
func Closest() JSOption
Closest makes a command's selector name the nearest ancestor of the element (itself included) that matches it, instead of matches anywhere on the page:
view.AddClass("is-open", ".menu", view.Closest())
func Display ¶ added in v2.22.0
Display is the display Show gives the element ("flex", "grid"…), instead of what its stylesheet says.
func Inner ¶ added in v2.22.0
func Inner() JSOption
Inner makes a command's selector match inside the element only.
func MaxAge ¶ added in v2.25.0
MaxAge is how long a cookie SetCookie sets is kept; zero or less deletes it.
func NoBubble ¶ added in v2.22.0
func NoBubble() JSOption
NoBubble keeps Dispatch's event from bubbling.
func Within ¶ added in v2.22.0
Within makes a command's selector match inside the element's nearest ancestor matching container — a row's own panel, a tab strip's tabs:
view.ToggleClass("show", ".panel", view.Within(".item"))
view.SetAttr("aria-selected", "false", "[role=tab]", view.Within("[role=tablist]"))
With view.This() as the target it is the container itself.
type LiveRouter ¶
LiveRouter is a live view's registration (liveview.go): routed at a path, it is a page; any live view can also be embedded in another's template with view.Component.
var Module = nexus.Module("orders",
nexus.Path("/admin"),
view.Live[*OrderDetail]("/orders/:id", auth.Requires("view_orders")).
Provide(NewOrderDetail),
)
T is a pointer to a struct. A DI instance of it — from Provide, when there is one — is the template each page and each connection copies; without one, T starts from its zero value.
func Live ¶
func Live[T any](prefix string, gates ...nexus.MiddlewareOption) *LiveRouter[T]
Live registers the live view T, routed at prefix and gated by gates — on the page and on its socket — or, with prefix "", only for embedding (view.Component), which a live view that takes dependencies needs. It is a nexus router, so it composes like one: inside nexus.Module it mounts under the module's Path.
func (*LiveRouter[T]) Provide ¶
func (l *LiveRouter[T]) Provide(fns ...any) *LiveRouter[T]
Provide adds constructors — usually T's — under the live page's module.
func (*LiveRouter[T]) URL ¶ added in v2.22.0
func (l *LiveRouter[T]) URL(ctx context.Context, params ...any) string
URL is the live page's URL in the app serving ctx, its path parameters and query filled from params as nexus.Route.Reverse does — a struct of Mount's props works:
var UserPage = view.Live[*UserShow]("/users/:id")
href={ UserPage.URL(ctx, u.ID) }
Its route is named after the page (UserShow → "userShow"), in the namespace of the routers that include it.
type LiveView ¶ added in v2.18.0
type LiveView struct {
// contains filtered or unexported fields
}
LiveView is what a live view embeds, by value: its link to the page it is part of — subscriptions, presence, navigation, flash messages.
type Chat struct {
view.LiveView
Messages view.Stream[Message]
}
func (*LiveView) Connected ¶ added in v2.18.0
Connected reports whether this render is the live connection's (true) or the first, server-rendered page load (false) — skip expensive work, or start subscriptions, only when connected.
func (*LiveView) ID ¶ added in v2.18.0
ID is the view's id where a page embeds it (view.Component), "" for the page itself.
func (*LiveView) PushEvent ¶ added in v2.22.0
PushEvent dispatches a CustomEvent named name on window once the reply is applied, with payload (JSON-encoded) as its detail — for islands and page scripts: window.addEventListener("orders:saved", e => …e.detail…).
func (*LiveView) PushJS ¶ added in v2.22.0
PushJS runs commands in the browser once the reply to the event under way (or to the Info, or the connected Mount) is applied — close a dialog after a save, focus a field, flash a row:
func (p *Orders) Save(ctx context.Context, f OrderForm) error {
…
p.PushJS(view.Hide("#order-dialog"), view.Transition("flash", "#row-"+id))
return nil
}
A selector "" is the page's live root. An event that fails sends none of what it pushed; the first, server-rendered load has no browser to run them in and drops them.
func (*LiveView) PushNavigate ¶ added in v2.18.0
PushNavigate, from an event, opens the page at href — on the connection when it is a live page, else with a page load.
func (*LiveView) PushPatch ¶ added in v2.18.0
PushPatch, from an event, moves the browser to href once the event's reply is sent: on the page's own path (another query), its Update runs with the new props and the page is patched; another live page opens on the connection. The browser's history gets the new URL.
func (*LiveView) PutFlash ¶ added in v2.18.0
PutFlash sets a message of kind ("info", "error", …) for the next render; the page's next event clears it.
func (*LiveView) Subscribe ¶ added in v2.18.0
Subscribe makes the view's Info hear the broadcasts to topics (view.Broadcast) while it is shown. Before the page connects it does nothing.
type MemoryRelay ¶ added in v2.15.0
type MemoryRelay struct {
// contains filtered or unexported fields
}
MemoryRelay is a Relay within one process — for tests, or several apps in one binary.
func NewMemoryRelay ¶ added in v2.15.0
func NewMemoryRelay() *MemoryRelay
type Message ¶
Message is what a live page's Info receives: a topic and the data broadcast to it, as the publisher's Go value.
type Presence ¶ added in v2.17.0
type Presence struct {
Key string
Metas []PresenceMeta
}
Presence is one key on a topic, with a meta per page that tracks it.
type PresenceDiff ¶ added in v2.17.0
PresenceDiff is the Info message a topic's pages get when keys join or leave it: msg.Data.(view.PresenceDiff). A key in Leaves may still be present — only one of its pages left; Presences tells.
type PresenceMeta ¶ added in v2.17.0
type PresenceMeta struct {
// contains filtered or unexported fields
}
PresenceMeta is what a page tracked a key with.
func (PresenceMeta) Decode ¶ added in v2.17.0
func (m PresenceMeta) Decode(v any) error
Decode reads the meta into v.
func (PresenceMeta) MarshalJSON ¶ added in v2.17.0
func (m PresenceMeta) MarshalJSON() ([]byte, error)
MarshalJSON writes the meta as it was tracked.
type Rec ¶ added in v2.12.0
type Rec struct {
// contains filtered or unexported fields
}
Rec is what generated code records a component's render through. Its zero value — a render that isn't a live page's, or one into another buffer — only writes.
func Record ¶ added in v2.12.0
Record returns the recorder of the live render ctx belongs to, when the component writes into its writer. Generated code calls it once per component; it is not for hand-written code.
func (Rec) Close ¶ added in v2.12.0
Close ends the frame Open or Guard started, as a dynamic of the frame around it.
func (Rec) ForStart ¶ added in v2.12.0
ForStart starts a loop; Item starts each of its items; ForEnd ends it.
func (Rec) Guard ¶ added in v2.16.0
Guard starts a spot: a nested frame, as Open does, that a tracked render may skip. The compiler guards a part of a template that reads nothing of the template's own variables — only what it reaches through recv, the component's receiver (nil when it uses none), and ctx. When none of the Assigns it read last time has changed, Guard reports false: the code is not run, and Close keeps what the spot rendered before. label names the spot in its file.
type Relay ¶ added in v2.15.0
type Relay interface {
Publish(ctx context.Context, payload []byte) error
Subscribe(ctx context.Context, deliver func(payload []byte)) error
}
Relay carries broadcasts between the replicas of an app, so view.Broadcast reaches every connected page, not only those on the replica that sent it. It moves opaque payloads: Publish sends one to every replica, its own included; Subscribe delivers each until ctx ends, reconnecting on its own. Redis pub/sub is a natural fit (extension/cache/redis/viewrelay); MemoryRelay is one in a process.
type Signal ¶
type Signal[T any] struct { // contains filtered or unexported fields }
Signal is a piece of browser state, created in a component with State:
{{ count := view.State(ctx, 0) }}
<button onclick={ count.Set(count.Get() + 1) }>+1</button>
<p>Clicked { count.Get() } times</p>
Markup that reads it with Get stays current in the browser. Set is its one action: in an on* attribute it describes what the event does, runs in the browser, and changes nothing on the server. Anything that needs the event goes through Do.
A value that comes back from the browser (a shard re-render) is user input: validate it before acting on it.
func State ¶
State creates a signal owned by the component rendering it:
{{ count := view.State(ctx, 0) }}
Its id comes from the component's place on the page and the order of its State calls, as with React hooks — so call State unconditionally, at the top of the component. In a shard re-render it starts from the browser's current value, which is user input.
func (*Signal[T]) Get ¶
func (s *Signal[T]) Get() T
Get returns the value: on the server, the one the page renders with; in the browser, the current one.
func (*Signal[T]) MarshalJSON ¶
MarshalJSON writes the reference the browser restores as a live signal.
func (*Signal[T]) NexusSchemaAs ¶
NexusSchemaAs types a signal as its value in the client SDK: an island receives the value.
func (*Signal[T]) Set ¶
func (s *Signal[T]) Set(v T) templ.ComponentScript
Set is the action that replaces the value.
func (*Signal[T]) UnmarshalJSON ¶
UnmarshalJSON reads a reference the browser sent back, keeping its id.
type Stream ¶ added in v2.17.0
type Stream[T any] struct { // contains filtered or unexported fields }
Stream is a list a live page shows without keeping it, as LiveView's streams: the page sends what changed — rows inserted, replaced, deleted — and the browser keeps the rest. A chat, a feed or a log of thousands of rows costs the server only the latest change.
type Chat struct {
view.LiveView
Messages view.Stream[Message]
}
func (c *Chat) Mount(ctx context.Context, store *Store) error {
c.Messages.Configure(func(m Message) string { return "msg-" + m.ID })
c.Messages.Limit(-200) // the browser keeps the last 200
c.Messages.Reset(store.Recent(50)...)
c.Subscribe("chat")
return nil
}
func (c *Chat) Info(ctx context.Context, msg view.Message) error {
var m Message
if err := msg.Decode(&m); err != nil {
return err
}
c.Messages.Insert(m)
return nil
}
templ (c *Chat) Render() {
<ul { c.Messages.Attrs()... }>
for _, m := range c.Messages.Items() {
<li id={ c.Messages.ID(m) }>{ m.Text }</li>
}
</ul>
}
Each item renders with the id Configure gives it, as a direct child of the element Attrs is spread on. Items are the items of the latest change only; the browser inserts them (or replaces the element with the same id), deletes what Delete named, and empties the list on Reset.
A Stream is page state like an Assign. Use it in Mount, Params, Info and events — the page's goroutine.
func (*Stream[T]) Attrs ¶ added in v2.17.0
func (s *Stream[T]) Attrs() templ.Attributes
Attrs are the list element's attributes: spread them on it.
func (*Stream[T]) Configure ¶ added in v2.17.0
Configure gives the stream how to identify an item: its element's id.
func (*Stream[T]) Delete ¶ added in v2.17.0
func (s *Stream[T]) Delete(items ...T)
Delete removes items from the list.
func (*Stream[T]) Insert ¶ added in v2.17.0
func (s *Stream[T]) Insert(items ...T)
Insert adds items at the end — or, for an item whose id is shown already, replaces it in place.
func (*Stream[T]) Items ¶ added in v2.17.0
func (s *Stream[T]) Items() []T
Items are the items of the latest change, in order: render each with its ID as a direct child of the element Attrs is spread on.
func (*Stream[T]) Limit ¶ added in v2.17.0
Limit bounds how many items the browser keeps: a positive n keeps the first n, a negative n the last -n, 0 all.
type ThisElement
deprecated
added in
v2.23.0
type ThisValue
deprecated
added in
v2.23.0
type ThisValue = ElementRead
ThisValue is the type This().Value() returned.
Deprecated: use ElementRead.
type Upload ¶ added in v2.16.0
type Upload struct {
// contains filtered or unexported fields
}
Upload is a live page's file input, as LiveView's allow_upload is: files go to the server as they are chosen, with progress the page renders, and an event takes them when the form is submitted.
type Profile struct {
Name view.Assign[string]
Avatar view.Upload
}
func (p *Profile) Mount(ctx context.Context) error {
p.Avatar.Allow(view.UploadConfig{Accept: []string{"image/*"}, MaxSize: 5 << 20})
return nil
}
func (p *Profile) Save(ctx context.Context, disk *Uploads, in ProfileForm) error {
return p.Avatar.Consume(func(e view.UploadEntry, f *os.File) error {
return disk.Put(ctx, "avatars/"+e.Name, f)
})
}
templ (p *Profile) Render() {
<form onsubmit={ view.Submit(p.Save) }>
<input type="file" { p.Avatar.Input()... }/>
for _, e := range p.Avatar.Entries() {
<p>{ e.Name } { strconv.Itoa(e.Progress) }%
if e.Err != "" { <span>{ e.Err }</span> }
<button type="button" onclick={ view.CancelUpload(&p.Avatar, e.Ref) }>×</button></p>
}
<button disabled?={ p.Avatar.Busy() }>Save</button>
</form>
}
Choosing files checks them against the config (Accept, MaxEntries, MaxSize): each becomes an entry, refused ones with Err set. Accepted ones are sent at once, each its own HTTP request to the page's route (its gates apply, and it belongs to the connection that asked), and written to a temporary file; their Progress and Done follow as the bytes arrive, and the page re-renders. Consume hands the finished ones to fn and removes them; anything left is removed when the page ends.
An Upload is page state like an Assign: it doesn't keep a page from tracking its changes, and the parts that render its entries re-render as they change. It works in live components too.
func (*Upload) Allow ¶ added in v2.16.0
func (u *Upload) Allow(cfg UploadConfig)
Allow sets what the upload accepts. Call it in Mount.
func (*Upload) Consume ¶ added in v2.16.0
Consume hands each finished file to fn, open for reading, then removes it — from the entries and from disk. A file fn fails on stays, and its error is returned. Entries still on their way, and refused ones, stay.
func (*Upload) Entries ¶ added in v2.16.0
func (u *Upload) Entries() []UploadEntry
Entries are the files chosen, in order. In Render it notes that this part of the page depends on them.
func (*Upload) Input ¶ added in v2.16.0
func (u *Upload) Input() templ.Attributes
Input is the file input's attributes: spread it on <input type="file">.
type UploadConfig ¶ added in v2.16.0
type UploadConfig struct {
// Accept lists what the input takes: extensions (".png") or MIME types
// ("image/png", "image/*"); empty takes anything. It is also the input's
// accept attribute.
Accept []string
// MaxEntries is how many files it holds at once (default 1).
MaxEntries int
// MaxSize is the largest file in bytes (default 8 MiB).
MaxSize int64
}
UploadConfig is what an Upload accepts.
type UploadEntry ¶ added in v2.16.0
type UploadEntry struct {
Ref string // its identity on the page
Name string // the file's name, as the browser gave it
Type string // its MIME type, as the browser gave it
Size int64
Received int64
Progress int // 0–100
Done bool
Err string // why it was refused or failed
}
UploadEntry is a file chosen for an Upload.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
browser
Package browser runs the view runtime against a small DOM in goja: a page realm with documents, events, form fields, selectors, a virtual clock, fetch and WebSocket, whose network is supplied by the host.
|
Package browser runs the view runtime against a small DOM in goja: a page realm with documents, events, form fields, selectors, a virtual clock, fetch and WebSocket, whose network is supplied by the host. |
|
templ: version: v0.3.1020
|
templ: version: v0.3.1020 |
|
Package rewrite compiles reactive .templ files.
|
Package rewrite compiles reactive .templ files. |
|
cmd/instrument
command
Command instrument records live render trees in templ output that wasn't compiled by nexus (templ generate): it rewrites each *_templ.go under the given directories with viewgen.Instrument, as nexus's view compiler does.
|
Command instrument records live render trees in templ output that wasn't compiled by nexus (templ generate): it rewrites each *_templ.go under the given directories with viewgen.Instrument, as nexus's view compiler does. |
|
jsgen
Package jsgen compiles the Go expressions of a reactive templ attribute to JavaScript.
|
Package jsgen compiles the Go expressions of a reactive templ attribute to JavaScript. |
|
Package viewtest drives view pages end to end in a test, without a browser: the page is fetched over HTTP from the app, the view runtime (/_view/runtime.js and the compiled expressions) runs in goja against a small DOM, a live page connects its WebSocket to the app, and every event, patch and form rule is the real runtime's.
|
Package viewtest drives view pages end to end in a test, without a browser: the page is fetched over HTTP from the app, the view runtime (/_view/runtime.js and the compiled expressions) runs in goja against a small DOM, a live page connects its WebSocket to the app, and every event, patch and form rule is the real runtime's. |