changeset

package
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: 8 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.

Documentation

Overview

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.

A ChangeSet is applied atomically and in order. Node ids are allocated by the producer, start at 2 and are never reused; Root (1) is the container the sink owns. A node is created detached before anything mentions it, and an Insert of a subtree always comes after the creation of every node in it.

Two encodings are provided: JSON (the shape bridges to other languages use, see ChangeSet.MarshalJSON) and a compact binary form (ChangeSet.AppendBinary, DecodeBinary). Both decoders treat their input as untrusted: sizes, counts and string lengths are bounded by Limits and a malformed input is an error wrapping ErrMalformed, never a panic.

Concurrency

The encoders and decoders keep no state and may be used from many goroutines at once. A ChangeSet is a plain value: share it read-only or copy it. A Sink is single-goroutine unless its documentation says otherwise.

Writing a change set by hand

Build the changes with the New constructors, one per kind:

cs := changeset.ChangeSet{Version: changeset.Version, Sequence: 1, Changes: []changeset.Change{
	changeset.NewCreateElement(2, "p"),
	changeset.NewSetText(3, "hi"),
}}

Index

Examples

Constants

View Source
const HTMLNamespace = "http://www.w3.org/1999/xhtml"

HTMLNamespace is the namespace of elements made by CreateElement.

View Source
const SVGNamespace = "http://www.w3.org/2000/svg"

SVGNamespace is the namespace URI CreateElementNS carries for elements inside an <svg> template.

View Source
const Version = 3

Version is the protocol version this package produces and the highest it accepts. Version 2 added CreateElementNS and Focus; version 3 added the scroll kinds. Every earlier kind keeps its meaning and encoding, so a sink that implements version 3 also accepts versions 1 and 2.

Variables

View Source
var (
	// ErrChangeSet is wrapped by every error a sink reports for a change
	// set it cannot apply (see [Sink]).
	ErrChangeSet = errors.New("changeset: invalid change set")
	// ErrMalformed is wrapped by every decode error: the bytes are not an
	// encoded change set, or exceed the decoder's [Limits].
	ErrMalformed = errors.New("changeset: malformed input")
)

Errors.

View Source
var DefaultLimits = Limits{MaxBytes: 64 << 20, MaxChanges: 1_000_000, MaxString: 16 << 20}

DefaultLimits are used when a decoder gets the zero Limits: 64 MiB per set, 1,000,000 changes, 16 MiB per string.

Functions

func BubblesNot

func BubblesNot(typ string) bool

BubblesNot reports whether DOM event type typ is one that does not bubble (focus, blur and invalid).

Types

type Change

type Change struct {
	Kind   Kind
	Node   NodeID
	Other  NodeID // Insert and Move: the child. Scroll kinds: the [ScrollBehavior].
	Before NodeID
	Name   string
	Value  string
}

Change is one mutation. Which fields are meaningful depends on Kind (see the constants). Fields a kind does not use are ignored by the encoders.

func NewAddClass

func NewAddClass(node NodeID, class string) Change

NewAddClass returns an AddClass change.

func NewAddListener

func NewAddListener(node NodeID, typ string) Change

NewAddListener returns an AddListener change for events of DOM type typ.

func NewAddStyleSheet

func NewAddStyleSheet(key, css string) Change

NewAddStyleSheet returns an AddStyleSheet change: css is added once per key.

func NewCreateElement

func NewCreateElement(node NodeID, tag string) Change

NewCreateElement returns a CreateElement change: node is the new id and tag the lower-case tag.

func NewCreateElementNS

func NewCreateElementNS(node NodeID, ns, name string) Change

NewCreateElementNS returns a CreateElementNS change: an element in namespace ns with the local name name, case kept.

func NewCreateText

func NewCreateText(node NodeID, data string) Change

NewCreateText returns a CreateText change.

func NewFocus

func NewFocus(node NodeID) Change

NewFocus returns a Focus change.

func NewInsert

func NewInsert(parent, child, before NodeID) Change

NewInsert returns an Insert change: child goes into parent before the sibling before, or at the end when before is 0.

func NewMove

func NewMove(parent, child, before NodeID) Change

NewMove returns a Move change, with the arguments of NewInsert.

func NewRemove

func NewRemove(node NodeID) Change

NewRemove returns a Remove change.

func NewRemoveAttribute

func NewRemoveAttribute(node NodeID, name string) Change

NewRemoveAttribute returns a RemoveAttribute change.

func NewRemoveClass

func NewRemoveClass(node NodeID, class string) Change

NewRemoveClass returns a RemoveClass change.

func NewRemoveListener

func NewRemoveListener(node NodeID, typ string) Change

NewRemoveListener returns a RemoveListener change.

func NewRemoveStyle

func NewRemoveStyle(node NodeID, property string) Change

NewRemoveStyle returns a RemoveStyle change.

func NewScrollBy

func NewScrollBy(node NodeID, dx, dy string, b ScrollBehavior) Change

NewScrollBy returns a ScrollBy change; an empty offset is 0.

func NewScrollIntoView

func NewScrollIntoView(node NodeID, block, inline string, b ScrollBehavior) Change

NewScrollIntoView returns a ScrollIntoView change: block and inline are CSSOM View alignments ("start", "center", "end" or "nearest").

func NewScrollTo

func NewScrollTo(node NodeID, left, top string, b ScrollBehavior) Change

NewScrollTo returns a ScrollTo change. left and top are CSS px as decimal text; an empty one leaves that axis where it is.

func NewSetAttribute

func NewSetAttribute(node NodeID, name, value string) Change

NewSetAttribute returns a SetAttribute change.

func NewSetProperty

func NewSetProperty(node NodeID, name, value string) Change

NewSetProperty returns a SetProperty change.

func NewSetStyle

func NewSetStyle(node NodeID, property, value string) Change

NewSetStyle returns a SetStyle change.

func NewSetText

func NewSetText(node NodeID, data string) Change

NewSetText returns a SetText change.

func (Change) AppendJSON

func (c Change) AppendJSON(dst []byte) []byte

AppendJSON appends the JSON object for c (see ChangeSet.AppendJSON).

func (Change) Behavior

func (c Change) Behavior() ScrollBehavior

Behavior returns Other as a typed scroll behavior, for the scroll kinds. The constructors NewScrollIntoView, NewScrollTo and NewScrollBy set it from a ScrollBehavior; Other holds it because the wire form has no extra field.

type ChangeSet

type ChangeSet struct {
	Version  int    // protocol version of the set, 1 to [Version]
	Sequence uint64 // 1, 2, 3, ... per producer
	Changes  []Change
}

ChangeSet is the changes of one batch. A sink applies the set atomically.

func DecodeBinary

func DecodeBinary(data []byte, lim Limits) (ChangeSet, error)

DecodeBinary decodes the encoding of ChangeSet.AppendBinary. The whole input must be consumed. Strings are copied, so data may be reused. Errors are *DecodeError and wrap ErrMalformed.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/oneui/changeset"
)

func main() {
	cs := changeset.ChangeSet{Version: changeset.Version, Sequence: 7, Changes: []changeset.Change{
		changeset.NewCreateText(2, "hi"),
	}}
	wire := cs.AppendBinary(nil)
	// Input from outside is bounded: the zero Limits means the defaults, and
	// a tighter bound is one field away.
	got, err := changeset.DecodeBinary(wire, changeset.Limits{MaxChanges: 100})
	fmt.Println(got.Sequence, got.Changes[0].Value, err)
	_, err = changeset.DecodeBinary(wire[:3], changeset.Limits{})
	fmt.Println(err != nil)
}
Output:
7 hi <nil>
true

func DecodeJSON

func DecodeJSON(data []byte, lim Limits) (ChangeSet, error)

DecodeJSON decodes the JSON encoding of a change set. The input must be one JSON object with only the documented fields; kinds must be known and available in the set's version. Limits bound size, count and string length. Errors wrap ErrMalformed.

func (ChangeSet) AppendBinary

func (cs ChangeSet) AppendBinary(dst []byte) []byte

AppendBinary appends the compact binary encoding of cs to dst: uvarint version, sequence and change count, then per change one kind byte followed by the fields the kind uses (uvarint ids; strings as uvarint length and bytes). The output is deterministic.

func (ChangeSet) AppendJSON

func (cs ChangeSet) AppendJSON(dst []byte) []byte

AppendJSON appends the JSON encoding of cs to dst:

{"version":3,"sequence":1,"changes":[{"kind":"SetText","node":4,"value":"hi"}]}

Zero ids are omitted. Name and Value are written when the kind uses them (so SetText with an empty Value writes "value":""), and for the scroll kinds only when non-empty. The output is deterministic.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/oneui/changeset"
)

func main() {
	cs := changeset.ChangeSet{Version: changeset.Version, Sequence: 1, Changes: []changeset.Change{
		changeset.NewCreateElement(2, "p"),
		changeset.NewSetAttribute(2, "class", "note"),
		changeset.NewInsert(changeset.Root, 2, changeset.NodeID(0)),
	}}
	fmt.Println(string(cs.AppendJSON(nil)))
}
Output:
{"version":3,"sequence":1,"changes":[{"kind":"CreateElement","node":2,"name":"p"},{"kind":"SetAttribute","node":2,"name":"class","value":"note"},{"kind":"Insert","node":1,"other":2}]}

func (ChangeSet) MarshalJSON

func (cs ChangeSet) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler with ChangeSet.AppendJSON.

func (*ChangeSet) UnmarshalJSON

func (cs *ChangeSet) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler with the default Limits.

type DecodeError

type DecodeError struct {
	Offset int // byte offset of the problem, or -1 when unknown
	Msg    string
}

DecodeError describes malformed encoded input. It wraps ErrMalformed.

func (*DecodeError) Error

func (e *DecodeError) Error() string

Error implements error.

func (*DecodeError) Unwrap

func (e *DecodeError) Unwrap() error

Unwrap returns ErrMalformed.

type Dispatcher

type Dispatcher interface {
	Dispatch(node NodeID, ev *Event)
}

Dispatcher receives events from a sink. The producer's context implements it. A sink calls Dispatch once for each node on an event's path that has a listener of that type (target first, then ancestors for bubbling events) and stops when the event's propagation is stopped.

type Error

type Error struct {
	Sequence uint64 // sequence of the set
	Index    int    // index of the offending change, or -1 for the set itself
	Kind     Kind   // kind of the offending change
	Msg      string
}

Error is a protocol violation found while applying or checking a set.

func (*Error) Error

func (e *Error) Error() string

Error implements error.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns ErrChangeSet.

type Event

type Event struct {
	Type          string
	Target        NodeID // the node the event was raised at
	CurrentTarget NodeID // the node whose listener is running
	RelatedTarget NodeID
	ClientX       float64
	ClientY       float64
	Button        int
	Buttons       int
	DeltaX        float64 // wheel events: horizontal scroll delta, CSS px
	DeltaY        float64 // wheel events: vertical scroll delta, CSS px
	Key           string  // KeyboardEvent.key, e.g. "Enter", " ", "a"
	Code          string  // KeyboardEvent.code
	Repeat        bool
	Modifiers     Modifiers
	Value         string // the control's value after an input or change
	Checked       bool
	// contains filtered or unexported fields
}

Event is a DOM event reported by a sink. One struct carries every payload; a field irrelevant to the event's Type is zero. Handlers receive a pointer and may call Event.StopPropagation and Event.PreventDefault.

The payload by type: mouse events (click, mousedown, mouseup, mousemove, dblclick, contextmenu) use ClientX, ClientY, Button, Buttons, and wheel events DeltaX and DeltaY; keyboard events (keydown, keyup) use Key, Code, Repeat; input and change use Value and Checked; focus, blur, focusin and focusout use RelatedTarget. Modifiers applies to mouse and keyboard events.

func (*Event) Bubbles

func (e *Event) Bubbles() bool

Bubbles reports whether events of this type bubble, per the UI Events specification: focus, blur and invalid do not; focusin, focusout and everything else this protocol carries do.

func (*Event) DefaultPrevented

func (e *Event) DefaultPrevented() bool

DefaultPrevented reports whether PreventDefault was called.

func (*Event) PreventDefault

func (e *Event) PreventDefault()

PreventDefault cancels the browser or document default action of the event (a click's toggle, Enter activating a button, Tab moving focus).

func (*Event) PropagationStopped

func (e *Event) PropagationStopped() bool

PropagationStopped reports whether StopPropagation was called.

func (*Event) StopPropagation

func (e *Event) StopPropagation()

StopPropagation stops the event from reaching listeners on nodes further up its path. Listeners on the current node still run.

type Kind

type Kind uint8

Kind is the type of one Change. The numeric values are part of the binary encoding and never change.

const (
	// CreateElement: Node is the new id, Name the lower-case tag.
	CreateElement Kind = iota
	// CreateText: Node is the new id, Value the data.
	CreateText
	// Insert: Node is the parent, Other the detached child, Before a
	// sibling or 0 to append.
	Insert
	// Move is Insert for a node already in the tree; identity and
	// listeners are kept.
	Move
	// Remove destroys Node's subtree and its listeners.
	Remove
	// SetAttribute sets Name to Value on Node. Name "class" replaces the
	// whole class list.
	SetAttribute
	// RemoveAttribute removes Name from Node.
	RemoveAttribute
	// SetText sets the data of text node Node to Value.
	SetText
	// AddClass adds class Name to Node.
	AddClass
	// RemoveClass removes class Name from Node.
	RemoveClass
	// SetStyle sets inline style property Name (or a --custom property) to
	// Value.
	SetStyle
	// RemoveStyle removes inline style property Name.
	RemoveStyle
	// SetProperty sets the DOM property Name ("value", "checked") to Value
	// as text; "checked" uses "true" and "false".
	SetProperty
	// AddListener asks the sink to report events of DOM type Name on Node.
	AddListener
	// RemoveListener stops reports of events of type Name on Node.
	RemoveListener
	// AddStyleSheet adds the style sheet keyed Name once; Value is the CSS
	// text for the whole document.
	AddStyleSheet
	// CreateElementNS (version 2) creates a detached element in namespace
	// Value with local name Name, case kept.
	CreateElementNS
	// Focus (version 2) focuses Node once the whole set has been applied.
	Focus
	// ScrollIntoView (version 3): Node is the element, Name the block
	// alignment, Value the inline alignment, Other the [ScrollBehavior].
	ScrollIntoView
	// ScrollTo (version 3): Node is the scroll container, Name the left and
	// Value the top position in CSS px as decimal text; an empty one leaves
	// that axis where it is. Other is the [ScrollBehavior].
	ScrollTo
	// ScrollBy (version 3): like ScrollTo with offsets; an empty one is 0.
	ScrollBy
)

The change kinds. The comment on each names the fields it uses; a field a kind does not use is zero or empty.

func ParseKind

func ParseKind(s string) (Kind, bool)

ParseKind is the inverse of Kind.String.

func (Kind) MinVersion

func (k Kind) MinVersion() int

MinVersion is the protocol version that introduced the kind.

func (Kind) String

func (k Kind) String() string

String returns the kind's name as used in the JSON encoding, for example "SetAttribute".

func (Kind) Valid

func (k Kind) Valid() bool

Valid reports whether k is a kind of protocol version 3.

type Limits

type Limits struct {
	MaxBytes   int // encoded size of one set
	MaxChanges int // changes per set
	MaxString  int // bytes of one Name or Value
}

Limits bound what a decoder accepts. The zero value means DefaultLimits.

type Modifiers

type Modifiers uint8

Modifiers is a bit set of the keyboard modifiers held during an event.

const (
	ModShift Modifiers = 1 << iota
	ModControl
	ModAlt
	ModMeta
)

The modifier bits.

type NodeID

type NodeID uint32

NodeID names a node of the document. Zero means "none".

const FirstID NodeID = 2

FirstID is the first id a producer allocates, 2: 0 means "none" and 1 is Root, which the sink owns.

const Root NodeID = 1

Root is the id of the container the sink owns. Top-level components are inserted into it.

type Queries

type Queries interface {
	// BoundingClientRect is the border box of n in viewport coordinates;
	// ok is false for an element with no box (unknown, detached,
	// display: none).
	BoundingClientRect(n NodeID) (r Rect, ok bool)
	// ViewportSize is innerWidth and innerHeight.
	ViewportSize() Size
	// ScrollMetrics reports n's metrics; ok is false when it has none.
	ScrollMetrics(n NodeID) (m ScrollMetrics, ok bool)
	// TabbableNodes lists the elements inside root that Tab reaches, in
	// sequential focus order: positive tabindex ascending, then tree order.
	TabbableNodes(root NodeID) []NodeID
	// ActiveElement is document.activeElement, or 0 for none.
	ActiveElement() NodeID
	// Contains is Node.contains: ancestor contains n, inclusive.
	Contains(ancestor, n NodeID) bool
	// IsInert reports whether n or an ancestor has the inert attribute.
	IsInert(n NodeID) bool
}

Queries is the optional interface of a sink that can answer questions about the document it holds, as of the last applied set, laying out first when stale. An unknown node gets the "none" answer, never an error. None of it travels through the change-set protocol.

type Rect

type Rect struct{ X, Y, W, H float64 }

Rect is a box in CSS pixels, viewport coordinates (CSSOM View's DOMRect).

func (Rect) Bottom

func (r Rect) Bottom() float64

Bottom returns the y of the bottom edge.

func (Rect) Left

func (r Rect) Left() float64

Left returns the x of the left edge.

func (Rect) Right

func (r Rect) Right() float64

Right returns the x of the right edge.

func (Rect) Top

func (r Rect) Top() float64

Top returns the y of the top edge.

type ScrollBehavior

type ScrollBehavior uint8

ScrollBehavior is the value of Change.Other for the scroll kinds.

const (
	// BehaviorAuto follows the container's CSS scroll-behavior.
	BehaviorAuto ScrollBehavior = iota
	// BehaviorInstant jumps.
	BehaviorInstant
	// BehaviorSmooth animates where the sink can and jumps where it cannot.
	BehaviorSmooth
)

The scroll behaviors of CSSOM View's ScrollBehavior.

type ScrollMetrics

type ScrollMetrics struct {
	ScrollLeft, ScrollTop     float64
	ScrollWidth, ScrollHeight float64
	ClientWidth, ClientHeight float64
}

ScrollMetrics are an element's scroll offsets and extents (CSSOM View).

type Sink

type Sink interface {
	Apply(cs ChangeSet) error
}

Sink is a document that applies change sets. Apply must not retain the Changes slice after it returns: the producer reuses it.

A sink returns an error wrapping ErrChangeSet for a change naming a missing node, a cycle, an element where text is expected and the like. Events a sink raises while applying (focus changes, for instance) must be delivered after Apply has returned, never from inside it: a sink is not re-entered.

type Size

type Size struct{ W, H float64 }

Size is a width and height in CSS pixels.

Jump to

Keyboard shortcuts

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