oneui

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 5, 2026 License: Apache-2.0, MIT Imports: 10 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

oneui

A pure-Go component model. A component is an HTML template, optional scoped CSS and a Go struct; oneui generate compiles it into plain Go that updates only the nodes bound to changed state, and emits a backend-neutral change-set stream. Includes a reference DOM with selector and accessibility queries, an engine-free retained UI tree, and a browser backend for GOOS=js GOARCH=wasm.

Licence: MIT OR Apache-2.0.

Quick start

A component is a template next to a Go struct. Hello.html:

<button on:click="Increment">Clicked {Count} times</button>

main.go:

package main

//go:generate go run recursiveai.org/go/oneui/cmd/oneui generate

import (
	"os"

	"recursiveai.org/go/oneui"
)

type Hello struct {
	oneui.Base
	Count int `oneui:"state"`
}

func (h *Hello) Increment() { h.SetCount(h.Count + 1) }

func main() {
	h := &Hello{}
	h.Increment()
	oneui.RenderHTML(os.Stdout, h)
}
go mod init example.com/hello
go get recursiveai.org/go/oneui@v1.0.0
go generate ./...
go run .
# <button>Clicked 1 times</button>

go generate writes Hello_oneui.go with SetCount and the code that updates only the button's text when Count changes. The same component runs in a test (below), in the browser and in any backend that applies change sets.

State and generated code

A field tagged oneui:"state" gets two generated methods: SetX replaces the value (and updates the bound nodes only when it changed, for types Go can compare; for slices, maps and structs holding them it always updates) and NotifyXChanged tells the component the value was changed in place. Generated files call the support package rt, which is versioned with the generator and is outside the compatibility promise: regenerate after upgrading. A generated file built against another runtime version stops at start-up with a message that says so.

Testing a component

oneui/oneuitest mounts a component in the reference document, with a manual clock:

page := oneuitest.Mount(t, &counter.Counter{})
page.Click("button")
if got := page.Text("button"); got != "Clicked 1 times" {
	t.Fatal(got)
}

Rendering to HTML

Every generated component has RenderHTML(w io.Writer) error, and oneui.RenderHTML(w, c) does the same for any oneui.Component: the markup for the current state, written without creating nodes, for first paint or server-side rendering. Read "RenderHTML or mount?" on oneui.HTMLRenderer first: a child shows its default state, nothing a user typed is in the markup, no lifecycle callbacks run, stylesheets and listeners are not emitted, and mounting over the markup is not supported (no hydration). Bound values are written as the HTML attribute with the same meaning (value, checked).

In the browser

recursiveai.org/go/oneui/browser (GOOS=js GOARCH=wasm) applies change sets to the page's real DOM, routes DOM events back to your handlers and registers components as custom elements:

func main() {
	browser.Define("x-counter", func() oneui.Component { return &counter.Counter{} })
	select {} // the page drives the program from here on
}

examples/browser builds and runs it (./build.sh, then serve the folder). The browser package's tests (browser/host_js_test.go) run in a real page: build the test binary with GOOS=js GOARCH=wasm go test -c ./browser and host it, with Go's wasm_exec.js, in a headless browser.

Speed

A 1,000-row list against templ and go-app, each checked to produce the same markup first (bench/METHOD.md, bench/RESULTS.md; AMD Ryzen 9 7950X3D, Go 1.26, six counts):

oneui templ go-app
Render to HTML 28.3 µs 537 µs 1.11 ms
Update one row, live (change set) 13.9 µs — —
Update one row, server re-render 29.1 µs 471 µs 1.08 ms
Update all rows, server re-render 29.5 µs 500 µs 1.18 ms

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

Examples

Constants

View Source
const (
	BehaviorAuto    = changeset.BehaviorAuto
	BehaviorInstant = changeset.BehaviorInstant
	BehaviorSmooth  = changeset.BehaviorSmooth
)

The scroll behaviors.

View Source
const Root = changeset.Root

Root is the container the sink owns; top-level components are inserted into it.

Variables

View Source
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.

View Source
var ErrDuplicateKey = errors.New("oneui: duplicate key in a keyed list")

ErrDuplicateKey is returned by Rows.Sync when a key appears twice.

View Source
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

func RenderHTML(w io.Writer, c Component) error

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

func StableRows(positions []int) []bool

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

func (b *Base) Adopt(n NodeID)

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

func (b *Base) Context() *Context

Context returns the context the component is mounted in, or nil before it is mounted.

func (*Base) HTMLSlots

func (b *Base) HTMLSlots() any

HTMLSlots returns what Base.SetHTMLSlots stored, or nil. It is for generated code.

func (*Base) Invalidate

func (b *Base) Invalidate(bit uint)

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

func (b *Base) IsMounted() bool

IsMounted reports whether the component is mounted: its Build has run and it has not been unmounted.

func (*Base) Mount

func (b *Base) Mount(parent NodeID, child Component, before NodeID) error

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

func (b *Base) Runtime() any

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

func (b *Base) SetHTMLSlots(v any)

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

func (b *Base) SetInterval(d time.Duration, fn func()) (*Timer, error)

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

func (b *Base) SetRuntime(v any)

SetRuntime stores the value for Base.Runtime. For generated code; see Runtime.

func (*Base) SetTimeout

func (b *Base) SetTimeout(d time.Duration, fn func()) (*Timer, error)

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.

func (*Base) Unmount

func (b *Base) Unmount(child Component) error

Unmount unmounts a child component mounted with Base.Mount and removes its nodes. For generated code, with Mount.

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

func New(sink changeset.Sink, opts ...Option) *Context

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

func (c *Context) ActiveElement() (NodeID, error)

ActiveElement returns document.activeElement, or 0 for none.

func (*Context) AddListener

func (c *Context) AddListener(n NodeID, typ string, h Handler) Listener

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

func (c *Context) AddStyleSheet(key, css string)

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

func (c *Context) Commit() error

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) Contains

func (c *Context) Contains(ancestor, n NodeID) (bool, error)

Contains is Node.contains (inclusive).

func (*Context) CreateElement

func (c *Context) CreateElement(tag string) NodeID

CreateElement creates a detached HTML element with the lower-case tag.

func (*Context) CreateElementNS

func (c *Context) CreateElementNS(ns, name string) NodeID

CreateElementNS creates a detached element in a namespace, for SVG (changeset.SVGNamespace); name keeps its case ("linearGradient").

func (*Context) CreateText

func (c *Context) CreateText(text string) NodeID

CreateText creates a detached text node.

func (*Context) Dispatch

func (c *Context) Dispatch(n NodeID, ev *Event)

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

func (c *Context) Err() error

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

func (c *Context) Focus(n NodeID)

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

func (c *Context) FocusFirstTabbable(root NodeID) (bool, error)

FocusFirstTabbable records a Focus for the first tabbable element inside root and reports whether there was one.

func (*Context) Insert

func (c *Context) Insert(parent, child, before NodeID)

Insert puts the detached child into parent before the sibling before, or at the end when before is 0.

func (*Context) IsInert

func (c *Context) IsInert(n NodeID) (bool, error)

IsInert reports whether the node or an ancestor has the inert attribute.

func (*Context) Mount

func (c *Context) Mount(comp Component) error

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

func (c *Context) MountAt(parent NodeID, comp Component, before NodeID) error

MountAt is Context.Mount into another parent, before a sibling (Append for the end).

func (*Context) Move

func (c *Context) Move(parent, child, before NodeID)

Move repositions a node already in the tree (identity and listeners kept).

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

func (c *Context) Rect(n NodeID) (r changeset.Rect, ok bool, err error)

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

func (c *Context) Remove(n NodeID)

Remove destroys the node's subtree and its listeners. Removing a node that is already gone does nothing.

func (*Context) RemoveAttribute

func (c *Context) RemoveAttribute(n NodeID, name string)

RemoveAttribute removes an attribute.

func (*Context) RemoveStyle

func (c *Context) RemoveStyle(n NodeID, property string)

RemoveStyle removes one inline style property.

func (*Context) Report

func (c *Context) Report(err error)

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) ScrollBy

func (c *Context) ScrollBy(n NodeID, dx, dy float64, b Behavior)

ScrollBy is element.scrollBy({left: dx, top: dy, behavior}).

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

func (c *Context) ScrollMetrics(n NodeID) (m changeset.ScrollMetrics, ok bool, err error)

ScrollMetrics returns the node's scroll offsets and extents; ok is false when it has none.

func (*Context) ScrollTo

func (c *Context) ScrollTo(n NodeID, left, top *float64, b Behavior)

ScrollTo is element.scrollTo({left, top, behavior}); a nil axis stays where it is.

func (*Context) SetAttribute

func (c *Context) SetAttribute(n NodeID, name, value string)

SetAttribute sets an attribute. Name "class" replaces the class list.

func (*Context) SetClass

func (c *Context) SetClass(n NodeID, class string, on bool)

SetClass adds the class when on is true and removes it otherwise.

func (*Context) SetInterval

func (c *Context) SetInterval(d time.Duration, fn func()) (*Timer, error)

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

func (c *Context) SetProperty(n NodeID, name, value string)

SetProperty sets a DOM property ("value", "checked") from its text form; "checked" takes "true" or "false".

func (*Context) SetQueries

func (c *Context) SetQueries(q changeset.Queries)

SetQueries sets where queries are answered; nil removes them, even the sink's.

func (*Context) SetScheduler

func (c *Context) SetScheduler(s Scheduler)

SetScheduler sets the scheduler timers use. Timers already running keep the scheduler they started with.

func (*Context) SetStyle

func (c *Context) SetStyle(n NodeID, property, value string)

SetStyle sets one inline style property (or a --custom property).

func (*Context) SetText

func (c *Context) SetText(n NodeID, text string)

SetText sets the data of a text node.

func (*Context) SetTimeout

func (c *Context) SetTimeout(d time.Duration, fn func()) (*Timer, error)

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

func (c *Context) Tabbable(root NodeID) ([]NodeID, error)

Tabbable lists the elements inside root that Tab reaches, in sequential focus order.

func (*Context) Unmount

func (c *Context) Unmount(comp Component) error

Unmount unmounts a component: its timers stop, OnDisposed runs (parents before children), its children are disposed and the nodes it adopted are removed. Unmounting a component that is not mounted does nothing.

func (*Context) ViewportSize

func (c *Context) ViewportSize() (changeset.Size, error)

ViewportSize returns innerWidth and innerHeight.

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.

func (*ElementRef) Unbind

func (r *ElementRef) Unbind()

Unbind clears the reference.

type Event

type Event = changeset.Event

Event is a DOM event reported by the sink. It is changeset.Event.

type HTMLRenderer

type HTMLRenderer interface {
	RenderHTML(w io.Writer) error
}

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 &nbsp;.

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.

func (Listener) Remove

func (l Listener) Remove()

Remove detaches the handler. The sink is told when it was the last one for its node and type. A handler whose node was removed is already gone; this does nothing for it.

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 NewLoop

func NewLoop() *Loop

NewLoop returns a loop; call Run to start it.

func (*Loop) Post

func (l *Loop) Post(fn func()) bool

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

func (l *Loop) Run(ctx context.Context) error

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.

func (*Loop) Schedule

func (l *Loop) Schedule(delay time.Duration, fn func()) *Timer

Schedule implements Scheduler with real time. The callback runs on the loop's goroutine; the returned timer's Stop reports whether it prevented that.

func (*Loop) Stop

func (l *Loop) Stop()

Stop makes Run return after the functions already queued have run. Posts after Stop are refused. It is the way to end the loop from inside a posted function; from outside, cancel the context passed to Run.

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.

func (*ManualScheduler) Schedule

func (m *ManualScheduler) Schedule(delay time.Duration, fn func()) *Timer

Schedule implements Scheduler.

type Mounter

type Mounter interface{ OnMounted() }

Mounter is implemented by components that want a callback after the commit that mounted them.

type NodeID

type NodeID = changeset.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

func WithErrorHandler(f func(error)) Option

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

func WithQueries(q changeset.Queries) Option

WithQueries sets where layout and focus queries are answered. By default they go to the sink, when it implements changeset.Queries.

func WithScheduler

func WithScheduler(s Scheduler) Option

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]) Clear

func (r *Rows[K, R]) Clear()

Clear removes every row.

func (*Rows[K, R]) Len

func (r *Rows[K, R]) Len() int

Len returns the number of rows.

func (*Rows[K, R]) Row

func (r *Rows[K, R]) Row(i int) R

Row returns the row at position i.

func (*Rows[K, R]) Sync

func (r *Rows[K, R]) Sync(keys []K) error

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

type Scheduler interface {
	Schedule(delay time.Duration, fn func()) *Timer
}

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

type SourceLocation struct {
	File string
	Line int
	Col  int
}

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.

func NewTimer

func NewTimer(stop func() bool) *Timer

NewTimer returns a timer for a Scheduler to hand back: stop cancels the callback and reports whether it was still pending.

func (*Timer) Stop

func (t *Timer) Stop() bool

Stop cancels the timer and reports whether this call stopped it: false when it already fired (a timeout) or was already stopped. It is safe to call more than once and from inside the timer's own callback; a nil Timer reports false.

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.
rt
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.
ui
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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL