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 ¶
- Constants
- Variables
- func BubblesNot(typ string) bool
- type Change
- func NewAddClass(node NodeID, class string) Change
- func NewAddListener(node NodeID, typ string) Change
- func NewAddStyleSheet(key, css string) Change
- func NewCreateElement(node NodeID, tag string) Change
- func NewCreateElementNS(node NodeID, ns, name string) Change
- func NewCreateText(node NodeID, data string) Change
- func NewFocus(node NodeID) Change
- func NewInsert(parent, child, before NodeID) Change
- func NewMove(parent, child, before NodeID) Change
- func NewRemove(node NodeID) Change
- func NewRemoveAttribute(node NodeID, name string) Change
- func NewRemoveClass(node NodeID, class string) Change
- func NewRemoveListener(node NodeID, typ string) Change
- func NewRemoveStyle(node NodeID, property string) Change
- func NewScrollBy(node NodeID, dx, dy string, b ScrollBehavior) Change
- func NewScrollIntoView(node NodeID, block, inline string, b ScrollBehavior) Change
- func NewScrollTo(node NodeID, left, top string, b ScrollBehavior) Change
- func NewSetAttribute(node NodeID, name, value string) Change
- func NewSetProperty(node NodeID, name, value string) Change
- func NewSetStyle(node NodeID, property, value string) Change
- func NewSetText(node NodeID, data string) Change
- type ChangeSet
- type DecodeError
- type Dispatcher
- type Error
- type Event
- type Kind
- type Limits
- type Modifiers
- type NodeID
- type Queries
- type Rect
- type ScrollBehavior
- type ScrollMetrics
- type Sink
- type Size
Examples ¶
Constants ¶
const HTMLNamespace = "http://www.w3.org/1999/xhtml"
HTMLNamespace is the namespace of elements made by CreateElement.
const SVGNamespace = "http://www.w3.org/2000/svg"
SVGNamespace is the namespace URI CreateElementNS carries for elements inside an <svg> template.
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 ¶
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.
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 ¶
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 ¶
NewAddClass returns an AddClass change.
func NewAddListener ¶
NewAddListener returns an AddListener change for events of DOM type typ.
func NewAddStyleSheet ¶
NewAddStyleSheet returns an AddStyleSheet change: css is added once per key.
func NewCreateElement ¶
NewCreateElement returns a CreateElement change: node is the new id and tag the lower-case tag.
func NewCreateElementNS ¶
NewCreateElementNS returns a CreateElementNS change: an element in namespace ns with the local name name, case kept.
func NewCreateText ¶
NewCreateText returns a CreateText change.
func NewInsert ¶
NewInsert returns an Insert change: child goes into parent before the sibling before, or at the end when before is 0.
func NewRemoveAttribute ¶
NewRemoveAttribute returns a RemoveAttribute change.
func NewRemoveClass ¶
NewRemoveClass returns a RemoveClass change.
func NewRemoveListener ¶
NewRemoveListener returns a RemoveListener change.
func NewRemoveStyle ¶
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 ¶
NewSetAttribute returns a SetAttribute change.
func NewSetProperty ¶
NewSetProperty returns a SetProperty change.
func NewSetStyle ¶
NewSetStyle returns a SetStyle change.
func NewSetText ¶
NewSetText returns a SetText change.
func (Change) AppendJSON ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
MarshalJSON implements json.Marshaler with ChangeSet.AppendJSON.
type DecodeError ¶
DecodeError describes malformed encoded input. It wraps ErrMalformed.
type Dispatcher ¶
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.
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 ¶
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 ¶
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 ¶
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 (Kind) MinVersion ¶
MinVersion is the protocol version that introduced the kind.
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.
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).
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 ¶
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.