Documentation
¶
Overview ¶
Package oneui is the component runtime: it mounts components, tracks their state, routes events, runs timers and writes every mutation to a document as a stream of change sets (recursiveai.org/go/oneui/changeset).
The first minutes ¶
A component is a Go struct, an HTML template and optional scoped CSS:
// counter.go
//go:generate go run recursiveai.org/go/oneui/cmd/oneui generate
type Counter struct {
oneui.Base
Count int `oneui:"state"`
}
func (c *Counter) Increment() { c.SetCount(c.Count + 1) }
<!-- Counter.html -->
<button on:click="Increment">Clicked {Count} times</button>
Run go generate. The tool checks every name in the template against the struct (an unknown field is a build-time error with a file:line:col position) and writes Counter_oneui.go: the setters (SetCount) and the code that creates the nodes once and rewrites only the nodes bound to state that changed. The struct tags are `oneui:"state"` (a field the template reads and the setters keep current), `oneui:"param"` or `oneui:"param,required"` (state a parent sets); an untagged field is a read-only member.
To test it, mount it in the reference document with package oneuitest. To run it in a browser, use package browser.
Two layers ¶
The low level is Context: allocate nodes, record changes, batch and commit them, add listeners, schedule timers, ask layout questions. It needs no templates; hand-written components and tools use it directly.
The happy path is a component: a struct that embeds Base and implements Component. Generated Build creates the nodes once, state setters call Base.Invalidate with the state's bit, and Update rewrites only the nodes bound to the state that changed. Nothing is diffed and nothing is reflected.
What generated code calls ¶
Generated files call the runtime support in package rt, which is outside this module's compatibility promise (see its documentation); the calls into this package are the ones marked "For generated code" in their comments, in the order generated code uses them:
- A component embeds Base and implements Component.Build and Component.Update. State lives in plain fields behind generated setters; a setter that changes the value calls Base.Invalidate(bit), with bit < 64 numbering the component's state.
- Build(parent, before) creates elements with Context.CreateElement (or CreateElementNS inside <svg>), sets static attributes, adds listeners with Context.AddListener, builds child nodes and components (Base.Mount), inserts the finished subtree into parent before the sibling before (Append places it last) and calls Base.Adopt for each top-level node it inserted, so unmounting removes them.
- Update(dirty) runs when state bits are set: for each bit it writes the nodes that read that state with SetText, SetAttribute, SetClass, SetStyle and SetProperty, and reconciles each-blocks with Rows.
- Element references are ElementRef fields bound with ElementRef.Bind.
- Lifecycle: optional Mounter and Disposer methods.
- Timers: Base.SetTimeout and Base.SetInterval; they stop when the component is unmounted.
Errors ¶
Errors are values. Everything that goes wrong at the wrong time wraps ErrInvalidOperation; test with errors.Is. A problem with no caller to return to (a sink refusing a set, an event for a node with no listener) goes to the WithErrorHandler function and is remembered for Context.Err.
Threading ¶
A Context, its components and the document they write to belong to one goroutine. Use Loop to give them one and Loop.Post to call in from others.
Index ¶
- Constants
- Variables
- func RenderHTML(w io.Writer, c Component) error
- func StableRows(positions []int) []bool
- type Base
- func (b *Base) Adopt(n NodeID)
- func (b *Base) AtDispose(fn func())
- func (b *Base) Batch(fn func())
- func (b *Base) Context() *Context
- func (b *Base) HTMLSlots() any
- func (b *Base) Invalidate(bit uint)
- func (b *Base) InvalidateAll()
- func (b *Base) IsMounted() bool
- func (b *Base) Mount(parent NodeID, child Component, before NodeID) error
- func (b *Base) Runtime() any
- func (b *Base) SetHTMLSlots(v any)
- func (b *Base) SetInterval(d time.Duration, fn func()) (*Timer, error)
- func (b *Base) SetRuntime(v any)
- func (b *Base) SetTimeout(d time.Duration, fn func()) (*Timer, error)
- func (b *Base) Unmount(child Component) error
- type Behavior
- type Component
- type Context
- func (c *Context) ActiveElement() (NodeID, error)
- func (c *Context) AddListener(n NodeID, typ string, h Handler) Listener
- func (c *Context) AddStyleSheet(key, css string)
- func (c *Context) AfterCommit(fn func())
- func (c *Context) Batch(fn func())
- func (c *Context) Commit() error
- func (c *Context) Contains(ancestor, n NodeID) (bool, error)
- func (c *Context) CreateElement(tag string) NodeID
- func (c *Context) CreateElementNS(ns, name string) NodeID
- func (c *Context) CreateText(text string) NodeID
- func (c *Context) Dispatch(n NodeID, ev *Event)
- func (c *Context) Err() error
- func (c *Context) Focus(n NodeID)
- func (c *Context) FocusFirstTabbable(root NodeID) (bool, error)
- func (c *Context) Insert(parent, child, before NodeID)
- func (c *Context) IsInert(n NodeID) (bool, error)
- func (c *Context) Mount(comp Component) error
- func (c *Context) MountAt(parent NodeID, comp Component, before NodeID) error
- func (c *Context) Move(parent, child, before NodeID)
- func (c *Context) NoteSource(n NodeID, loc SourceLocation)
- func (c *Context) Rect(n NodeID) (r changeset.Rect, ok bool, err error)
- func (c *Context) Remove(n NodeID)
- func (c *Context) RemoveAttribute(n NodeID, name string)
- func (c *Context) RemoveStyle(n NodeID, property string)
- func (c *Context) Report(err error)
- func (c *Context) ScrollBy(n NodeID, dx, dy float64, b Behavior)
- func (c *Context) ScrollIntoView(n NodeID, block, inline ScrollAlign, b Behavior)
- func (c *Context) ScrollMetrics(n NodeID) (m changeset.ScrollMetrics, ok bool, err error)
- func (c *Context) ScrollTo(n NodeID, left, top *float64, b Behavior)
- func (c *Context) SetAttribute(n NodeID, name, value string)
- func (c *Context) SetClass(n NodeID, class string, on bool)
- func (c *Context) SetInterval(d time.Duration, fn func()) (*Timer, error)
- func (c *Context) SetProperty(n NodeID, name, value string)
- func (c *Context) SetQueries(q changeset.Queries)
- func (c *Context) SetScheduler(s Scheduler)
- func (c *Context) SetStyle(n NodeID, property, value string)
- func (c *Context) SetText(n NodeID, text string)
- func (c *Context) SetTimeout(d time.Duration, fn func()) (*Timer, error)
- func (c *Context) Source(n NodeID) (SourceLocation, bool)
- func (c *Context) Tabbable(root NodeID) ([]NodeID, error)
- func (c *Context) Unmount(comp Component) error
- func (c *Context) ViewportSize() (changeset.Size, error)
- type Disposer
- type ElementRef
- func (r *ElementRef) Bind(ctx *Context, n NodeID)
- func (r *ElementRef) Contains(n NodeID) (bool, error)
- func (r *ElementRef) Focus() error
- func (r *ElementRef) FocusFirstTabbable() (bool, error)
- func (r *ElementRef) IsBound() bool
- func (r *ElementRef) IsInert() (bool, error)
- func (r *ElementRef) Node() NodeID
- func (r *ElementRef) Rect() (rect changeset.Rect, ok bool, err error)
- func (r *ElementRef) ScrollBy(dx, dy float64, b Behavior) error
- func (r *ElementRef) ScrollIntoView(block, inline ScrollAlign, b Behavior) error
- func (r *ElementRef) ScrollMetrics() (m changeset.ScrollMetrics, ok bool, err error)
- func (r *ElementRef) ScrollTo(left, top *float64, b Behavior) error
- func (r *ElementRef) SetScrollLeft(v float64) error
- func (r *ElementRef) SetScrollTop(v float64) error
- func (r *ElementRef) Tabbable() ([]NodeID, error)
- func (r *ElementRef) Unbind()
- type Event
- type HTMLRenderer
- type Handler
- type Listener
- type Loop
- type ManualScheduler
- type Mounter
- type NodeID
- type Option
- type RowOps
- type Rows
- type Scheduler
- type ScrollAlign
- type SourceLocation
- type Timer
Examples ¶
Constants ¶
const ( BehaviorAuto = changeset.BehaviorAuto BehaviorInstant = changeset.BehaviorInstant BehaviorSmooth = changeset.BehaviorSmooth )
The scroll behaviors.
const Root = changeset.Root
Root is the container the sink owns; top-level components are inserted into it.
Variables ¶
var ( // ErrInvalidOperation is wrapped by every error for a call made at the // wrong time or in the wrong place: a query inside a binding or while a // sink applies a set, a timer with no scheduler, a reference that is // not bound. ErrInvalidOperation = errors.New("oneui: invalid operation") // ErrNoQueries is returned by a layout or focus query when neither the // sink nor the context supplies [changeset.Queries]. It wraps // [ErrInvalidOperation]. ErrNoQueries = fmt.Errorf("%w: the document answers no queries", ErrInvalidOperation) // ErrNoScheduler is returned by a timer call on a context with no // scheduler. It wraps [ErrInvalidOperation]. ErrNoScheduler = fmt.Errorf("%w: the context has no scheduler", ErrInvalidOperation) // ErrUnbound is returned by an [ElementRef] method called before the element is // created or after it is removed. It wraps [ErrInvalidOperation]. ErrUnbound = fmt.Errorf("%w: the element reference is not bound", ErrInvalidOperation) // ErrReentrant is returned by a query or [Context.Commit] made from // inside a component's Build or Update or while a sink is applying a // set. It wraps [ErrInvalidOperation]. ErrReentrant = fmt.Errorf("%w: not allowed while building, updating or applying", ErrInvalidOperation) )
Errors. Test with errors.Is.
var ErrDuplicateKey = errors.New("oneui: duplicate key in a keyed list")
ErrDuplicateKey is returned by Rows.Sync when a key appears twice.
var ErrNotRenderable = errors.New("oneui: component has no RenderHTML method")
ErrNotRenderable is wrapped by the error RenderHTML returns for a component that has no RenderHTML method, for instance one written by hand. Test for it with errors.Is.
Functions ¶
func RenderHTML ¶
RenderHTML writes the markup of c, for its current state, to w. It is the form of the RenderHTML method every generated component has, for code that holds a Component (the argument order is that of fmt.Fprint: the writer first). It returns an error wrapping ErrNotRenderable when c has no such method, and otherwise the method's result. A value that is not a Component but has the method is called directly. See HTMLRenderer for what the markup contains, when to mount instead, and the error and thread rules.
Example ¶
RenderHTML writes a component's markup for its current state, without mounting it.
package main
import (
"fmt"
"regexp"
"strings"
"recursiveai.org/go/oneui"
todo "recursiveai.org/go/oneui/examples/counter"
)
func main() {
c := &todo.Counter{Count: 3, Name: "Ada", Items: []todo.Todo{{ID: 1, Title: "write", Done: true}}}
var sb strings.Builder
if err := oneui.RenderHTML(&sb, c); err != nil {
panic(err)
}
// Elements carry a data-oui scope attribute, which this example leaves out.
fmt.Println(regexp.MustCompile(` data-oui-[0-9a-f]+=""`).ReplaceAllString(sb.String(), ""))
}
Output: <div class="box"><button>Clicked 3 times</button><input value="Ada"><p title="Hi Ada!">Ada</p><b>many</b><ul><li class="done">0: write</li></ul></div>
Example (NotRenderable) ¶
A component written by hand has no RenderHTML method; the error says so.
package main
import (
"errors"
"fmt"
"io"
"recursiveai.org/go/oneui"
)
// Clock is a component written by hand with the low-level API: it embeds
// oneui.Base, builds its nodes in Build and rewrites the text node in Update
// when state bit 0 is dirty. `oneui generate` writes the same shape from a
// template.
type Clock struct {
oneui.Base
Time string
text oneui.NodeID
}
// SetTime changes the state and marks bit 0.
func (c *Clock) SetTime(t string) {
if c.Time != t {
c.Time = t
c.Invalidate(0)
}
}
func (c *Clock) Build(parent, before oneui.NodeID) {
ctx := c.Context()
p := ctx.CreateElement("p")
c.text = ctx.CreateText(c.Time)
ctx.Insert(p, c.text, oneui.Append)
ctx.Insert(parent, p, before)
c.Adopt(p)
}
func (c *Clock) Update(dirty uint64) {
if dirty&1 != 0 {
c.Context().SetText(c.text, c.Time)
}
}
func main() {
err := oneui.RenderHTML(io.Discard, &Clock{})
fmt.Println(errors.Is(err, oneui.ErrNotRenderable))
}
Output: true
func StableRows ¶
StableRows marks which entries of positions form the longest strictly increasing run, ignoring negative entries (new rows). The marked rows can stay where they are; the others must move.
Types ¶
type Base ¶
type Base struct {
// contains filtered or unexported fields
}
Base is embedded in every component. The zero value is ready; a component must not be copied after it is mounted.
func (*Base) Adopt ¶
Adopt records a node the component inserted at its top level, so that unmounting the component removes it. For generated code and hand-written components that build nodes in Build.
func (*Base) AtDispose ¶
func (b *Base) AtDispose(fn func())
AtDispose registers fn to run when the component is unmounted, in registration order, before its OnDisposed and before its children are disposed.
func (*Base) Batch ¶
func (b *Base) Batch(fn func())
Batch runs fn as one batch of the component's context; see Context.Batch.
func (*Base) Context ¶
Context returns the context the component is mounted in, or nil before it is mounted.
func (*Base) HTMLSlots ¶
HTMLSlots returns what Base.SetHTMLSlots stored, or nil. It is for generated code.
func (*Base) Invalidate ¶
Invalidate marks state bit (0 to 63) changed and schedules an Update: at the end of the open batch, or at once when none is open. Before the component is mounted it does nothing, because Build reads the current state.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneui"
"recursiveai.org/go/oneui/dom"
)
// Clock is a component written by hand with the low-level API: it embeds
// oneui.Base, builds its nodes in Build and rewrites the text node in Update
// when state bit 0 is dirty. `oneui generate` writes the same shape from a
// template.
type Clock struct {
oneui.Base
Time string
text oneui.NodeID
}
// SetTime changes the state and marks bit 0.
func (c *Clock) SetTime(t string) {
if c.Time != t {
c.Time = t
c.Invalidate(0)
}
}
func (c *Clock) Build(parent, before oneui.NodeID) {
ctx := c.Context()
p := ctx.CreateElement("p")
c.text = ctx.CreateText(c.Time)
ctx.Insert(p, c.text, oneui.Append)
ctx.Insert(parent, p, before)
c.Adopt(p)
}
func (c *Clock) Update(dirty uint64) {
if dirty&1 != 0 {
c.Context().SetText(c.text, c.Time)
}
}
func main() {
doc := dom.New()
ctx := oneui.New(doc)
clock := &Clock{Time: "a"}
_ = ctx.Mount(clock)
// Several changes in a batch produce one Update.
ctx.Batch(func() {
clock.SetTime("b")
clock.SetTime("c")
})
fmt.Println(doc.HTML(), len(doc.Commits())) // the mount, then one update
}
Output: <p>c</p> 2
func (*Base) InvalidateAll ¶
func (b *Base) InvalidateAll()
InvalidateAll marks every state bit changed.
func (*Base) IsMounted ¶
IsMounted reports whether the component is mounted: its Build has run and it has not been unmounted.
func (*Base) Mount ¶
Mount builds child into parent before the sibling before (Append for the end) as a child component of b's: it is unmounted with b. It returns an error for a nil or already mounted child, or when b is not mounted in a context. For generated code and components that nest others; a top-level component is mounted with Context.Mount.
func (*Base) Runtime ¶
Runtime returns the value stored with Base.SetRuntime.
For generated code. It is the slot where the generated component keeps its update scope, and application code that overwrites it breaks every later Update of the component, which then panics naming the component. Nil until the generated Build sets it.
func (*Base) SetHTMLSlots ¶
SetHTMLSlots stores the slot content a parent passes to a child it is about to render with RenderHTML. It is for generated code and kept apart from Base.SetRuntime, which a component may use for its own purposes.
func (*Base) SetInterval ¶
SetInterval runs fn every d, as one batch each time, until the component is unmounted or the timer stopped. Errors as for Base.SetTimeout.
func (*Base) SetRuntime ¶
SetRuntime stores the value for Base.Runtime. For generated code; see Runtime.
func (*Base) SetTimeout ¶
SetTimeout runs fn once after d, as one batch, unless the component is unmounted first. It returns ErrNoScheduler when the context has none and an ErrInvalidOperation error when the component is not mounted.
type Behavior ¶
type Behavior = changeset.ScrollBehavior
Behavior is a scroll behavior: BehaviorAuto, BehaviorInstant or BehaviorSmooth.
type Component ¶
type Component interface {
// Build creates the component's nodes and inserts them into parent
// before the sibling before ([Append] for the end). It runs once, when the
// component is mounted, and must not query layout.
Build(parent, before NodeID)
// Update brings the nodes bound to changed state in line with it. dirty
// has bit i set when state i changed since the last update. It must not
// query layout.
Update(dirty uint64)
// contains filtered or unexported methods
}
Component is a unit of UI: a struct that embeds Base. The methods are written by `oneui generate` (or by hand for a low-level component).
Component is sealed on purpose: it has an unexported method that only Base provides, so every component embeds Base and the runtime can keep its lifecycle state in one place without asking each implementation to get it right. A hand-written component embeds Base and implements Build and Update; see the Component example.
Example ¶
A component is a struct that embeds Base. It is sealed: Build and Update are the whole contract, and only Base provides the rest.
package main
import (
"fmt"
"recursiveai.org/go/oneui"
"recursiveai.org/go/oneui/dom"
)
// Clock is a component written by hand with the low-level API: it embeds
// oneui.Base, builds its nodes in Build and rewrites the text node in Update
// when state bit 0 is dirty. `oneui generate` writes the same shape from a
// template.
type Clock struct {
oneui.Base
Time string
text oneui.NodeID
}
// SetTime changes the state and marks bit 0.
func (c *Clock) SetTime(t string) {
if c.Time != t {
c.Time = t
c.Invalidate(0)
}
}
func (c *Clock) Build(parent, before oneui.NodeID) {
ctx := c.Context()
p := ctx.CreateElement("p")
c.text = ctx.CreateText(c.Time)
ctx.Insert(p, c.text, oneui.Append)
ctx.Insert(parent, p, before)
c.Adopt(p)
}
func (c *Clock) Update(dirty uint64) {
if dirty&1 != 0 {
c.Context().SetText(c.text, c.Time)
}
}
func main() {
doc := dom.New()
ctx := oneui.New(doc) // connects the document's events to the context
clock := &Clock{Time: "12:00"}
if err := ctx.Mount(clock); err != nil {
fmt.Println(err)
return
}
fmt.Println(doc.HTML())
clock.SetTime("12:01") // one change set, touching one text node
fmt.Println(doc.HTML())
}
Output: <p>12:00</p> <p>12:01</p>
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context owns the document connection of one component tree: it allocates node ids, records the changes components make, batches them into change sets for the sink, routes the sink's events back to handlers, runs timers and answers layout queries.
A Context and everything attached to it belong to one goroutine (the UI goroutine). To call in from others, use Loop.Post or a host's equivalent.
Methods by audience ¶
Writing the document, for components and tools: CreateElement, CreateElementNS, CreateText, Insert, Move, Remove, SetAttribute, RemoveAttribute, SetText, SetClass, SetStyle, RemoveStyle, SetProperty, AddStyleSheet, Focus, ScrollIntoView, ScrollTo, ScrollBy and AddListener.
Running the application: Mount, MountAt, Unmount, Batch, Commit, AfterCommit, SetTimeout, SetInterval, SetScheduler, SetQueries, Err and Dispatch (called by the sink).
Asking the document: Rect, ViewportSize, ScrollMetrics, Tabbable, FocusFirstTabbable, ActiveElement, Contains and IsInert. Each commits first and fails with ErrNoQueries when the sink answers no queries.
For generated code and tooling only: Report, NoteSource and Source.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneui"
"recursiveai.org/go/oneui/dom"
)
func main() {
doc := dom.New()
ctx := oneui.New(doc)
ctx.Batch(func() { // one change set for everything in the batch
p := ctx.CreateElement("p")
ctx.SetAttribute(p, "class", "note")
ctx.Insert(p, ctx.CreateText("hello"), oneui.Append)
ctx.Insert(oneui.Root, p, oneui.Append)
})
fmt.Println(doc.HTML(), len(doc.Commits()))
}
Output: <p class="note">hello</p> 1
func New ¶
New returns a context that writes to sink. The first node it allocates has id 2; Root is the sink's.
When the sink can be told where its events go (it has a SetDispatcher(changeset.Dispatcher) method, as the reference document and the browser host do), New connects the new context to it, so events the sink raises reach the components' handlers.
func (*Context) ActiveElement ¶
ActiveElement returns document.activeElement, or 0 for none.
func (*Context) AddListener ¶
AddListener reports events of DOM type typ on n to h. Handlers on one node and type run in the order they were added. The sink is told once per node and type, when the first handler is added.
func (*Context) AddStyleSheet ¶
AddStyleSheet adds a style sheet to the document once per key (a second call with the same key does nothing); css is the text for the whole document.
func (*Context) AfterCommit ¶
func (c *Context) AfterCommit(fn func())
AfterCommit runs fn once, after the next commit has been applied (even when the commit is empty). Lifecycle callbacks such as OnMounted use it.
func (*Context) Batch ¶
func (c *Context) Batch(fn func())
Batch runs fn with commits deferred: state changes and recorded changes made inside it are applied once, as one change set, when the outermost batch ends. Batches nest. If fn panics the panic propagates and the recorded changes wait for the next commit.
func (*Context) Commit ¶
Commit applies what has been recorded now, running dirty bindings first, even inside a batch. Queries call it, like a forced synchronous layout. It returns the sink's error, if any, and ErrReentrant from inside Build or Update or while the sink applies.
func (*Context) CreateElement ¶
CreateElement creates a detached HTML element with the lower-case tag.
func (*Context) CreateElementNS ¶
CreateElementNS creates a detached element in a namespace, for SVG (changeset.SVGNamespace); name keeps its case ("linearGradient").
func (*Context) CreateText ¶
CreateText creates a detached text node.
func (*Context) Dispatch ¶
Dispatch delivers an event from the sink to the handlers of node n and type ev.Type, as one batch: the state changes the handlers make are committed together. The sink calls it for each node on the event's path that has a listener, stopping when the event's propagation is stopped. An event for a node with no handler of that type is dropped and reported to the error handler.
Dispatch implements changeset.Dispatcher. An event that arrives while the sink is applying a set is queued and delivered when the set has been applied, so a sink is never re-entered.
func (*Context) Err ¶
Err returns the first error the sink returned since the last call to Err and clears it. Errors also go to the error handler when set.
func (*Context) Focus ¶
Focus asks the document to focus the node once the set is applied. Nothing happens when it is not a focusable area.
func (*Context) FocusFirstTabbable ¶
FocusFirstTabbable records a Focus for the first tabbable element inside root and reports whether there was one.
func (*Context) Insert ¶
Insert puts the detached child into parent before the sibling before, or at the end when before is 0.
func (*Context) Mount ¶
Mount builds a top-level component into the root container and commits. Its OnMounted runs after the commit. It returns an error for a nil or already mounted component.
func (*Context) MountAt ¶
MountAt is Context.Mount into another parent, before a sibling (Append for the end).
func (*Context) NoteSource ¶
func (c *Context) NoteSource(n NodeID, loc SourceLocation)
NoteSource records where a node was written in its template. For generated code (in programs built with the oneui_reload tag) and tooling.
func (*Context) Rect ¶
Rect returns the node's border box in viewport coordinates (CSS px); ok is false for an element with no box. Like every query it commits first.
func (*Context) Remove ¶
Remove destroys the node's subtree and its listeners. Removing a node that is already gone does nothing.
func (*Context) RemoveAttribute ¶
RemoveAttribute removes an attribute.
func (*Context) RemoveStyle ¶
RemoveStyle removes one inline style property.
func (*Context) Report ¶
Report sends a problem to the error handler and remembers it for Context.Err (the first one is kept). For generated code, which uses it for errors it cannot return to a caller. A nil error is ignored.
func (*Context) ScrollIntoView ¶
func (c *Context) ScrollIntoView(n NodeID, block, inline ScrollAlign, b Behavior)
ScrollIntoView is element.scrollIntoView({block, inline, behavior}). The DOM default is block start and inline nearest.
func (*Context) ScrollMetrics ¶
ScrollMetrics returns the node's scroll offsets and extents; ok is false when it has none.
func (*Context) ScrollTo ¶
ScrollTo is element.scrollTo({left, top, behavior}); a nil axis stays where it is.
func (*Context) SetAttribute ¶
SetAttribute sets an attribute. Name "class" replaces the class list.
func (*Context) SetInterval ¶
SetInterval runs fn every d, as one batch each time. An interval is re-armed when it fires, so a slow callback never queues extra runs. It returns ErrNoScheduler when the context has no scheduler.
func (*Context) SetProperty ¶
SetProperty sets a DOM property ("value", "checked") from its text form; "checked" takes "true" or "false".
func (*Context) SetQueries ¶
SetQueries sets where queries are answered; nil removes them, even the sink's.
func (*Context) SetScheduler ¶
SetScheduler sets the scheduler timers use. Timers already running keep the scheduler they started with.
func (*Context) SetTimeout ¶
SetTimeout runs fn once after d, as one batch (like an event handler). It returns ErrNoScheduler when the context has no scheduler.
func (*Context) Source ¶
func (c *Context) Source(n NodeID) (SourceLocation, bool)
Source returns the location recorded with Context.NoteSource for a node, if any. For tooling.
func (*Context) Tabbable ¶
Tabbable lists the elements inside root that Tab reaches, in sequential focus order.
type Disposer ¶
type Disposer interface{ OnDisposed() }
Disposer is implemented by components that want a callback when they are unmounted, after their timers stopped. A parent's OnDisposed runs before its children's.
type ElementRef ¶
type ElementRef struct {
// contains filtered or unexported fields
}
ElementRef is a reference to an element of a template (ref="{Member}"). The generated Build binds it; a method on an unbound ElementRef returns ErrUnbound. An ElementRef becomes unbound when its element is removed.
func (*ElementRef) Bind ¶
func (r *ElementRef) Bind(ctx *Context, n NodeID)
Bind points the reference at node n of context ctx.
func (*ElementRef) Contains ¶
func (r *ElementRef) Contains(n NodeID) (bool, error)
Contains is Node.contains (inclusive) for another node.
func (*ElementRef) Focus ¶
func (r *ElementRef) Focus() error
Focus focuses the element, as element.focus().
func (*ElementRef) FocusFirstTabbable ¶
func (r *ElementRef) FocusFirstTabbable() (bool, error)
FocusFirstTabbable focuses the first tabbable element inside this one.
func (*ElementRef) IsBound ¶
func (r *ElementRef) IsBound() bool
IsBound reports whether the element exists.
func (*ElementRef) IsInert ¶
func (r *ElementRef) IsInert() (bool, error)
IsInert reports whether the element or an ancestor is inert.
func (*ElementRef) Node ¶
func (r *ElementRef) Node() NodeID
NodeID returns the element's node id, or 0 when unbound.
func (*ElementRef) Rect ¶
func (r *ElementRef) Rect() (rect changeset.Rect, ok bool, err error)
Rect is getBoundingClientRect: the border box in viewport coordinates; ok is false for an element with no box.
func (*ElementRef) ScrollBy ¶
func (r *ElementRef) ScrollBy(dx, dy float64, b Behavior) error
ScrollBy is element.scrollBy; see Context.ScrollBy.
func (*ElementRef) ScrollIntoView ¶
func (r *ElementRef) ScrollIntoView(block, inline ScrollAlign, b Behavior) error
ScrollIntoView is element.scrollIntoView; see Context.ScrollIntoView.
func (*ElementRef) ScrollMetrics ¶
func (r *ElementRef) ScrollMetrics() (m changeset.ScrollMetrics, ok bool, err error)
ScrollMetrics returns the element's scroll offsets and extents.
func (*ElementRef) ScrollTo ¶
func (r *ElementRef) ScrollTo(left, top *float64, b Behavior) error
ScrollTo is element.scrollTo; see Context.ScrollTo.
func (*ElementRef) SetScrollLeft ¶
func (r *ElementRef) SetScrollLeft(v float64) error
SetScrollLeft is `element.scrollLeft = v`: a ScrollTo that leaves the vertical axis alone.
func (*ElementRef) SetScrollTop ¶
func (r *ElementRef) SetScrollTop(v float64) error
SetScrollTop is `element.scrollTop = v`: a ScrollTo that leaves the horizontal axis alone.
func (*ElementRef) Tabbable ¶
func (r *ElementRef) Tabbable() ([]NodeID, error)
Tabbable lists the elements inside this one that Tab reaches, in order.
type Event ¶
Event is a DOM event reported by the sink. It is changeset.Event.
type HTMLRenderer ¶
HTMLRenderer is implemented by every component `oneui generate` compiled. RenderHTML writes the component's markup for its current state to w, without mounting it: no nodes and no change sets are created, which makes it the way to produce a first paint or a server-rendered page. The generated method is the primary way to call it; RenderHTML is the adapter for a Component held as an interface.
RenderHTML or mount? ¶
A child component is built from the parameters its parent passes and shows its default state, not state a user changed in a mounted child. The markup is a snapshot of the struct's fields: lifecycle callbacks (mount, dispose, timers) do not run, so state they would set is not there, and values a user typed live in the document, not in the struct, so they are absent. Stylesheets and event listeners are not part of the markup; deliver the CSS separately. Elements carry the data-oui-<hash> attribute their stylesheet scope needs. A bound value is written as the HTML attribute with the same meaning (value, checked; a textarea's value as its content; a select gets none). The text is the HTML Standard's serialisation ("Serializing HTML fragments"), except that U+00A0 is written as the character and not as .
Mounting over markup this wrote is not supported: a mount builds its own nodes and does not adopt existing ones (there is no hydration), so replace the server's markup with the mounted component's nodes.
Errors and threads ¶
On error the output is incomplete: it may hold a prefix of the page. The error is the first one w returned, as is. A panic in a template expression propagates. RenderHTML reads the component without synchronisation, so it must not run at the same time as a setter of the same component; renders of different components may run concurrently.
type Handler ¶
type Handler func(*Event)
Handler handles an event. It runs on the context's goroutine inside a batch, so the state changes it makes become one change set.
type Listener ¶
type Listener struct {
// contains filtered or unexported fields
}
Listener identifies one handler added with Context.AddListener.
type Loop ¶
type Loop struct {
// contains filtered or unexported fields
}
Loop is a single-goroutine event loop and a real-time Scheduler: the goroutine that calls Loop.Run executes every posted function and every due timer, one at a time, so a Context used only from there needs no locks. Post, Schedule, Stop and the Stop of the timers Schedule returns are safe from any goroutine. Create a loop with NewLoop: the zero Loop is not usable.
Example ¶
package main
import (
"context"
"fmt"
"recursiveai.org/go/oneui"
)
func main() {
loop := oneui.NewLoop()
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { _ = loop.Run(ctx); close(done) }()
result := make(chan string)
loop.Post(func() { result <- "ran on the loop's goroutine" })
fmt.Println(<-result)
cancel()
<-done
fmt.Println(loop.Post(func() {})) // false: the loop is closed
}
Output: ran on the loop's goroutine false
func (*Loop) Post ¶
Post queues fn to run on the loop's goroutine. It reports false when the loop is closed (Stop was called or Run's context ended), in which case fn will never run.
func (*Loop) Run ¶
Run executes posted functions until ctx is done or Loop.Stop is called, then returns ctx's error (nil after Stop). The loop sleeps while idle.
type ManualScheduler ¶
type ManualScheduler struct {
// contains filtered or unexported fields
}
ManualScheduler is a Scheduler whose clock only moves when a test says so. Nothing runs until ManualScheduler.Advance. It is for one goroutine.
Example ¶
package main
import (
"fmt"
"time"
"recursiveai.org/go/oneui"
"recursiveai.org/go/oneui/dom"
)
func main() {
doc := dom.New()
clock := &oneui.ManualScheduler{}
ctx := oneui.New(doc, oneui.WithScheduler(clock))
n := 0
_, _ = ctx.SetInterval(time.Second, func() { n++ })
clock.Advance(3500 * time.Millisecond)
fmt.Println(n)
}
Output: 3
func (*ManualScheduler) Advance ¶
func (m *ManualScheduler) Advance(d time.Duration)
Advance moves the clock forward by d, running what falls due in order of due time (ties in the order scheduled). Each callback runs with the clock at its own due time, so work it schedules is measured from there.
func (*ManualScheduler) Now ¶
func (m *ManualScheduler) Now() time.Duration
Now returns the scheduler's clock, starting at zero.
func (*ManualScheduler) Pending ¶
func (m *ManualScheduler) Pending() int
Pending returns the number of scheduled callbacks that have neither run nor been cancelled.
type Mounter ¶
type Mounter interface{ OnMounted() }
Mounter is implemented by components that want a callback after the commit that mounted them.
type NodeID ¶
NodeID names a node of the document. It is changeset.NodeID. The zero value names no node; as a "before" argument it means Append.
const Append NodeID = 0
Append is the "before" argument that places a node after its parent's last child.
type Option ¶
type Option func(*Context)
Option configures New.
func WithErrorHandler ¶
WithErrorHandler sets a function that receives problems the context cannot return to a caller: a sink refusing a set, an event for a node with no listener, an Update that never settles. The default drops them (see Context.Err). The function runs on the context's goroutine.
func WithQueries ¶
WithQueries sets where layout and focus queries are answered. By default they go to the sink, when it implements changeset.Queries.
func WithScheduler ¶
WithScheduler sets the scheduler timers use.
type RowOps ¶
type RowOps[K comparable, R any] struct { // Create builds the row for the key at position index and inserts its // nodes before the sibling before ([Append] for the end). Create func(index int, key K, before NodeID) R // Move moves the row's nodes before the sibling before ([Append] for the end). Move func(row R, before NodeID) // Remove removes the row's nodes and disposes what it holds. Remove func(row R) // First returns the row's first node, the anchor for the row before it. First func(row R) NodeID }
RowOps are the callbacks of Rows. R is whatever the generated code keeps per row (its nodes, its child component).
type Rows ¶
type Rows[K comparable, R any] struct { // contains filtered or unexported fields }
Rows reconciles a keyed list of rows with new keys using the fewest changes: rows whose key is gone are removed, new rows are created from the last to the first, and of the rows that stay only those outside the longest run already in order are moved.
func NewRows ¶
func NewRows[K comparable, R any](ops RowOps[K, R], end NodeID) *Rows[K, R]
NewRows returns an empty list whose rows come before the node end (0 for the end of the parent).
func (*Rows[K, R]) Sync ¶
Sync makes the rows match keys. A duplicate key returns ErrDuplicateKey and changes nothing.
Example ¶
package main
import (
"fmt"
"recursiveai.org/go/oneui"
)
func main() {
var log []string
rows := oneui.NewRows(oneui.RowOps[string, string]{
Create: func(i int, key string, before oneui.NodeID) string { log = append(log, "create "+key); return key },
Move: func(row string, before oneui.NodeID) { log = append(log, "move "+row) },
Remove: func(row string) { log = append(log, "remove "+row) },
First: func(row string) oneui.NodeID { return 2 },
}, oneui.Append)
_ = rows.Sync([]string{"a", "b", "c"})
log = nil
_ = rows.Sync([]string{"a", "c", "d"}) // b goes, d is new, a and c stay put
fmt.Println(log)
}
Output: [remove b create d]
type Scheduler ¶
Scheduler runs callbacks later on the context's goroutine. Schedule arranges fn to run once after delay and returns the Timer that cancels it (Stop is safe to call more than once, and after fn ran). The host chooses the clock: a Loop for real time, a ManualScheduler for tests.
type ScrollAlign ¶
type ScrollAlign string
ScrollAlign is a scroll alignment: ScrollAlignStart, ScrollAlignCenter, ScrollAlignEnd or ScrollAlignNearest.
const ( ScrollAlignStart ScrollAlign = "start" ScrollAlignCenter ScrollAlign = "center" ScrollAlignEnd ScrollAlign = "end" ScrollAlignNearest ScrollAlign = "nearest" )
The scroll alignments of CSSOM View's ScrollIntoViewOptions.
type SourceLocation ¶
SourceLocation says where an element was written in its template. Programs built with the oneui_reload tag record it for template reload and tooling.
type Timer ¶
type Timer struct {
// contains filtered or unexported fields
}
Timer is a pending timeout or interval, or the handle a Scheduler returns for one callback. Like time.Timer it is used from one goroutine, except the timers a Loop returns, whose Stop is safe from any goroutine. The zero Timer is stopped.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package browser runs oneui components in a web page.
|
Package browser runs oneui components in a web page. |
|
Package changeset defines the change-set protocol (version 3): the backend-neutral stream of document mutations that components write and a sink (the reference DOM, a native document or the browser) applies, together with the events a sink reports back.
|
Package changeset defines the change-set protocol (version 3): the backend-neutral stream of document mutations that components write and a sink (the reference DOM, a native document or the browser) applies, together with the events a sink reports back. |
|
cmd
|
|
|
oneui
command
Command oneui compiles component templates into Go.
|
Command oneui compiles component templates into Go. |
|
Package dom is the reference document of the change-set protocol: an in-memory DOM that applies [changeset.ChangeSet]s, validates them, answers selector and accessibility queries and drives events the way a browser's default actions would.
|
Package dom is the reference document of the change-set protocol: an in-memory DOM that applies [changeset.ChangeSet]s, validates them, answers selector and accessibility queries and drives events the way a browser's default actions would. |
|
examples
|
|
|
browser
command
Command browser is the counter component running in a web page: the generated component from examples/counter, registered as the custom element <x-counter>.
|
Command browser is the counter component running in a web page: the generated component from examples/counter, registered as the custom element <x-counter>. |
|
counter
Package counter is a component written for `oneui generate`: a template, a stylesheet and this struct.
|
Package counter is a component written for `oneui generate`: a template, a stylesheet and this struct. |
|
Package gen compiles component templates and scoped stylesheets into Go.
|
Package gen compiles component templates and scoped stylesheets into Go. |
|
internal
|
|
|
compiler
Package compiler is the checker and code generator behind package gen and template reload.
|
Package compiler is the checker and code generator behind package gen and template reload. |
|
htmlnorm
Package htmlnorm maps the reference document's serialisation to what RenderHTML writes, for the tests that compare the two.
|
Package htmlnorm maps the reference document's serialisation to what RenderHTML writes, for the tests that compare the two. |
|
reloadimpl
Package reload swaps the template of a running component without restarting the program, for debug builds.
|
Package reload swaps the template of a running component without restarting the program, for debug builds. |
|
renderdiff
Package renderdiff holds components that use every part of the template language, for the test that compares RenderHTML with the document a mount builds.
|
Package renderdiff holds components that use every part of the template language, for the test that compares RenderHTML with the document a mount builds. |
|
Package oneuitest mounts a component in the reference document for tests.
|
Package oneuitest mounts a component in the reference document for tests. |
|
Package reload swaps the template of a running component without restarting the program, for debug builds.
|
Package reload swaps the template of a running component without restarting the program, for debug builds. |
|
Package rt is the support library that code written by `oneui generate` calls.
|
Package rt is the support library that code written by `oneui generate` calls. |
|
reload
Package reload is the part of template reload that generated code calls in programs built with the oneui_reload tag.
|
Package reload is the part of template reload that generated code calls in programs built with the oneui_reload tag. |
|
Package template parses OneUI component templates and scoped stylesheets.
|
Package template parses OneUI component templates and scoped stylesheets. |
|
Package ui is an engine-free retained UI tree: elements, CSS-model styles and style sheets, flexbox layout, input routing and focus, tweens, and a display list that a host paints.
|
Package ui is an engine-free retained UI tree: elements, CSS-model styles and style sheets, flexbox layout, input routing and focus, tweens, and a display list that a host paints. |
|
kit
Package kit is the component kit built on the retained tree: buttons, toggles, radio groups, sliders, steppers, dropdowns, tabs, dialogs, lists, tables, scroll views and text inputs, a light and a dark theme, input glyphs and tooltips.
|
Package kit is the component kit built on the retained tree: buttons, toggles, radio groups, sliders, steppers, dropdowns, tabs, dialogs, lists, tables, scroll views and text inputs, a light and a dark theme, input glyphs and tooltips. |