types

package
v1.54.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 18 Imported by: 0 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 types holds the user-facing shared CRDT collection types: Map, Array, Text, XmlElement / XmlFragment / XmlText.

Each type is a thin wrapper around a *block.Branch — the branch owns the actual CRDT state (linked list of Items + map of map-key tails); the type wrapper exposes idiomatic Go APIs that hide the block-layer mechanics.

Construction pattern: a Doc registers root branches by name via Doc.Branch(name); the types-layer constructor (NewMap, NewArray, NewText) wraps the returned branch.

Mutating methods take a *doc.TransactionMut. Read methods do not require a transaction parameter for ergonomic reasons but the caller is responsible for holding at least a read lock on the Doc (typically via a ReadTxn).

See docs/yrs-port-notes/types-map.md for the per-method contract of the Map type, and DESIGN.md for the API style decisions.

Index

Constants

This section is empty.

Variables

View Source
var ErrDetachedType = errors.New("ygo: relative position: type is not anchored in a document")

ErrDetachedType reports a wrapper whose branch is neither a root type nor attached to a live item, so no stable anchor exists for it.

View Source
var ErrEmptyAnchor = errors.New("ygo: relative position: empty anchor")

ErrEmptyAnchor reports a RelativePosition with no anchor set (none of Item, TName, Type). Such a value cannot come from Create or Decode; it indicates a caller-constructed zero value.

View Source
var ErrUndefinedEmbed = errors.New("ygo: text: an embed cannot be undefined")

ErrUndefinedEmbed is returned for an embed that is undefined itself. yjs throws on insertEmbed(undefined), after the format markers for the attributes went in; ygo refuses it before changing anything. An undefined embed a peer sent stays in the document.

Functions

func EncodeRelativePosition added in v1.1.0

func EncodeRelativePosition(rpos RelativePosition) ([]byte, error)

EncodeRelativePosition serialises rpos to the binary form of Y.encodeRelativePosition: a varuint tag (0 item / 1 tname / 2 type), the payload, then assoc as a signed varint. Returns ErrEmptyAnchor for a zero-value rpos (yjs throws unexpectedCase here).

Types

type AbsolutePosition added in v1.1.0

type AbsolutePosition struct {
	Branch *block.Branch
	Index  uint64
	Assoc  int64
}

AbsolutePosition is a resolved RelativePosition: the branch of the shared type the position lives in and the current numeric index within it (UTF-16 code units for Text, elements for Array).

func CreateAbsolutePositionFromRelativePosition added in v1.1.0

func CreateAbsolutePositionFromRelativePosition(d *doc.Doc, rpos RelativePosition) (AbsolutePosition, bool)

CreateAbsolutePositionFromRelativePosition resolves rpos against the current state of d. Returns ok=false when the anchor refers to state this replica has not seen, or to a garbage-collected range.

Follows undone deletions (the yjs default): an anchor on a character that was deleted and restored by undo resolves to the restored copy.

Mirrors yjs createAbsolutePositionFromRelativePosition.

type Array

type Array struct {
	// contains filtered or unexported fields
}

Array is the user-facing wrapper around a positional Branch. The branch's Start linked list holds the document-order sequence; we count live (non-deleted, countable) items to translate user-facing positions to *Item references.

Construct via NewArray; usually obtained as types.NewArray(d.Branch("name")).

Array shares its underlying Branch with Map's possible usage of the same name — Map uses Branch.Map (string-keyed), Array uses Branch.Start (positional). The two surfaces operate on disjoint fields of the same Branch and may technically coexist, though in practice each root branch is used as one type.

func NewArray

func NewArray(branch *block.Branch) *Array

NewArray wraps the given branch as an Array.

func (*Array) Branch

func (a *Array) Branch() *block.Branch

Branch returns the underlying *block.Branch for low-level access.

func (*Array) Delete

func (a *Array) Delete(txn *doc.TransactionMut, idx, length uint64)

Delete removes length elements starting at idx. Items that straddle the [idx, idx+length) range are split via SplitBlock so the deletion lands on Item boundaries.

length == 0 is a no-op. Out-of-range deletions clip to Len().

func (*Array) Get

func (a *Array) Get(idx uint64) any

Get returns the value at idx, or nil if idx is out of range or the underlying content kind is not unpacked by extractValueAt.

O(N) over the linked list. Search markers help only when callers alternate Get with Insert/Delete near the same area; pure Get loops still walk from start (no marker write occurs here).

func (*Array) Insert

func (a *Array) Insert(txn *doc.TransactionMut, idx uint64, value any)

Insert inserts a single value at idx. Convenience for InsertRange with a one-element slice.

idx should be in [0, Len]. A larger idx appends the value after the last item of the list, deleted or not, as Push does; yjs throws instead.

func (*Array) InsertArray

func (a *Array) InsertArray(txn *doc.TransactionMut, idx uint64) *Array

InsertArray inserts a freshly-constructed nested Array at idx.

func (*Array) InsertMap

func (a *Array) InsertMap(txn *doc.TransactionMut, idx uint64) *Map

InsertMap inserts a freshly-constructed nested Map at idx and returns the wrapper. Per docs/yrs-port-notes/nested-types.md §6.

Like InsertRange, an idx past Len appends; the new Map element occupies one slot (Len contribution = 1).

func (*Array) InsertRange

func (a *Array) InsertRange(txn *doc.TransactionMut, idx uint64, values []any)

InsertRange inserts every value at idx in order, packed into a single ContentAny Item with Len == len(values). Per types-array.md finding 3, this matches yrs's RangePrelim squash-on-insert.

Mid-block inserts trigger Store.SplitBlock to materialize a clean boundary at idx.

func (*Array) InsertText

func (a *Array) InsertText(txn *doc.TransactionMut, idx uint64) *Text

InsertText inserts a freshly-constructed nested Text at idx (plain-text only).

func (*Array) Len

func (a *Array) Len() uint64

Len returns the number of live elements. O(1) — reads branch.BlockLen, which Item.Integrate (+countable.Len) and TransactionMut.Delete (-countable.Len) maintain.

Per types-array.md finding 5: Map keys are excluded from BlockLen; the counter only tracks positional, countable, live items.

func (*Array) Observe added in v1.2.0

func (a *Array) Observe(fn func(*ArrayEvent)) func()

Observe registers fn to run after every transaction that changes this array, with an ArrayEvent carrying the change delta. Returns an unsubscribe function. Fires on local edits and remote updates.

Mirrors yjs yarray.observe. The callback runs while the doc write lock is held; it must not start a new transaction on the same doc, and must not edit through the transaction being committed: the commit's events are built when first given out, so a later one may show such an edit.

func (*Array) ObserveDeep added in v1.2.0

func (a *Array) ObserveDeep(fn func([]any)) func()

ObserveDeep registers fn to run after any transaction that changes this array OR any shared type nested under it, with the list of events (each carrying its Path relative to this array). Returns an unsubscribe function. Mirrors yjs yarray.observeDeep. The callback runs under the same rules as Observe.

func (*Array) Push

func (a *Array) Push(txn *doc.TransactionMut, values ...any)

Push appends one or more values to the end of the array: after the last item of the list, deleted or not, as yjs typeListPushGenerics does. InsertRange at Len() puts them right after the last live element instead, before any trailing tombstones, as yjs insert(length) does; the difference shows when a tombstone at the end comes back through undo or meets a concurrent insert.

func (*Array) Range

func (a *Array) Range(fn func(idx uint64, value any) bool)

Range visits live elements in document order. The callback returns false to stop early. For ContentAny items with Len > 1 (squashed runs from InsertRange / Push) each element is yielded individually.

func (*Array) ToSlice

func (a *Array) ToSlice() []any

ToSlice materializes the array into a fresh []any. Convenience for tests; production callers should prefer Range to avoid the allocation.

type ArrayDeltaOp added in v1.2.0

type ArrayDeltaOp struct {
	Insert []any
	Delete int
	Retain int
}

ArrayDeltaOp is one operation of an array change delta. Exactly one of the three is set: Insert (the inserted values), Delete (a count of removed elements), or Retain (a count of unchanged elements). The text DeltaOp (text_format.go) is the string-valued analogue for Text.

type ArrayEvent added in v1.2.0

type ArrayEvent struct {
	Target *Array
	// Path locates Target relative to the ObserveDeep type firing;
	// empty for shallow Observe.
	Path  []any
	Delta []ArrayDeltaOp
}

ArrayEvent is delivered to Array observers (Array.Observe) after a transaction that changed the array. Delta is the Quill-style change description. Mirrors yjs YArrayEvent.

type Attrs

type Attrs = map[string]any

Attrs is the format-attribute map carried by KindFormat markers and exposed in Range / ToDelta output. Per docs/yrs-port-notes/types-text-rich.md §9.

Nil values inside Attrs mean "clear this attribute" — they encode to the Any-Null tag on the wire and are interpreted by currentAttributes as removing the key. To distinguish "key not present" from "key present with nil value", check via the second return of a map lookup.

type BranchHolder added in v1.1.0

type BranchHolder interface {
	Branch() *block.Branch
}

BranchHolder is satisfied by every shared-type wrapper (Map, Array, Text, XmlFragment, XmlElement); it exposes the underlying Branch.

type ChunkKind

type ChunkKind uint8

ChunkKind discriminates the variants emitted by Text.Range.

const (
	// ChunkString is a contiguous run of UTF-8 text from a KindString
	// item; the value passed to fn is a string.
	ChunkString ChunkKind = iota
	// ChunkEmbed is a single embedded value from a KindEmbed item;
	// the value passed to fn is whatever the embed payload's runtime
	// type is (typically map[string]any or a primitive Any).
	ChunkEmbed
)

type DeltaOp

type DeltaOp struct {
	// Insert is the text to insert at the cursor. Mutually exclusive
	// with Embed, Retain, Delete.
	Insert string

	// Embed is a single embedded value (image, mention, etc.). Mutually
	// exclusive with Insert, Retain, Delete. The Embed value's runtime
	// type matches whatever Y.encodeStateAsUpdate-produced JS clients
	// would round-trip through Any — typically a map[string]any.
	Embed any

	// Retain advances the cursor by N UTF-16 units, optionally
	// applying Attributes to the retained range. Mutually exclusive
	// with Insert, Embed, Delete.
	Retain uint64

	// Delete removes N UTF-16 units from the cursor. Mutually exclusive
	// with Insert, Embed, Retain.
	Delete uint64

	// Attributes applies to Insert, Embed, or Retain. An Insert or
	// Embed carries exactly these attributes: one in effect at the
	// cursor that is absent here is cleared for the inserted content,
	// and nil means none. On a Retain, a nil-valued key clears that
	// attribute over the range and an absent key leaves it as it is.
	Attributes Attrs
}

DeltaOp is a single op from a Quill-style delta. Exactly one of Insert / Embed / Retain / Delete is set for any given op. Used by ToDelta to expose the doc and by ApplyDelta to ingest one.

type KeyChange added in v1.2.0

type KeyChange struct {
	// Action is "add", "update", or "delete".
	Action string
	// OldValue is the value the key held before this transaction; nil
	// for an "add".
	OldValue any
}

KeyChange describes one map key's change within a transaction: the kind of change and the value the key held before it. Mirrors yjs's YMapEvent change entry ({ action, oldValue }).

type Map

type Map struct {
	// contains filtered or unexported fields
}

Map is the user-facing wrapper around a map-like Branch. Construct via NewMap; usually obtained as types.NewMap(d.Branch("name")).

Map exposes Set / Get / Delete / Has / Len / Range / Clear plus a Branch accessor for low-level integration.

func NewMap

func NewMap(branch *block.Branch) *Map

NewMap wraps the given branch as a Map. The branch's Map field is initialized lazily if nil — typical for a freshly-created root branch from Doc.Branch(name).

func (*Map) Branch

func (m *Map) Branch() *block.Branch

Branch returns the underlying *block.Branch. Useful for cross-package wiring (e.g. observers, encoders) that need to operate at the block layer.

func (*Map) Clear

func (m *Map) Clear(txn *doc.TransactionMut)

Clear deletes every entry in the map, in the order the keys were first set, as yjs YMap.clear walks _map. The order is that of the transaction's deletions, which an UndoManager restores in.

func (*Map) Delete

func (m *Map) Delete(txn *doc.TransactionMut, key string)

Delete tombstones the entry under key. Calling Delete when the key is absent or already tombstoned is a no-op.

Per types-map.md finding 3: Delete does NOT clear branch.Map[key]. The map entry continues to point at the tombstoned item so a subsequent Set can chain off it as Origin/Left, preserving YATA convergence for concurrent writers that didn't see the delete yet.

func (*Map) Get

func (m *Map) Get(key string) any

Get returns the current value under key, or nil if the key is absent or its tail item is tombstoned.

Per types-map.md finding 5: this is one-step. branch.Map[key] is the LWW winner; if it's deleted there is no live predecessor to fall back to.

func (*Map) GetDoc added in v0.10.0

func (m *Map) GetDoc(d *doc.Doc, key string) (*doc.Doc, bool)

GetDoc returns the subdocument referenced under key within parent d, or (nil, false) if key holds no live subdoc. The returned handle is the registered instance for the referenced GUID (created on first access for subdocs surfaced from a decoded update).

func (*Map) Has

func (m *Map) Has(key string) bool

Has reports whether key has a live (non-tombstoned) entry.

func (*Map) Len

func (m *Map) Len() int

Len returns the number of live (non-tombstoned) entries.

O(N) over the map size: iterates and counts. yrs has a TODO at map.rs:158 about caching this on the Branch — we'd inherit that optimization for free if we add the cache to Branch. Tracked in tech-debt.md if it shows up in benchmarks.

func (*Map) Observe added in v1.2.0

func (m *Map) Observe(fn func(*MapEvent)) func()

Observe registers fn to run after every transaction that changes this map, with a MapEvent describing the changed keys. Returns an unsubscribe function. Observers fire on local edits and on remote updates applied via ApplyUpdate.

Mirrors yjs ymap.observe. The callback runs while the doc write lock is held; it must not start a new transaction on the same doc, and must not edit through the transaction being committed: the commit's events are built when first given out, so a later one may show such an edit.

func (*Map) ObserveDeep added in v1.2.0

func (m *Map) ObserveDeep(fn func([]any)) func()

ObserveDeep registers fn to run after any transaction that changes this map OR any shared type nested under it, with the list of events (each carrying its Path relative to this map). Returns an unsubscribe function. Mirrors yjs ymap.observeDeep. The callback runs under the same rules as Observe.

func (*Map) Range

func (m *Map) Range(fn func(key string, value any) bool)

Range iterates over live (key, value) pairs in unspecified order (Go map iteration). The callback returns false to stop early.

func (*Map) Set

func (m *Map) Set(txn *doc.TransactionMut, key string, value any)

Set stores value under key in this map. Concurrent writes from different replicas converge to the same final value — the writer with the higher (clientID, clock) wins per YATA.

value may be of any type; the encoding-layer port (deferred per tech-debt.md) will decide how each Go type maps to a wire variant. For now value is stored as ContentAny, which round-trips through reflection.

Mirrors yrs Map::insert (yrs/src/types/map.rs ~line 73).

func (*Map) SetArray

func (m *Map) SetArray(txn *doc.TransactionMut, key string) *Array

SetArray inserts a freshly-constructed nested Array under key.

func (*Map) SetDoc added in v0.10.0

func (m *Map) SetDoc(txn *doc.TransactionMut, key string) *doc.Doc

setNested is the shared scaffolding for SetMap/SetArray/SetText: build an Item with KindType content and the supplied Branch, chain off the existing tail at this key (Origin = left.LastID()), push to store, integrate. The Item.Integrate KindType arm wires SetDoc nests a new subdocument under key and returns its handle. The subdocument carries its own GUID; its content syncs as a separate update stream, while the parent stores only the reference (GUID + options). Mirrors yjs `map.set(key, new Y.Doc())`.

func (*Map) SetDocWithOptions added in v1.0.0

func (m *Map) SetDocWithOptions(txn *doc.TransactionMut, key string, autoLoad bool) *doc.Doc

SetDocWithOptions is SetDoc with subdocument options. When autoLoad is true the reference carries the autoLoad flag on the wire, so peers that decode it mark the subdocument to load automatically (it appears in their SubdocsLoaded set).

func (*Map) SetMap

func (m *Map) SetMap(txn *doc.TransactionMut, key string) *Map

SetMap inserts a freshly-constructed nested Map under key and returns the wrapper bound to it. Subsequent edits via the returned *Map are addressed to this map-key slot in m; concurrent peers see the same nested-map structure once they apply the resulting updates.

Per docs/yrs-port-notes/nested-types.md §5 — recommended API over overloading Set(any) so the caller never has to type-assert the returned wrapper.

func (*Map) SetText

func (m *Map) SetText(txn *doc.TransactionMut, key string) *Text

SetText inserts a freshly-constructed nested Text under key (plain-text only — see tech-debt.md for rich-text formatting).

type MapEvent added in v1.2.0

type MapEvent struct {
	// Target is the map that changed.
	Target *Map
	// Path is the location of Target relative to the type whose
	// ObserveDeep callback is firing; empty for a shallow Observe and
	// for a deep observer on Target itself.
	Path []any
	// Keys maps each changed key to how it changed. Only keys whose
	// observable value actually changed appear (a key added and
	// removed in the same transaction is omitted, matching yjs).
	Keys map[string]KeyChange
}

MapEvent is delivered to Map observers after a transaction that changed the map. Mirrors yjs YMapEvent.

func (*MapEvent) KeysChanged added in v1.2.0

func (e *MapEvent) KeysChanged() []string

KeysChanged returns the set of keys that changed, for callers that only need the names.

type RelativePosition added in v1.1.0

type RelativePosition struct {
	Type  *block.ID
	TName *string
	Item  *block.ID
	Assoc int64
}

RelativePosition is a position anchored to the Yjs document model rather than to a numeric index, so it stays attached to the same logical character as concurrent edits land before or after it. The canonical use is collaborative cursors and selections.

Exactly one of Item, TName, Type identifies the anchor:

  • Item: the position sits on a concrete character, identified by the ID of the item (plus offset baked into the clock).
  • TName: the position sits at the end of a ROOT type with this name.
  • Type: the position sits at the end of a NESTED type, identified by the ID of the item whose content holds the type.

Assoc is the side the position sticks to: >= 0 associates with the character after the position (default), < 0 with the character before it.

Mirrors yjs RelativePosition (utils/RelativePosition.js); the binary form produced by Encode is byte-compatible with Y.encodeRelativePosition.

TName is a pointer because the empty string is a legal root-type name in yjs (doc.get(”)); nil means "not a root anchor".

func CreateRelativePositionFromTypeIndex added in v1.1.0

func CreateRelativePositionFromTypeIndex(t BranchHolder, index uint64, assoc int64) (RelativePosition, error)

CreateRelativePositionFromTypeIndex anchors the numeric position index within the shared type t as a RelativePosition. index counts UTF-16 code units for Text and elements for Array. assoc chooses the side the position sticks to (>= 0 right, < 0 left).

Mirrors yjs createRelativePositionFromTypeIndex. The caller must not hold an open write transaction mutating t concurrently.

func DecodeRelativePosition added in v1.1.0

func DecodeRelativePosition(buf []byte) (RelativePosition, error)

DecodeRelativePosition parses the binary form produced by EncodeRelativePosition / Y.encodeRelativePosition. A missing assoc (older producers) decodes as 0, matching yjs.

type Text

type Text struct {
	// contains filtered or unexported fields
}

Text is the user-facing wrapper around a Branch holding plain text. The branch's positional linked list (branch.Start) holds ContentString items; per types-text.md their Item.Len is in UTF-16 code units (matching JS Yjs and the wire format).

Plain-text only in this commit. Rich-text formatting (Format markers, applyDelta, embeds, attributes) is tracked in docs/tech-debt.md.

All offsets and lengths in Insert / Delete are UTF-16 code units, not Go bytes and not runes. Use utf16.Length(string) to convert a Go string to its UTF-16 length when computing positions.

func NewText

func NewText(branch *block.Branch) *Text

NewText wraps the given branch as a Text. It tags the branch as a Text type (TypeRefText) so the observer dispatcher can tell a root Text from a root Array, whose branches both default to TypeRef zero otherwise. The root TypeRef is never serialized (roots are written by name), so this does not affect the wire format.

func (*Text) ApplyDelta

func (t *Text) ApplyDelta(txn *doc.TransactionMut, ops []DeltaOp) error

ApplyDelta applies a Quill-style delta, as yjs applyDelta does with its default options: one cursor starts at the beginning of the text and every op continues from where the previous one left it.

  • Insert (string) or Embed inserts at the cursor carrying exactly Attributes; nil Attributes means none, so inherited attributes are closed around the insert. A string Embed is inserted as text.
  • Retain N formats the next N units with Attributes (nil means none, which only moves the cursor). A retain that runs past the end of the text appends a newline for each missing unit, up to math.MaxInt32; a longer one fails before the op writes anything.
  • Delete N deletes the next N units, or as many as there are.

An op with every field zero is a no-op. yjs runs an explicit {retain: 0}, which can move the cursor across markers; a DeltaOp cannot say whether its Retain was given, so ygo cannot. Quill does not emit zero retains. yjs also writes the nulls of cleared attributes into the attributes object it is given, so a caller reusing one object across ops sees them in later ops; ygo never writes into Attributes.

All ops execute inside the supplied txn so the entire delta is atomic from peers' perspective. Errors abort mid-delta; the partial mutation persists (the doc layer's TransactionMut has no Rollback).

func (*Text) Branch

func (t *Text) Branch() *block.Branch

Branch returns the underlying *block.Branch for low-level access.

func (*Text) Delete

func (t *Text) Delete(txn *doc.TransactionMut, idx, length uint64) error

Delete removes length UTF-16 code units starting at idx. Items straddling the [idx, idx+length) range are split via Store.SplitBlock at UTF-16 boundaries so the deletion lands on Item edges.

Returns an error if the range exceeds the current Length.

After deleting, format markers left in the gap that no longer mark anything are removed, as yjs deleteText does with cleanupFormattingGap.

Mirrors yrs Text::remove_range (text.rs:361-368) → remove (text.rs:806-863).

func (*Text) Format

func (t *Text) Format(txn *doc.TransactionMut, idx, length uint64, attrs Attrs) error

Format applies attrs to the range [idx, idx+length). It is a port of yjs YText.format / formatText: the cursor stops at idx before any format markers there, markers that already set a requested value are stepped over, an opening marker is written for every attribute that changes, markers inside the range for a requested key are deleted (they would otherwise re-establish the old value mid-range), and markers after the range restore what was in effect there.

A nil value in attrs clears that attribute over the range. length == 0 and empty attrs are no-ops. A range past the end of the text is an error; yjs instead appends newlines for the missing length, a Quill convention this port does not follow.

func (*Text) Insert

func (t *Text) Insert(txn *doc.TransactionMut, idx uint64, str string) error

Insert inserts str at the UTF-16 code-unit position idx. idx must be in [0, Length()]. str may contain any Unicode characters; non-BMP chars (e.g. emoji) contribute 2 UTF-16 units each.

The text takes the formatting in effect at idx, as yjs insert(index, text) does: it goes in right after the content before idx, past tombstones and past markers that set a value already in effect, and before the first marker that changes one. So text typed at the end of a bold run is bold, and text typed at its start is not. In a root that received formatted text before it was first read as text, and into which no format item has integrated since, yjs starts from a search marker and takes only the formatting of the markers it passes from there, so the result depends on the edits before; ygo does the same (Branch.LateText).

Multiple consecutive Insert calls produce separate Items; commit-time TrySquash merges adjacent same-client adjacent-clock String items into one (yrs/src/block.rs:1987-1990).

Returns an error if idx is out of range.

func (*Text) InsertEmbed

func (t *Text) InsertEmbed(txn *doc.TransactionMut, idx uint64, value any) error

InsertEmbed inserts a single embedded value at idx with no attributes: as yjs insertEmbed(index, embed) does, the attributes in effect at idx are closed around it. It is InsertEmbedWithAttributes(txn, idx, value, nil).

func (*Text) InsertEmbedWithAttributes added in v1.25.0

func (t *Text) InsertEmbedWithAttributes(txn *doc.TransactionMut, idx uint64, value any, attrs Attrs) error

InsertEmbedWithAttributes inserts a single embedded value at idx carrying exactly attrs, as yjs insertEmbed(index, embed, attributes). nil attrs and an empty map both mean no attributes; in a root typed after formatted text arrived (see Insert) they differ as in yjs, where an embed without attributes starts from a search marker and one with {} from the start of the text. The value must be representable as a lib0 Any, typically a map[string]any or a scalar. A string value is inserted as text, as yjs does with a string embed; an empty string inserts nothing.

Embeds count as one UTF-16 position in Text.Length. They are emitted by Range / ToDelta as an Embed op rather than a string chunk.

func (*Text) InsertWithAttributes

func (t *Text) InsertWithAttributes(txn *doc.TransactionMut, idx uint64, str string, attrs Attrs) error

InsertWithAttributes inserts str at idx carrying exactly attrs, as yjs insert(index, text, attributes) does: an attribute in effect at idx that attrs does not name is cleared for the inserted text, an opening marker is written for each value that differs from the one in effect, and the values in effect are restored after the text.

nil attrs is Insert(idx, str): the text takes the formatting in effect at idx. A non-nil empty map is yjs's {}: the text is inserted with no attributes, every inherited one closed around it.

func (*Text) Length

func (t *Text) Length() uint64

Length returns the total number of UTF-16 code units in live content. O(1) — reads branch.BlockLen which Item.Integrate (+) and TransactionMut.Delete (-) maintain.

Per types-text.md §4: for our UTF-16-only port, BlockLen is already the count of UTF-16 units across live String items.

func (*Text) Observe added in v1.2.0

func (t *Text) Observe(fn func(*TextEvent)) func()

Observe registers fn to run after every transaction that changes this text, with a TextEvent carrying the formatting-aware change delta. Returns an unsubscribe function. Fires on local edits and remote updates.

Mirrors yjs ytext.observe. The callback runs while the doc write lock is held; it must not start a new transaction on the same doc, and must not edit through the transaction being committed: the commit's events are built when first given out, so a later one may show such an edit.

func (*Text) Range

func (t *Text) Range(fn func(kind ChunkKind, value any, attrs Attrs) bool)

Range walks the document and invokes fn for each (kind, value, attrs) chunk. attrs reflects the current formatting at this chunk's start.

Stops early when fn returns false. Returns immediately for an empty doc.

Per docs/yrs-port-notes/types-text-rich.md §8 — companion to ToDelta. Explicit ChunkKind discriminator means a string-typed embed payload is not misidentified as a text chunk by callers that switch on the runtime type of the value.

func (*Text) String

func (t *Text) String() string

String returns the concatenation of every live ContentString in document order as a Go UTF-8 string. O(N) over the linked list.

Mirrors yrs Text::get_string (text.rs:120-132).

func (*Text) ToDelta

func (t *Text) ToDelta() []DeltaOp

ToDelta returns the Quill-style delta representation of the doc. Consecutive strings are joined into one insert op up to the next live format marker or embed. As in yjs toDelta, every live format marker ends the op, even one that changes no attribute, so two adjacent ops can carry equal attributes, and an attribute named "ychange", which yjs reserves for snapshot diffs, is dropped at the next string. Embeds appear as separate ops.

The returned slice has no Retain / Delete ops — those exist only in deltas representing CHANGES, not snapshots.

type TextEvent added in v1.2.0

type TextEvent struct {
	Target *Text
	// Path locates Target relative to the ObserveDeep type firing;
	// empty for shallow Observe.
	Path  []any
	Delta []DeltaOp
	// Keys maps each attribute of the text changed by the transaction
	// (yjs YText.setAttribute, an XmlText's attributes) to how it changed,
	// as MapEvent.Keys does; nil when none changed.
	Keys map[string]KeyChange
	// contains filtered or unexported fields
}

TextEvent is delivered to Text observers (Text.Observe) after a transaction that changed the text. Delta is the Quill-style, formatting-aware change description (the same DeltaOp shape ToDelta produces). Mirrors yjs YTextEvent.

Delta is computed when the event is first given out and changes nothing. yjs's event.delta getter also deletes the format markers it finds redundant (one added equal to the attribute in effect, or an older one equal to the attribute an added one sets), in a transaction of its own; ReadDelta is that getter. A receiver that never reads event.delta in yjs ends as one that reads only Delta here.

func (*TextEvent) ReadDelta added in v1.46.0

func (e *TextEvent) ReadDelta() []DeltaOp

ReadDelta returns the event's delta as yjs's event.delta getter does, computed on the first call (by this event or a copy of it given to another observer) and the same on every later call.

A first call during the commit that delivered the event, from its observers or those of the transactions that commit runs after it, opens a local transaction with Origin nil, as the getter's transact does, which deletes the format markers the walk finds redundant: a marker the transaction added whose value is the attribute already in effect, and an older marker whose value is the attribute an added one set. That transaction is committed after the delivering one (its update and events come after), and opened whether or not it deletes anything.

Delta is the delta when the event was first given out; ReadDelta's is computed at its first call, as yjs's getter's is, so it sees what changed the text in between: the deletions of another event's first read, a transaction run after this one (the format cleanup's). Read before anything changed the text since the event was given out, they are the same. After that commit ReadDelta deletes nothing and returns Delta: yjs would open a transaction of its own then.

Call it from the goroutine running the commit (an observer or handler of the commit, or of a transaction it runs after it). From another goroutine while the commit runs it races with the commit, as any use of the document there does; after the commit it is safe.

type XmlElement

type XmlElement struct {
	// contains filtered or unexported fields
}

XmlElement is an XML element — a tag name (NodeName), an attribute map (Map-like), and a list of children (Array-like) — all backed by the same Branch.

Attributes are stored as map-keyed Items with ContentAny string values. Children are stored as positional Items. The two surfaces (map and positional) coexist on the same Branch because they use disjoint fields (branch.Map vs branch.Start).

func NewXmlElement

func NewXmlElement(branch *block.Branch) *XmlElement

NewXmlElement wraps the given branch as an XmlElement. Sets TypeRef = TypeRefXmlElement if not already set; the caller is responsible for setting Branch.Name (which is the nodeName) if the branch is freshly constructed at the root level. For nested elements, use the InsertXmlElement family which sets Name automatically.

func (*XmlElement) Attributes

func (e *XmlElement) Attributes() map[string]string

Attributes returns a snapshot of all live attribute (name, value) pairs. Returned map is a copy; mutate freely.

func (*XmlElement) Branch

func (e *XmlElement) Branch() *block.Branch

Branch returns the underlying *block.Branch.

func (*XmlElement) Delete

func (e *XmlElement) Delete(txn *doc.TransactionMut, idx, length uint64)

Delete removes length children starting at idx.

func (*XmlElement) Get

func (e *XmlElement) Get(idx uint64) any

Get returns the child at idx, wrapped as *XmlElement or *XmlText.

func (*XmlElement) GetAttribute

func (e *XmlElement) GetAttribute(name string) (string, bool)

GetAttribute returns the value of the named attribute. The second return reports whether the attribute is set.

func (*XmlElement) InsertXmlElement

func (e *XmlElement) InsertXmlElement(txn *doc.TransactionMut, idx uint64, nodeName string) *XmlElement

InsertXmlElement inserts a new XmlElement child with nodeName at position idx. Returns the wrapper.

func (*XmlElement) InsertXmlText

func (e *XmlElement) InsertXmlText(txn *doc.TransactionMut, idx uint64) *XmlText

InsertXmlText inserts a new XmlText child at position idx.

func (*XmlElement) Length

func (e *XmlElement) Length() uint64

Length returns the number of live children.

func (*XmlElement) NodeName

func (e *XmlElement) NodeName() string

NodeName returns the element's tag name (the JS Yjs nodeName).

func (*XmlElement) Range

func (e *XmlElement) Range(fn func(idx uint64, child any) bool)

Range iterates over children. fn returns false to stop early.

func (*XmlElement) RemoveAttribute

func (e *XmlElement) RemoveAttribute(txn *doc.TransactionMut, name string)

RemoveAttribute tombstones the named attribute. Calling on an unset attribute is a no-op.

func (*XmlElement) SetAttribute

func (e *XmlElement) SetAttribute(txn *doc.TransactionMut, name, value string)

SetAttribute sets the named attribute to value, replacing any prior value. Reuses the Map.Set machinery — attributes are map-keyed entries on the same Branch.

func (*XmlElement) ToString

func (e *XmlElement) ToString() string

ToString renders the element as yjs YXmlElement.toString does:

<nodename attr1="value1" attr2="value2">...children...</nodename>

The tag is lower-cased, an empty element still gets a closing tag (never self-closing), and attribute keys are sorted. Attribute values are inlined without escaping, as in yjs; an HTML encoder would escape them.

type XmlFragment

type XmlFragment struct {
	// contains filtered or unexported fields
}

XmlFragment is a root container of XmlElement and XmlText children. Mirrors Y.XmlFragment — the top-level entry for collaborative XML/DOM documents (ProseMirror, Tiptap, BlockNote all use this shape). Children are accessed positionally.

Per docs/yrs-port-notes/nested-types.md §1, the underlying Branch carries TypeRef = TypeRefXmlFragment; NewXmlFragment sets it on wrap so cross-client receivers that wrap the same root by name end up with consistent state.

func NewXmlFragment

func NewXmlFragment(branch *block.Branch) *XmlFragment

NewXmlFragment wraps the given branch as an XmlFragment. Sets Branch.TypeRef = TypeRefXmlFragment.

func (*XmlFragment) Branch

func (f *XmlFragment) Branch() *block.Branch

Branch returns the underlying *block.Branch.

func (*XmlFragment) Delete

func (f *XmlFragment) Delete(txn *doc.TransactionMut, idx, length uint64)

Delete removes length children starting at idx.

func (*XmlFragment) Get

func (f *XmlFragment) Get(idx uint64) any

Get returns the child at idx as *XmlElement, *XmlText, or nil if idx is out of range or the underlying item is of an unsupported kind.

func (*XmlFragment) InsertXmlElement

func (f *XmlFragment) InsertXmlElement(txn *doc.TransactionMut, idx uint64, nodeName string) *XmlElement

InsertXmlElement inserts a new XmlElement child with the given nodeName at position idx. Returns the wrapper bound to the new child branch.

func (*XmlFragment) InsertXmlText

func (f *XmlFragment) InsertXmlText(txn *doc.TransactionMut, idx uint64) *XmlText

InsertXmlText inserts a new XmlText child at position idx. Use the returned wrapper to populate the text content.

func (*XmlFragment) Length

func (f *XmlFragment) Length() uint64

Length returns the number of live children.

func (*XmlFragment) Range

func (f *XmlFragment) Range(fn func(idx uint64, child any) bool)

Range iterates over children in document order. fn receives the index and the wrapped child; return false to stop early.

func (*XmlFragment) ToString

func (f *XmlFragment) ToString() string

ToString renders the fragment as an XML-like string by concatenating child renderings. Attribute keys are sorted ascending for deterministic output (tests and snapshots compare stable strings).

type XmlText

type XmlText struct {
	Text
}

XmlText is rich-text content within an XML tree. Embeds the regular Text wrapper, so every Insert / InsertWithAttributes / Format / InsertEmbed / Range / ToDelta method is available directly. The Branch's TypeRef is set to TypeRefXmlText so wire round-trips identify the child as text rather than a generic Y.Text.

func NewXmlText

func NewXmlText(branch *block.Branch) *XmlText

NewXmlText wraps the given branch as an XmlText, setting TypeRef = TypeRefXmlText.

func (*XmlText) ToString

func (x *XmlText) ToString() string

ToString returns the underlying text — alias for Text.String() kept for parity with XmlElement/XmlFragment ToString.

Jump to

Keyboard shortcuts

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