Documentation
¶
Overview ¶
Package ui contains the standard JaWS widgets and template helpers.
Its main building blocks are HTMLInner for dynamic inner HTML; Input, InputText, InputBool, and InputDate for typed controls; Number and Range for numeric controls; Container, Tbody, Select, and MultiSelect for dynamic children; and Template, Handler, and RequestWriter for templates.
Widgets follow github.com/linkdata/jaws.UI's request ownership and equality requirements. Input widgets retain state for one live Element; other widgets document their supported multiplicity on their concrete types.
HTMLInner widgets adapt content with github.com/linkdata/jaws/lib/bind.MakeHTMLGetter. Plain strings are trusted HTML; adapters for string-valued getters escape their text. Existing github.com/linkdata/jaws/lib/bind.HTMLGetter values retain their own rendering behavior. Render-parameter strings are trusted raw attributes.
The widget guide covers templates, inputs, containers, and custom widgets.
Index ¶
- Variables
- func Clickable(innerHTML any, onClick func(elem *jaws.Element, click jaws.Click) (err error)) jaws.ClickHandlerdeprecated
- func Handler(jw *jaws.Jaws, name string, dot any) http.Handler
- type A
- type Button
- type Checkbox
- type Container
- type Date
- type Div
- type HTMLInner
- type Img
- type Input
- type InputBool
- type InputDate
- type InputText
- type JsVarBinding
- type JsVarCheck
- type JsVarPathWriter
- type JsVarStore
- func (store *JsVarStore[T]) Bind() *JsVarBinding[T]
- func (store *JsVarStore[T]) DeletePath(path string) (changed bool, err error)
- func (store *JsVarStore[T]) ReadLocked(fn func(value *T))
- func (store *JsVarStore[T]) SetPath(path string, value any) (changed bool, err error)
- func (store *JsVarStore[T]) WriteLocked(fn func(value *T, writer JsVarPathWriter) error) (err error)
- type Label
- type Li
- type MultiSelect
- type Number
- type Numeric
- type Object
- type ObjectClickedHook
- type ObjectContextMenuHook
- type ObjectInitialHTMLAttrHook
- type Option
- type Password
- type Radio
- type RadioElement
- type Range
- type RequestWriter
- func (rw RequestWriter) A(innerHTML any, params ...any) error
- func (rw RequestWriter) Button(innerHTML any, params ...any) error
- func (rw RequestWriter) Checkbox(value any, params ...any) error
- func (rw RequestWriter) Container(outerHTMLTag string, children jaws.Container, params ...any) error
- func (rw RequestWriter) Date(value any, params ...any) error
- func (rw RequestWriter) Div(innerHTML any, params ...any) error
- func (rw RequestWriter) Get(key string) (value any)
- func (rw RequestWriter) HeadHTML() error
- func (rw RequestWriter) Img(imageSrc any, params ...any) error
- func (rw RequestWriter) Initial() *http.Request
- func (rw RequestWriter) Label(innerHTML any, params ...any) error
- func (rw RequestWriter) Li(innerHTML any, params ...any) error
- func (rw RequestWriter) MultiSelect(handler named.MultiSelectHandler, params ...any) error
- func (rw RequestWriter) NewElement(ui jaws.UI) *jaws.Element
- func (rw RequestWriter) NewUI(ui jaws.UI, params ...any) (err error)
- func (rw RequestWriter) Number(value any, params ...any) error
- func (rw RequestWriter) Password(value any, params ...any) error
- func (rw RequestWriter) Radio(value any, params ...any) error
- func (rw RequestWriter) RadioGroup(nba *named.BoolArray) (rel []RadioElement)
- func (rw RequestWriter) Range(value any, params ...any) error
- func (rw RequestWriter) Register(updater jaws.Updater, params ...any) jid.Jid
- func (rw RequestWriter) Select(handler named.SelectHandler, params ...any) error
- func (rw RequestWriter) Session() *jaws.Session
- func (rw RequestWriter) Set(key string, value any)
- func (rw RequestWriter) Span(innerHTML any, params ...any) error
- func (rw RequestWriter) TailHTML() error
- func (rw RequestWriter) Tbody(children jaws.Container, params ...any) error
- func (rw RequestWriter) Td(innerHTML any, params ...any) error
- func (rw RequestWriter) Template(outerHTMLTag, name string, dot any, params ...any) error
- func (rw RequestWriter) Text(value any, params ...any) error
- func (rw RequestWriter) Textarea(value any, params ...any) error
- func (rw RequestWriter) Tr(innerHTML any, params ...any) error
- func (rw RequestWriter) Write(p []byte) (n int, err error)
- type Select
- type Span
- type Tbody
- type Td
- type Template
- func (tmpl Template) JawsClick(elem *jaws.Element, click jaws.Click) (err error)
- func (tmpl Template) JawsContextMenu(elem *jaws.Element, click jaws.Click) (err error)
- func (tmpl Template) JawsInput(elem *jaws.Element, value string) (err error)
- func (tmpl Template) JawsRender(elem *jaws.Element, w io.Writer, params []any) (err error)
- func (tmpl Template) JawsUpdate(elem *jaws.Element)
- func (tmpl Template) String() string
- type Text
- type Textarea
- type Tr
- type With
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrElementStateUnclaimed errElementStateUnclaimed
ErrElementStateUnclaimed reports an update without rendered widget state.
Template.JawsUpdate, Container.JawsUpdate, and Select.JawsUpdate report this error through jaws.Request.MustLog instead of returning it.
var ErrIllegalJsVarName = errors.New("illegal jsvar name")
ErrIllegalJsVarName reports an invalid or reserved browser name.
var ErrIllegalJsVarPath = errors.New("jsvar: invalid path")
ErrIllegalJsVarPath reports an invalid path or unsupported complex-shape proposal.
var ErrJsVarBindingUsed = errors.New("jsvar: binding already rendered")
ErrJsVarBindingUsed reports a binding rendered more than once.
var ErrJsVarBindingWrongJaws = errors.New("jsvar: binding rendered on a different Jaws instance")
ErrJsVarBindingWrongJaws reports a binding rendered on another jaws.Jaws.
var ErrJsVarNameConflict = errors.New("jsvar: browser name already bound")
ErrJsVarNameConflict reports duplicate or overlapping browser names in a Request.
var ErrJsVarReadOnly = errors.New("jsvar: browser writes denied")
ErrJsVarReadOnly reports a browser proposal to a store without ClientCheck.
var ErrJsVarTooLarge = errors.New("jsvar: JSON size check failed")
ErrJsVarTooLarge reports a failed JSON size check.
A browser proposal rejected with this error cancels its source Request.
var ErrMissingTemplate errMissingTemplate
ErrMissingTemplate is returned when trying to render an undefined template by name.
Functions ¶
func Clickable
deprecated
added in
v0.304.0
func Clickable(innerHTML any, onClick func(elem *jaws.Element, click jaws.Click) (err error)) jaws.ClickHandler
Clickable returns an object implementing bind.HTMLGetter, jaws.ClickHandler and tag.TagGetter.
innerHTML is passed to bind.MakeHTMLGetter, which may or may not provide tags.
Deprecated: use New(innerHTML).Clicked(...) directly.
func Handler ¶
Handler returns an http.Handler that renders the named template.
For each request, Handler looks up name and renders it with With.Dot set to dot. Unless the response already has a Content-Type, Handler sets it to "text/html; charset=utf-8" on the first write. Before rendering, Handler calls jaws.Jaws.NewRequest, which replaces any existing Cache-Control value with "no-store". A render failure before any output uses http.Error's text response.
Handler renders without a generated wrapper and does not use dot as a tag. Dot may be arbitrary template data. When dot implements jaws.ConnectHandler, Handler installs its JawsConnect method on each Request before executing the page template. The page GET does not invoke JawsConnect. Only the top-level dot's method set is considered, including promoted methods. Implementations available only through non-promoted fields or nested Template dots are ignored without a diagnostic.
Handler reuses dot across requests, so dot and its callbacks must support concurrent execution. The bundled client connects after parsing the document.
Example (ConnectHandler) ¶
package main
import (
"html/template"
"log/slog"
"net/http"
"sync"
"github.com/linkdata/jaws"
"github.com/linkdata/jaws/lib/bind"
"github.com/linkdata/jaws/lib/ui"
)
const exampleConnectionsHTML = `<html>
<head>{{$.HeadHTML}}</head>
<body>{{$.Span .Dot.Count}}{{$.TailHTML}}</body>
</html>`
type exampleConnections struct {
mu sync.RWMutex
count int
}
// Count returns the accepted connection count as a direct field binding.
func (state *exampleConnections) Count() bind.Binder[int] {
return bind.New(&state.mu, &state.count)
}
// JawsConnect records an accepted JaWS client connection.
func (state *exampleConnections) JawsConnect(rq *jaws.Request) error {
state.mu.Lock()
state.count++
state.mu.Unlock()
rq.Dirty(&state.count)
return nil
}
func main() {
jw, err := jaws.New()
if err != nil {
panic(err)
}
defer jw.Close()
jw.Logger = slog.Default()
templates := template.Must(template.New("connections").Parse(exampleConnectionsHTML))
if err = jw.AddTemplateLookuper(templates); err != nil {
panic(err)
}
go jw.Serve()
mux := http.NewServeMux()
mux.Handle("GET /jaws/", jw)
mux.Handle("GET /{$}", ui.Handler(jw, "connections", new(exampleConnections)))
_ = mux // serve mux with an HTTP server
}
Output:
Types ¶
type A ¶
type A struct{ HTMLInner }
An A renders an HTML anchor element with dynamic inner HTML.
One A value may back multiple live jaws.Element values. Its HTML getter is shared by those Elements and must be safe for their render, update and event calls.
func NewA ¶
NewA returns an anchor widget whose inner HTML is rendered from innerHTML.
innerHTML is passed to bind.MakeHTMLGetter; plain strings are trusted HTML.
type Button ¶
type Button struct{ HTMLInner }
Button renders an HTML button element with dynamic inner HTML.
One Button value may back multiple live jaws.Element values. Its HTML getter is shared by those Elements and must be safe for their render, update and event calls.
func NewButton ¶
NewButton returns a button widget whose inner HTML is rendered from innerHTML.
innerHTML is passed to bind.MakeHTMLGetter; plain strings are trusted HTML.
type Checkbox ¶
type Checkbox struct{ InputBool }
Checkbox renders an HTML checkbox input bound to a bool setter.
A Checkbox value must back at most one live jaws.Element. Construct distinct Checkbox values over the same setter to render one bound value more than once.
func NewCheckbox ¶
NewCheckbox returns a checkbox input widget bound to g.
For writable use, g must provide the setter-derived dirty target described by Input.
type Container ¶
type Container struct {
// contains filtered or unexported fields
}
Container renders an HTML element around a dynamic child collection.
Its outer tag and child provider define its identity. The provider's dynamic value must be comparable and equal to itself. Rebuilding an equal Container lets a parent retain its live Element. Keep application state containing a slice, map, or function behind a stable pointer and synchronize access to it.
Reconciliation affects direct children only. Reordering retained equal children preserves their Elements and nested subtrees. Nested containers whose children change need their own update. Child Element identity is scoped to its parent; moving a child definition between parents does not preserve its Element. Each child must render one direct DOM node carrying its Element's JaWS ID. Use NewTemplate for Template children so removal and ordering can target a wrapper.
Equal Container values may back multiple live Elements in one jaws.Request when the provider is safe for all calls and each child UI value reused across those Elements supports multiple live Elements. Use Container as a value; taking its address changes identity and is unsupported.
A typed-nil provider is called normally and must tolerate its nil receiver.
Example (RenderScoped) ¶
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/linkdata/jaws"
"github.com/linkdata/jaws/lib/ui"
)
type exampleContainer []string
func (c exampleContainer) JawsContains(elem *jaws.Element) (contents []jaws.UI) {
for _, item := range c {
contents = append(contents, ui.NewSpan(item))
}
return
}
func main() {
firstRows := exampleContainer{"one"}
secondRows := exampleContainer{"two"}
first := ui.NewContainer("div", &firstRows)
second := ui.NewContainer("div", &secondRows)
fmt.Println(first == second)
var b bytes.Buffer
enc := json.NewEncoder(&b)
_ = enc.Encode([]string{"construct containers during render"})
fmt.Print(b.String())
}
Output: false ["construct containers during render"]
func NewContainer ¶
NewContainer returns a Container that renders children inside outerHTMLTag.
An empty outerHTMLTag selects "div".
func (Container) JawsRender ¶
JawsRender renders u as its configured container element.
If elem's widget state is occupied, JawsRender returns jaws.ErrElementStateClaimed without rendering.
func (Container) JawsUpdate ¶
JawsUpdate reconciles u's direct children.
Missing render state reports ErrElementStateUnclaimed. A foreign or in-progress state reports jaws.ErrElementStateClaimed. Errors are logged through jaws.Request.MustLog without calling the provider or queuing work.
type Date ¶
type Date struct{ InputDate }
Date renders an HTML date input bound to a time value setter.
A Date value must back at most one live jaws.Element. Construct distinct Date values over the same setter to render one bound value more than once.
The control is date-only: a browser edit normalizes the bound time.Time to midnight UTC of the picked date, discarding time-of-day and location. See InputDate.JawsInput.
func NewDate ¶
NewDate returns a date input widget bound to g.
For writable use, g must provide the setter-derived dirty target described by Input.
The widget is date-only; see InputDate.JawsInput for how a browser edit normalizes the bound time.Time to midnight UTC and which years round-trip.
type Div ¶
type Div struct{ HTMLInner }
Div renders an HTML div element with dynamic inner HTML.
One Div value may back multiple live jaws.Element values. Its HTML getter is shared by those Elements and must be safe for their render, update and event calls.
func NewDiv ¶
NewDiv returns a div widget whose inner HTML is rendered from innerHTML.
innerHTML is passed to bind.MakeHTMLGetter; plain strings are trusted HTML.
type HTMLInner ¶
type HTMLInner struct {
// HTMLGetter returns the trusted inner HTML to render and update.
HTMLGetter bind.HTMLGetter
}
HTMLInner is a reusable base for widgets that render as `<tag>inner</tag>`.
HTMLInner retains no Element-specific state. A widget embedding it may back multiple live jaws.Element values when its HTMLGetter is also safe for those Elements' render, update and event calls.
func (*HTMLInner) JawsUpdate ¶
JawsUpdate updates the rendered inner HTML.
Unlike the typed input widgets, which dedup against a stored last value, HTMLInner keeps no last-rendered value and re-sends the inner HTML on every update. Dirty its dependency tags only when content or attributes can change.
type Img ¶
Img renders an HTML img element whose src is read from a string getter.
The getter-derived src takes precedence over any src attribute passed as a render param or returned by the getter's jaws.InitialHTMLAttrHandler.
One Img value may back multiple live jaws.Element values. Its getter is shared by those Elements and must be safe for their render, update and event calls.
func (*Img) JawsRender ¶
JawsRender renders ui as an HTML img element.
func (*Img) JawsUpdate ¶
JawsUpdate updates the src attribute.
Like the other display widgets and unlike the typed inputs, Img keeps no last-rendered value and re-sends src on every update; mark the jaws.Element dirty only when src has actually changed.
type Input ¶
type Input struct {
// Last holds widget-specific state used to filter redundant browser updates.
// Widget implementations own this cache; callers must not modify it.
Last atomic.Value
// contains filtered or unexported fields
}
Input stores common state for interactive input widgets.
An Input value provides a widget-owned update cache and dirty target for one live jaws.Element. A widget embedding Input must therefore back at most one live Element. To render the same bound state more than once, construct distinct widgets that share the setter.
For post-set reconciliation, a writable setter must expose at least one stable, usable tag through jaws.Element.ApplyGetter. bind.New exposes its backing value pointer.
After bind.Setter.JawsSet returns a result that does not match jaws.ErrValueUnchanged, Input dirties the setter-derived tag so the server value can reconcile rejected or normalized browser input. Tags supplied as render parameters register the Element but do not replace that dirty target. Without a valid setter-derived target, automatic reconciliation does not occur.
A completed native form reset changes browser state without an input/change event, so it does not update the Go binding. Reset authoritative Go values from a JaWS-handled button with type="button", then dirty their tags.
type InputBool ¶
InputBool is the reusable base for boolean input widgets.
A widget embedding InputBool must back at most one live jaws.Element. Call InputBool.RenderInput from the embedding widget's JawsRender method.
func (*InputBool) JawsUpdate ¶
JawsUpdate updates the input value when the bound bool value changes.
func (*InputBool) RenderInput ¶ added in v0.807.0
func (u *InputBool) RenderInput(elem *jaws.Element, w io.Writer, htmlType string, params ...any) (err error)
RenderInput renders a boolean-backed HTML <input> element.
It registers the setter through jaws.Element.ApplyGetter, applies render parameters and initial setter attributes, and remembers the rendered value for JawsUpdate. With a usable setter tag, JawsInput can reconcile rejected or normalized browser values. Use "checkbox" or "radio" for htmlType so the browser sends the checked-state values JawsInput expects.
type InputDate ¶
InputDate is the reusable base for date input widgets.
A widget embedding InputDate must back at most one live jaws.Element.
The control is date-only. Rendering shows the calendar date in the bound value's own location, but a browser edit normalizes the bound time.Time to midnight UTC of the picked date, and only years 1 through 9999 round-trip; see InputDate.JawsInput.
Call InputDate.RenderInput from an embedding widget's JawsRender method.
func (*InputDate) JawsInput ¶ added in v0.401.0
JawsInput stores a browser-side date input value.
An empty value maps to the zero time.Time, which renders as "0001-01-01". Non-empty values are calendar dates (YYYY-MM-DD). time.Parse resolves them to midnight UTC, so the stored time.Time drops any time-of-day and time.Location the previously bound value carried. In a non-UTC deployment the stored instant therefore shifts by the zone offset, and because time.Time inequality includes the location, re-selecting the same date still reports a change and broadcasts it. Bind a date whose clock and zone are irrelevant, or keep your bound values at midnight UTC to match.
Only years 1 through 9999 round-trip. Those render as four digits, which is what the fixed-width "2006-01-02" layout parses back. A bound year of 10000 or more renders with five or more digits, because time.Time.Format widens the year field, but time.Parse then rejects the extra digit; that edit returns a parse error and leaves the last accepted value in place instead of updating the bound value. Keep bound years within 1..9999.
func (*InputDate) JawsUpdate ¶
JawsUpdate updates the input value when the bound date value changes.
func (*InputDate) RenderInput ¶ added in v0.807.0
func (u *InputDate) RenderInput(elem *jaws.Element, w io.Writer, htmlType string, params ...any) (err error)
RenderInput renders a date-backed HTML <input> element.
It registers the setter through jaws.Element.ApplyGetter, applies render parameters and initial setter attributes, and remembers the rendered value for JawsUpdate. With a usable setter tag, JawsInput can reconcile rejected or normalized browser values. Use "date" for htmlType: InputDate.JawsInput parses non-empty values as YYYY-MM-DD.
type InputText ¶
InputText is the reusable base for string input widgets.
A widget embedding InputText must back at most one live jaws.Element. Call InputText.RenderInput from the embedding widget's JawsRender method.
func (*InputText) JawsUpdate ¶
JawsUpdate updates the input value when the bound string value changes.
func (*InputText) RenderInput ¶ added in v0.807.0
func (u *InputText) RenderInput(elem *jaws.Element, w io.Writer, htmlType string, params ...any) (err error)
RenderInput renders a string-backed HTML <input> element.
It registers the setter through jaws.Element.ApplyGetter, applies render parameters and initial setter attributes, and remembers the rendered value for JawsUpdate. With a usable setter tag, JawsInput can reconcile rejected or normalized browser values. htmlType becomes the escaped type attribute.
type JsVarBinding ¶ added in v0.805.0
type JsVarBinding[T any] struct { // contains filtered or unexported fields }
JsVarBinding renders one browser route to a JsVarStore.
Bindings are one-use and request-scoped.
func (*JsVarBinding[T]) JawsInput ¶ added in v0.805.0
func (binding *JsVarBinding[T]) JawsInput(elem *jaws.Element, input string) (err error)
JawsInput applies a browser proposal allowed by ClientCheck.
A rejected, invalid, or unchanged proposal schedules a canonical correction for its source binding. A changed accepted proposal invalidates every binding. An unchanged proposal to a complex Go shape is rejected. A panicking check rolls back and schedules a root correction before the panic continues. ErrJsVarTooLarge cancels the source Request for reload recovery.
Browser JSON numbers are decoded as float64 and converted by jq to the Go destination before ClientCheck runs. Conversion may lose information: 300 becomes 44 for uint8 and 2.9 becomes 2 for int, on root or nested paths. Other out-of-range float-to-integer results may vary by platform. ClientCheck sees only the converted state. Send exact values as JSON strings to string fields, or use Number for typed numeric input.
func (*JsVarBinding[T]) JawsRender ¶ added in v0.805.0
func (binding *JsVarBinding[T]) JawsRender(elem *jaws.Element, w io.Writer, params []any) (err error)
JawsRender writes the hidden browser route and its initial JSON value.
A Request owned by a different jaws.Jaws returns ErrJsVarBindingWrongJaws without output. Rendering twice returns ErrJsVarBindingUsed; a duplicate or overlapping browser name in the Request returns ErrJsVarNameConflict.
func (*JsVarBinding[T]) JawsUpdate ¶ added in v0.805.0
func (binding *JsVarBinding[T]) JawsUpdate(elem *jaws.Element)
JawsUpdate sends canonical patches for store changes and browser corrections.
A failed encoding cancels the Request.
type JsVarCheck ¶ added in v0.700.0
JsVarCheck validates the complete tentative state of a browser proposal.
A nil check denies browser writes. The check runs under the store's write lock after jq tentatively applies a changed value. It must only inspect next; an error or panic rolls the proposal back. The source can authorize a user or session. Validate the complete value, including changes through parent and root paths. The check sees converted Go values, not raw browser JSON; see JsVarBinding.JawsInput.
func JSONSizeCheck ¶ added in v0.700.0
func JSONSizeCheck[T any](maxBytes int) (check JsVarCheck[T])
JSONSizeCheck limits the encoded size of a tentative JsVar store value.
A non-positive limit returns nil, which denies browser writes if used as the store's sole ClientCheck. The check bounds JSON bytes, not Go heap capacity. An encoding failure returns an error matching ErrJsVarTooLarge.
Example ¶
package main
import (
"sync"
"github.com/linkdata/jaws"
"github.com/linkdata/jaws/lib/ui"
)
func main() {
type clientState struct {
Items []string `json:"items"`
}
jw, err := jaws.New()
if err != nil {
panic(err)
}
defer jw.Close()
var mu sync.Mutex
state := clientState{}
store, err := ui.NewJsVarStore(jw, "client", &mu, &state)
if err != nil {
panic(err)
}
store.ClientCheck = ui.JSONSizeCheck[clientState](1 << 20)
_ = store.Bind() // render one request-scoped binding normally
}
Output:
type JsVarPathWriter ¶ added in v0.805.0
type JsVarPathWriter interface {
// SetPath sets a canonical path in the locked value.
// See [JsVarStore.SetPath] for path and no-op behavior.
SetPath(path string, value any) (changed bool, err error)
// DeletePath removes a string-keyed map entry from the locked value.
// See [JsVarStore.DeletePath] for path and no-op behavior.
DeletePath(path string) (changed bool, err error)
}
JsVarPathWriter applies path edits inside JsVarStore.WriteLocked.
A writer is valid only during the callback. Changed edits are published after the store unlocks, even if the callback returns an error or panics.
type JsVarStore ¶ added in v0.805.0
type JsVarStore[T any] struct { ClientCheck JsVarCheck[T] // nil denies browser proposals ExtraTags []any // dirtied after each changed mutation // contains filtered or unexported fields }
JsVarStore owns one authoritative Go value and its browser name.
Use JsVarStore.Bind once per Request during initial page rendering. ClientCheck and ExtraTags must be configured before first use and remain unchanged while the store is active. Every binding sees the same JSON value; ClientCheck controls writes, not disclosure.
All reads and writes of the bound value must use the supplied locker. Server mutations must use SetPath, DeletePath, or WriteLocked to publish changes. The JSON encoding must have unique object member names. For partial map patches, the bound JSON tree must not share mutable pointers, maps, or slices across different paths. Complex Go types use root patches. Custom JSON methods reached while locked must not re-enter the store or its locker, and must produce the same JSON until the next store change. The last rendered JSON snapshot stays in memory until a newer one replaces it.
A JsVarStore must not be copied after first use.
func NewJsVarStore ¶ added in v0.805.0
func NewJsVarStore[T any](jw *jaws.Jaws, name string, locker sync.Locker, value *T) (store *JsVarStore[T], err error)
NewJsVarStore creates a store for a browser variable.
The name is a dot-separated path from window using JavaScript identifiers with ASCII letters, digits, underscore, or dollar sign. No component may be "__proto__", "constructor", or "prototype"; the limit is 4096 bytes. For dotted names, every parent object must exist on window before jaws.js runs; otherwise the client stops before opening its WebSocket. A top-level name needs no existing property. Initial data and patches assign to that live path, including browser-owned properties and setters.
The value and locker must remain valid for the store's lifetime. An invalid name returns ErrIllegalJsVarName, and a nil value returns github.com/linkdata/jq.ErrInvalidReceiver.
func (*JsVarStore[T]) Bind ¶ added in v0.805.0
func (store *JsVarStore[T]) Bind() *JsVarBinding[T]
Bind creates a one-use browser binding for this store.
Render each binding once during the Request's initial page render, outside regions that may later be replaced or removed. Browser names may neither duplicate nor contain one another within a Request. For dotted names, the parent objects must exist on window before jaws.js runs; otherwise the client stops before opening its WebSocket.
func (*JsVarStore[T]) DeletePath ¶ added in v0.805.0
func (store *JsVarStore[T]) DeletePath(path string) (changed bool, err error)
DeletePath removes a map entry by JSON path.
The parent must be a map with built-in string keys. A missing key in that map returns changed=false; a missing or non-map parent returns github.com/linkdata/jq.ErrPathNotFound. JSON null is a value; deletion is a separate operation. The empty path returns ErrIllegalJsVarPath.
func (*JsVarStore[T]) ReadLocked ¶ added in v0.805.0
func (store *JsVarStore[T]) ReadLocked(fn func(value *T))
ReadLocked inspects the authoritative value while its read lock is held.
The callback must not retain value or a mutable value reachable from it, and must not call a lock-taking store method. The lock is released after a panic.
func (*JsVarStore[T]) SetPath ¶ added in v0.805.0
func (store *JsVarStore[T]) SetPath(path string, value any) (changed bool, err error)
SetPath sets a Go value at a canonical path and publishes a changed result.
Paths are dot-separated JSON names, with no empty or prototype-sensitive component, control byte, DEL, or '='; the maximum is 4096 UTF-8 bytes. The empty path replaces the root. A no-op returns changed=false. Server writes do not invoke ClientCheck. The resulting value must remain JSON encodable.
Example ¶
package main
import (
"fmt"
"sync"
"github.com/linkdata/jaws"
"github.com/linkdata/jaws/lib/ui"
)
func main() {
jw, err := jaws.New()
if err != nil {
panic(err)
}
defer jw.Close()
var mu sync.Mutex
state := struct {
Title string `json:"title"`
}{Title: "old"}
store, err := ui.NewJsVarStore(jw, "client", &mu, &state)
if err != nil {
panic(err)
}
_, err = store.SetPath("title", "new")
fmt.Println(state.Title, err)
}
Output: new <nil>
func (*JsVarStore[T]) WriteLocked ¶ added in v0.805.0
func (store *JsVarStore[T]) WriteLocked(fn func(value *T, writer JsVarPathWriter) error) (err error)
WriteLocked groups server path edits under one application lock.
The value is borrowed for reads and must not be retained or mutated directly. The writer is valid only during fn and must not be retained. The callback must use the writer for edits and must not call lock-taking store methods. Each successful changed edit remains applied and is published after unlocking, even if a later edit fails or fn panics. WriteLocked is a lock scope, not a rollback transaction.
type Label ¶
type Label struct{ HTMLInner }
Label renders an HTML label element with dynamic inner HTML.
One Label value may back multiple live jaws.Element values. Its HTML getter is shared by those Elements and must be safe for their render, update and event calls.
func NewLabel ¶
NewLabel returns a label widget whose inner HTML is rendered from innerHTML.
innerHTML is passed to bind.MakeHTMLGetter; plain strings are trusted HTML.
type Li ¶
type Li struct{ HTMLInner }
Li renders an HTML list item with dynamic inner HTML.
One Li value may back multiple live jaws.Element values. Its HTML getter is shared by those Elements and must be safe for their render, update and event calls.
func NewLi ¶
NewLi returns a list item widget whose inner HTML is rendered from innerHTML.
innerHTML is passed to bind.MakeHTMLGetter; plain strings are trusted HTML.
type MultiSelect ¶ added in v0.807.0
type MultiSelect struct {
// contains filtered or unexported fields
}
MultiSelect renders an HTML select element with multiple selection enabled.
Its handler supplies the options and all selected values. Option values must be non-empty and distinct. The standard handler is named.BoolArray constructed with named.NewBoolArray(true). An empty or nil selection clears every option; values without a matching option select nothing.
Like Select, MultiSelect is an immutable definition used as a value. Its handler must be comparable and equal to itself. Equal definitions may back multiple live Elements when the handler and option widgets support that use. Keep shared application state synchronized behind stable pointers.
Native form reset does not update Go state. Reset the authoritative selection from a JaWS-handled button with type="button", then dirty its tag. The complete browser input message must fit the 32 KiB inbound limit; larger selections close the Request connection.
func NewMultiSelect ¶ added in v0.807.0
func NewMultiSelect(handler named.MultiSelectHandler) MultiSelect
NewMultiSelect returns a MultiSelect backed by handler. Use named.NewBoolArray(true) for a named.BoolArray handler.
func (MultiSelect) JawsInput ¶ added in v0.807.0
func (u MultiSelect) JawsInput(elem *jaws.Element, value string) (err error)
JawsInput replaces the selected values from a browser JSON array of strings. Malformed input is ignored without calling the handler. Every proposal reconciles the originating Element, including rejected or unchanged values. A nil-interface handler is a no-op; a typed-nil handler is called normally.
func (MultiSelect) JawsRender ¶ added in v0.807.0
JawsRender renders the options and queues their complete selected state.
func (MultiSelect) JawsUpdate ¶ added in v0.807.0
func (u MultiSelect) JawsUpdate(elem *jaws.Element)
JawsUpdate reconciles options before queuing their complete selected state. Missing, foreign, or in-progress state suppresses both operations.
type Number ¶
type Number struct {
Input
// contains filtered or unexported fields
}
Number renders an HTML number input.
A Number value must back at most one live jaws.Element. Construct distinct Number values over the same source to render one bound value more than once. Construct a Number with NewNumber; using its zero value as a widget panics.
Editable Numbers send edits on the browser's change event. Pending edits remain browser-local until then and may be replaced by server or ancestor renders.
func NewNumber ¶
NewNumber returns a number input widget bound to source.
Predeclared and named integer and floating-point types are parsed and formatted at their own width. Integer sources use base-10 integer syntax. If source's dynamic type also implements bind.Setter, the input is editable; rendering fails unless source exposes the stable, usable tag described by Input. A getter-only source renders read-only.
A non-finite bound floating-point value cancels the jaws.Request with a cause matching jaws.ErrValueNotFinite.
func (*Number) JawsInput ¶ added in v0.700.0
JawsInput settles a browser-side number edit.
Empty, malformed, non-finite, and unrepresentable browser values are rejected without calling the setter or returning an error. The canonical value is restored by updating only the originating Element. Accepted text is reconciled through the binding's formatter, including when the setter returns jaws.ErrValueUnchanged. Getter-only Numbers ignore browser input.
func (*Number) JawsRender ¶
JawsRender renders the Number as an HTML number input.
func (*Number) JawsUpdate ¶ added in v0.700.0
JawsUpdate reconciles the input with its canonical source value.
type Numeric ¶ added in v0.700.0
type Numeric interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
~float32 | ~float64
}
Numeric is an integer or floating-point type supported by Number and Range.
Named types with one of these underlying types are included.
type Object ¶ added in v0.400.0
type Object interface {
bind.HTMLGetter
tag.TagGetter
jaws.ClickHandler
jaws.ContextMenuHandler
jaws.InitialHTMLAttrHandler
// Clicked adds fn as the newest click hook and returns the resulting [Object].
Clicked(fn ObjectClickedHook) (newobj Object)
// ContextMenu adds fn as the newest context-menu hook and returns the
// resulting [Object].
ContextMenu(fn ObjectContextMenuHook) (newobj Object)
// InitialHTMLAttr adds fn as the newest initial-attribute hook and returns the
// resulting [Object].
InitialHTMLAttr(fn ObjectInitialHTMLAttrHook) (newobj Object)
}
Object is a chainable UI object.
Each call to Object.Clicked, Object.ContextMenu, or Object.InitialHTMLAttr returns a new chain node wrapping its receiver. Calls to jaws.ClickHandler.JawsClick and jaws.ContextMenuHandler.JawsContextMenu run the corresponding hooks from newest to oldest. Dispatch continues while the result matches jaws.ErrEventUnhandled according to errors.Is, including when wrapped, and stops at the first other result. If no hook handles the event, the invoked method returns an error matching jaws.ErrEventUnhandled.
jaws.InitialHTMLAttrHandler.JawsInitialHTMLAttr runs all initial-attribute hooks from newest to oldest. Their non-empty results are joined in that order with one space inserted between results.
Every event and initial-attribute hook receives the Object on which dispatch was invoked. That Object may include links added after the hook.
The adapted innerHTML supplies the Object's tag. Adding hooks preserves it. The tag remains subject to tag.TagGetter's initialization, stability, and concurrency requirements. Use tag.TagExpand to obtain flattened, validated tags.
func New ¶ added in v0.400.0
New returns a new Object that renders innerHTML.
innerHTML is passed to bind.MakeHTMLGetter. Its HTML and any tags exposed by the adapted value's tag.TagGetter are used. An existing bind.HTMLGetter without JawsGetTag contributes no tag. innerHTML's event and initial-attribute methods are not inherited; add those behaviors with Object.Clicked, Object.ContextMenu, and Object.InitialHTMLAttr. Plain strings are trusted HTML.
type ObjectClickedHook ¶ added in v0.500.0
ObjectClickedHook handles a click event for an Object.
obj is the Object on which JawsClick was invoked.
Unlike bind.ClickedHook, ObjectClickedHook receives an Object rather than a bind.Binder.
type ObjectContextMenuHook ¶ added in v0.500.0
ObjectContextMenuHook handles a context menu event for an Object.
obj is the Object on which JawsContextMenu was invoked.
type ObjectInitialHTMLAttrHook ¶ added in v0.500.0
ObjectInitialHTMLAttrHook provides attributes when an Object is initially rendered.
obj is the Object on which JawsInitialHTMLAttr was invoked.
ObjectInitialHTMLAttrHook is a type alias so a value of a defined function type with this signature can be passed to Object.InitialHTMLAttr without explicit conversion.
type Option ¶
Option renders an HTML option element backed by a named.Bool.
The value attribute is always named.Bool.Name and takes precedence over a value attribute passed as a render param.
One Option value may back multiple live jaws.Element values. All of those Elements reflect the shared Bool.
func (Option) JawsRender ¶
JawsRender renders ui as an HTML option element.
func (Option) JawsUpdate ¶
JawsUpdate updates the selected attribute.
type Password ¶
type Password struct{ InputText }
Password renders an HTML password input bound to a string setter.
A Password value must back at most one live jaws.Element. Construct distinct Password values over the same setter to render one bound value more than once.
func NewPassword ¶
NewPassword returns a password input widget bound to g.
For writable use, g must provide the setter-derived dirty target described by Input.
type Radio ¶
type Radio struct{ InputBool }
Radio renders an HTML radio input bound to a bool setter.
A Radio value must back at most one live jaws.Element. Construct distinct Radio values over the same setter to render one bound value more than once.
Each Radio binds an independent boolean. An HTML radio group does not group its Go bindings: the browser reports the newly checked radio, not peers it unchecks. Use RequestWriter.RadioGroup with a single-select named.BoolArray and distinct named.Bool.Name values, or coordinated setters that clear peers together and dirty every changed binding.
type RadioElement ¶
type RadioElement struct {
// contains filtered or unexported fields
}
RadioElement renders the input and label elements for one radio option.
The underlying jaws.Element values are created lazily on the first call to RadioElement.Radio or RadioElement.Label, so options that a template never renders register no elements on the jaws.Request. Call each of Radio and Label at most once. Render Label only when Radio is also rendered: Label emits a for="..." referencing the radio's id, so a Label without its Radio points at an input that is absent from the document. The radio Element it created is still unregistered by the Template that owns it (see RequestWriter.RadioGroup) when that template next replaces its content. With no template owner it has no DOM node for a removal to report either, so it stays registered until the jaws.Request ends.
func (RadioElement) Label ¶
func (re RadioElement) Label(params ...any) template.HTML
Label renders an HTML label element.
The generated for= attribute referencing the radio's id takes precedence over any for= passed in params: it is emitted first and the HTML parser keeps the first of duplicate attributes, so the label always targets its own radio.
Render errors are reported through jaws.Jaws.MustLog, which panics when no jaws.Jaws.Logger is configured.
func (RadioElement) Radio ¶
func (re RadioElement) Radio(params ...any) template.HTML
Radio renders an HTML input element of type radio.
The group's generated name= attribute takes precedence over any name= passed in params: it is emitted first and the HTML parser keeps the first of duplicate attributes, preserving the invariant that every radio in the group shares the same request-scoped name.
Render errors are reported through jaws.Jaws.MustLog, which panics when no jaws.Jaws.Logger is configured.
type Range ¶
type Range struct {
Input
// contains filtered or unexported fields
}
Range renders an HTML range input.
A Range value must back at most one live jaws.Element. Construct distinct Range values over the same source to render one bound value more than once. Construct a Range with NewRange; using its zero value as a widget panics. Editable Ranges send live browser input while their thumb moves.
func NewRange ¶
NewRange returns a range input widget bound to source.
Predeclared and named integer and floating-point types are parsed and formatted at their own width. Integer sources use base-10 integer syntax. If source's dynamic type also implements bind.Setter, the input is editable; rendering fails unless source exposes the stable, usable tag described by Input. A getter-only source renders disabled; when tagged, it continues to receive dirty-driven server updates.
A non-finite bound floating-point value cancels the jaws.Request with a cause matching jaws.ErrValueNotFinite.
Range emits no min, max, or step attributes, so the browser defaults apply. Supply them as render parameters when those defaults do not fit the source domain. The browser may clamp or round the displayed value; a browser-adjusted value reaches the setter only on a later input event and only when representable by T.
func (*Range) JawsInput ¶ added in v0.700.0
JawsInput accepts or rejects a browser-side range value.
Text that is malformed or cannot be represented by the source type is rejected without calling the setter or returning an error. Accepted and rejected text is reconciled with the binding's formatter. Rejection and jaws.ErrValueUnchanged update only the originating Element. Getter-only Ranges ignore browser input.
func (*Range) JawsRender ¶
JawsRender renders the Range as an HTML range input.
func (*Range) JawsUpdate ¶ added in v0.700.0
JawsUpdate reconciles the range with its canonical source value.
type RequestWriter ¶
RequestWriter combines a jaws.Request with an io.Writer while rendering.
func (RequestWriter) A ¶
func (rw RequestWriter) A(innerHTML any, params ...any) error
A renders an HTML anchor element. A plain string innerHTML is trusted HTML; see NewA and bind.MakeHTMLGetter to pass untrusted input safely.
func (RequestWriter) Button ¶
func (rw RequestWriter) Button(innerHTML any, params ...any) error
Button renders an HTML button element. A plain string innerHTML is trusted HTML; see NewButton and bind.MakeHTMLGetter to pass untrusted input safely.
func (RequestWriter) Checkbox ¶
func (rw RequestWriter) Checkbox(value any, params ...any) error
Checkbox renders an HTML checkbox input.
func (RequestWriter) Container ¶
func (rw RequestWriter) Container(outerHTMLTag string, children jaws.Container, params ...any) error
Container renders children inside outerHTMLTag.
func (RequestWriter) Date ¶
func (rw RequestWriter) Date(value any, params ...any) error
Date renders an HTML date input.
The control is date-only: a browser edit normalizes the bound time.Time to midnight UTC of the picked date, discarding time-of-day and location. See InputDate.JawsInput.
func (RequestWriter) Div ¶
func (rw RequestWriter) Div(innerHTML any, params ...any) error
Div renders an HTML div element. A plain string innerHTML is trusted HTML; see NewDiv and bind.MakeHTMLGetter to pass untrusted input safely.
func (RequestWriter) Get ¶
func (rw RequestWriter) Get(key string) (value any)
Get calls jaws.Request.Get.
func (RequestWriter) HeadHTML ¶
func (rw RequestWriter) HeadHTML() error
HeadHTML calls jaws.Request.HeadHTML.
func (RequestWriter) Img ¶
func (rw RequestWriter) Img(imageSrc any, params ...any) error
Img renders an HTML img element.
func (RequestWriter) Initial ¶
func (rw RequestWriter) Initial() *http.Request
Initial returns the initial http.Request.
func (RequestWriter) Label ¶
func (rw RequestWriter) Label(innerHTML any, params ...any) error
Label renders an HTML label element. A plain string innerHTML is trusted HTML; see NewLabel and bind.MakeHTMLGetter to pass untrusted input safely.
func (RequestWriter) Li ¶
func (rw RequestWriter) Li(innerHTML any, params ...any) error
Li renders an HTML list item. A plain string innerHTML is trusted HTML; see NewLi and bind.MakeHTMLGetter to pass untrusted input safely.
func (RequestWriter) MultiSelect ¶ added in v0.807.0
func (rw RequestWriter) MultiSelect(handler named.MultiSelectHandler, params ...any) error
MultiSelect renders an HTML select element with multiple selection enabled. See MultiSelect for handler requirements and native reset semantics.
func (RequestWriter) NewElement ¶ added in v0.700.0
func (rw RequestWriter) NewElement(ui jaws.UI) *jaws.Element
NewElement creates a new jaws.Element for ui.
It has the same ownership and multiplicity requirements as jaws.Request.NewElement. An Element created through the RequestWriter passed to a Template execution belongs to that Template.
func (RequestWriter) NewUI ¶ added in v0.500.0
func (rw RequestWriter) NewUI(ui jaws.UI, params ...any) (err error)
NewUI creates an element for ui and renders it to the underlying writer.
The ui value must satisfy the ownership and live-Element multiplicity requirements documented by jaws.UI.
func (RequestWriter) Number ¶
func (rw RequestWriter) Number(value any, params ...any) error
Number renders an HTML number input for value.
Numeric values and getter-only bind.Getter sources render read-only; bind.Setter sources render editable. It panics for any other value.
func (RequestWriter) Password ¶
func (rw RequestWriter) Password(value any, params ...any) error
Password renders an HTML password input.
func (RequestWriter) Radio ¶
func (rw RequestWriter) Radio(value any, params ...any) error
Radio renders an HTML radio input.
See Radio for grouping semantics.
func (RequestWriter) RadioGroup ¶
func (rw RequestWriter) RadioGroup(nba *named.BoolArray) (rel []RadioElement)
RadioGroup returns a RadioElement for each value in nba.
Elements are created lazily as they are rendered; see RadioElement. Every rendered radio in the group shares a name derived from the first created radio Element's request-scoped jaws.Jid.
Use a single-select named.BoolArray with distinct named.Bool.Name values. Multi-select arrays and duplicate names are incompatible with native radio semantics. Separately bound Radio widgets are not grouped server-side by their HTML name.
Call RadioGroup from the Template that renders the returned RadioElement values; do not pass them into a nested wrapped Template for rendering.
func (RequestWriter) Range ¶
func (rw RequestWriter) Range(value any, params ...any) error
Range renders an HTML range input for value.
Numeric values and getter-only bind.Getter sources render disabled; bind.Setter sources render editable. It panics for any other value. Supply min, max, and step attributes in params when the browser defaults do not cover the source's domain. For example:
rw.Range(floatBinder, `min="0"`, `max="200"`, `step="0.5"`)
func (RequestWriter) Register ¶
Register binds an updater to otherwise static template-authored HTML.
Register is an advanced escape hatch primarily for updating HTML whose markup is written by the surrounding template. The registered HTML is intended to contain no JaWS widgets. Render widgets through RequestWriter.NewUI or their corresponding RequestWriter helpers instead.
Register makes no compatibility guarantees for passing a standard widget as updater or placing JaWS widgets inside the registered HTML. Their behavior in either position is unspecified.
The returned jid.Jid must be the element's id. Register never calls jaws.Renderer.JawsRender, so updater must work without render-time initialization.
Register tags the Element with updater, applies tag and event-handler params, attaches event-handler methods implemented by updater, and invokes jaws.Updater.JawsUpdate once for the initial browser state. Updater handlers are tried only after applicable param handlers return jaws.ErrEventUnhandled. HTML attribute params have no effect; write attributes in the template.
The updater must be comparable at runtime, equal to itself, and usable as a tag. A typed nil is invoked normally and must tolerate its nil receiver. The same updater may back multiple live Elements only when it supports that use without retaining Element-specific state on the shared value. If shared across requests, it must be safe for concurrent use.
A surrounding Template owns and cleans up the registered Element. Outside a Template, it remains registered until explicitly deleted, DOM removal is reported, or its jaws.Request ends; always emit the returned Jid.
The returned Jid is suitable for including as an HTML id attribute:
<div id="{{$.Register .MyUpdater}}">...</div>
func (RequestWriter) Select ¶
func (rw RequestWriter) Select(handler named.SelectHandler, params ...any) error
Select renders a single-selection HTML select element.
HTML attribute params are applied to the select element, but the multiple attribute is unsupported. A named.BoolArray handler must be single-select: use named.NewBoolArray(false) or its zero value. Use RequestWriter.MultiSelect for multiple selected options.
See Select for handler requirements and native reset semantics.
func (RequestWriter) Session ¶
func (rw RequestWriter) Session() *jaws.Session
Session returns the request's jaws.Session, or nil.
func (RequestWriter) Set ¶
func (rw RequestWriter) Set(key string, value any)
Set calls jaws.Request.Set.
func (RequestWriter) Span ¶
func (rw RequestWriter) Span(innerHTML any, params ...any) error
Span renders an HTML span element. A plain string innerHTML is trusted HTML; see NewSpan and bind.MakeHTMLGetter to pass untrusted input safely.
func (RequestWriter) TailHTML ¶
func (rw RequestWriter) TailHTML() error
TailHTML writes optional HTML code at the end of the page's BODY section that can apply queued attribute and class updates before the WebSocket connects.
func (RequestWriter) Tbody ¶
func (rw RequestWriter) Tbody(children jaws.Container, params ...any) error
Tbody renders children in an HTML tbody element.
func (RequestWriter) Td ¶
func (rw RequestWriter) Td(innerHTML any, params ...any) error
Td renders an HTML table cell. A plain string innerHTML is trusted HTML; see NewTd and bind.MakeHTMLGetter to pass untrusted input safely.
func (RequestWriter) Template ¶
func (rw RequestWriter) Template(outerHTMLTag, name string, dot any, params ...any) error
Template renders the named partial template with dot exposed as With.Dot.
The generated outerHTMLTag wrapper owns the JaWS ID, HTML attributes in params, and attributes returned by dot when it implements jaws.InitialHTMLAttrHandler. Attributes in params take precedence when dot returns an attribute with the same name. An empty outerHTMLTag defaults to "div". See NewTemplate.
func (RequestWriter) Text ¶
func (rw RequestWriter) Text(value any, params ...any) error
Text renders an HTML text input.
func (RequestWriter) Textarea ¶
func (rw RequestWriter) Textarea(value any, params ...any) error
Textarea renders an HTML textarea.
See Textarea for the browser-to-server message-size limit.
func (RequestWriter) Tr ¶
func (rw RequestWriter) Tr(innerHTML any, params ...any) error
Tr renders an HTML table row. A plain string innerHTML is trusted HTML; see NewTr and bind.MakeHTMLGetter to pass untrusted input safely.
func (RequestWriter) Write ¶
func (rw RequestWriter) Write(p []byte) (n int, err error)
Write marks render activity through jaws.Request.MarkWritten before writing p to the underlying writer.
type Select ¶
type Select struct {
// contains filtered or unexported fields
}
Select renders a single-selection HTML select element.
Its handler supplies the options and represents the selection as a string. Option values must be non-empty and distinct. A string that matches no option value represents no selection. The standard handler is named.BoolArray constructed with named.NewBoolArray(false) or its zero value.
The handler's dynamic value defines Select's identity and must be comparable and equal to itself. Rebuilding with an equal handler lets a parent retain its live Element. Keep application state containing a slice, map, or function behind a stable pointer and synchronize access to it.
Equal Select values may back multiple live jaws.Element values in one jaws.Request when the handler is safe for all calls and each option UI value reused across those Elements supports multiple live Elements. Use Select as a value; taking its address changes identity and is unsupported.
A typed-nil handler is called normally and must tolerate its nil receiver.
Select supports one selected option. The HTML multiple attribute and multi-select BoolArray values are unsupported. Use MultiSelect for multiple selected options.
A completed native form reset changes browser state without an input/change event, so it does not update the Go binding. Reset the authoritative selection from a JaWS-handled button with type="button", then dirty its tag.
func NewSelect ¶
func NewSelect(handler named.SelectHandler) Select
NewSelect returns a single-selection Select backed by handler.
A named.BoolArray handler must be single-select: use named.NewBoolArray(false) or its zero value.
See Select for handler requirements and native reset semantics.
func (Select) JawsInput ¶ added in v0.401.0
JawsInput stores one browser-side selected option value.
A nil-interface handler is a no-op; a typed-nil handler is called normally. If no render-derived dirty tag is available, Select performs no additional dirtying after calling the handler.
func (Select) JawsRender ¶
JawsRender renders u as an HTML select element.
On success, it queues the selected value after the options.
func (Select) JawsUpdate ¶
JawsUpdate reconciles child options and queues the selected value.
Missing, foreign, or in-progress state suppresses both operations.
type Span ¶
type Span struct{ HTMLInner }
Span renders an HTML span element with dynamic inner HTML.
One Span value may back multiple live jaws.Element values. Its HTML getter is shared by those Elements and must be safe for their render, update and event calls.
func NewSpan ¶
NewSpan returns a span widget whose inner HTML is rendered from innerHTML.
innerHTML is passed to bind.MakeHTMLGetter; plain strings are trusted HTML.
type Tbody ¶
type Tbody struct {
Container
}
Tbody renders an HTML tbody containing dynamic child rows.
NewTbody configures its embedded Container for tbody. Replacing that Container is unsupported. Tbody otherwise follows Container's identity, reconciliation, multiplicity, and typed-nil-provider behavior. Treat it as immutable after use and use it as a value; taking its address changes identity and is unsupported.
type Td ¶
type Td struct{ HTMLInner }
Td renders an HTML table cell with dynamic inner HTML.
One Td value may back multiple live jaws.Element values. Its HTML getter is shared by those Elements and must be safe for their render, update and event calls.
func NewTd ¶
NewTd returns a table cell widget whose inner HTML is rendered from innerHTML.
innerHTML is passed to bind.MakeHTMLGetter; plain strings are trusted HTML.
type Template ¶
type Template struct {
OuterHTMLTag string // Wrapper element; empty renders unwrapped and disables JawsUpdate.
Name string // Template name to be looked up using Jaws.LookupTemplate.
Dot any // Template data, tag source, event delegate, and initial-attribute source.
// contains filtered or unexported fields
}
Template renders a named Go html/template partial through JaWS.
Use Templates as values; NewTemplate is the usual constructor for wrapped Templates. A Template may back multiple live jaws.Element values in one jaws.Request; its Dot and callbacks must support all of their render, update, and event calls. Taking a Template's address is unsupported because it changes container reuse from value identity to pointer identity.
Dot may be a nil interface. Otherwise the Template must be comparable at runtime and equal to itself, and Dot must be usable as a tag under tag.TagExpand.
If Dot implements jaws.InitialHTMLAttrHandler, its callback supplies wrapper attributes separately for each wrapped Element's initial render. An unwrapped Template has no attribute target and does not invoke the callback. The callback is not invoked during Template.JawsUpdate.
OuterHTMLTag names the wrapper that receives the JaWS ID. Wrapper attribute precedence is render parameters, NewTemplate attributes, then Dot attributes. An empty field renders without a wrapper, making Template.JawsUpdate a no-op. NewTemplate defaults an empty wrapper argument to "div". The named template must be a partial; use Handler for a complete document.
A Template owns the Elements created through its RequestWriter. A successful update unregisters Elements from the previous execution. Elements created by a failed execution are also unregistered.
Replacing wrapper contents reports all managed descendants being removed in one WebSocket message, subject to jaws.Request.ServeHTTP's 32 KiB inbound limit. Split large trees into independently updated nested wrappers.
Execution is not transactional. An error may leave partial output, queued messages, or application side effects in place.
Example (FailureBehavior) ¶
package main
import (
"bytes"
"fmt"
"html/template"
"net/http/httptest"
"strings"
"github.com/linkdata/jaws"
"github.com/linkdata/jaws/lib/tag"
"github.com/linkdata/jaws/lib/ui"
)
func main() {
tmpl := template.Must(template.New("partial").Parse(`before {{.Dot}} {{call .Missing}} after`))
jw, err := jaws.New()
if err != nil {
panic(err)
}
defer jw.Close()
if err = jw.AddTemplateLookuper(tmpl); err != nil {
panic(err)
}
rq := jw.NewRequest(httptest.NewRecorder(), nil)
elem := rq.NewElement(ui.NewTemplate("div", "partial", tag.Tag("dot")))
var out bytes.Buffer
err = elem.JawsRender(&out, nil)
fmt.Println(strings.Contains(out.String(), `id="Jid.1"`))
fmt.Println(strings.Contains(out.String(), "before dot"))
fmt.Println(err != nil)
}
Output: true true true
func NewTemplate ¶
NewTemplate returns a Template for rendering the named partial template with dot exposed as With.Dot.
outerHTMLTag names the generated wrapper element that owns the JaWS ID and initial HTML attributes. If outerHTMLTag is empty, "div" is used. Choose a tag suitable for the DOM context. For an unwrapped fragment, use html/template's native {{template "name" pipeline}} action. The name is resolved at render and update time.
dot may be a nil interface. Otherwise it must make the returned Template comparable and equal to itself, and it must be usable as a tag under tag.TagExpand. Use the returned Template as a value; taking its address is unsupported. If dot implements jaws.InitialHTMLAttrHandler, its callback supplies attributes separately for each generated wrapper's initial render.
attrs contains trusted raw HTML attributes for the generated wrapper. Values are joined with a single space, and the result participates in Template equality. Constructor attributes are applied only during initial rendering and persist unchanged across Template.JawsUpdate. Attribute precedence is render parameters, attrs, then attributes returned by dot.
Example (DefaultWrapper) ¶
package main
import (
"fmt"
"github.com/linkdata/jaws/lib/tag"
"github.com/linkdata/jaws/lib/ui"
)
func main() {
tmpl := ui.NewTemplate("", "partial", tag.Tag("dot"))
fmt.Println(tmpl.OuterHTMLTag)
}
Output: div
func (Template) JawsClick ¶ added in v0.401.0
JawsClick delegates click events to t.Dot when it implements jaws.ClickHandler.
func (Template) JawsContextMenu ¶ added in v0.401.0
JawsContextMenu delegates context-menu events to t.Dot when it implements jaws.ContextMenuHandler.
func (Template) JawsInput ¶ added in v0.401.0
JawsInput delegates input events to t.Dot when it implements jaws.InputHandler.
func (Template) JawsRender ¶
JawsRender renders t through the request's configured template lookupers.
If elem's widget state is occupied, JawsRender returns jaws.ErrElementStateClaimed without output. Other errors may leave partial output or side effects as described on Template.
func (Template) JawsUpdate ¶
JawsUpdate re-renders the Template into its wrapper.
An empty OuterHTMLTag has no DOM target, so the update is a no-op. Otherwise elem must have been rendered by an equal Template value; using an unequal value is unsupported. After a successful lookup, missing Template state reports ErrElementStateUnclaimed.
On success, JawsUpdate replaces the wrapper content and unregisters Elements from the previous execution. On execution failure, it keeps the previous DOM and Elements and unregisters Elements created by the failed attempt.
Lookup, state, and execution errors are reported through jaws.Request.MustLog, which may panic when no jaws.Jaws.Logger is configured.
type Text ¶
type Text struct{ InputText }
Text renders an HTML text input bound to a string setter.
A Text value must back at most one live jaws.Element. Construct distinct Text values over the same setter to render one bound value more than once.
type Textarea ¶
type Textarea struct{ InputText }
Textarea renders an HTML textarea bound to a string setter.
A Textarea value must back at most one live jaws.Element. Construct distinct Textarea values over the same setter to render one bound value more than once.
While the WebSocket is open, each input event sends the complete value in one message. The value plus protocol and JSON overhead must fit the 32 KiB inbound limit documented by jaws.Request.ServeHTTP. Use a conservative maxlength or a separate upload endpoint for potentially large text.
func NewTextarea ¶
NewTextarea returns a textarea widget bound to g.
For writable use, g must provide the setter-derived dirty target described by Input. See Textarea for the browser-to-server message-size limit.
type Tr ¶
type Tr struct{ HTMLInner }
Tr renders an HTML table row with dynamic inner HTML.
One Tr value may back multiple live jaws.Element values. Its HTML getter is shared by those Elements and must be safe for their render, update and event calls.
func NewTr ¶
NewTr returns a table row widget whose inner HTML is rendered from innerHTML.
innerHTML is passed to bind.MakeHTMLGetter; plain strings are trusted HTML.
type With ¶
type With struct {
*jaws.Element // the Element being rendered using a template
RequestWriter // the RequestWriter for nested UI helpers
Dot any // user data parameter
// Auth is the authentication information from [jaws.Jaws.MakeAuth]. When
// MakeAuth is nil it is a [jaws.DefaultAuth], whose IsAdmin returns true for
// everyone — gating UI on {{if .Auth.IsAdmin}} is only safe once MakeAuth is
// set. See [jaws.DefaultAuth] for the fail-open caveat.
Auth jaws.Auth
}
With is passed as the data parameter when using RequestWriter.Template, populated with all required members set.
Source Files
¶
- a.go
- button.go
- checkbox.go
- clickable.go
- common.go
- container.go
- containerstate.go
- date.go
- div.go
- doc.go
- errelementstateunclaimed.go
- errjsvar.go
- errmissingtemplate.go
- handler.go
- html_widgets.go
- img.go
- input_widgets.go
- jsvar.go
- label.go
- li.go
- multiselect.go
- number.go
- numeric.go
- numeric_source.go
- object.go
- option.go
- owned.go
- password.go
- radio.go
- radiogroup.go
- range.go
- register.go
- requestwriter.go
- select.go
- span.go
- tbody.go
- td.go
- template.go
- text.go
- textarea.go
- tr.go
- with.go