y_crdt

package module
v0.0.0-...-c0cb10d Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 14 Imported by: 0

README

y-crdt

A Golang implementation of the Yjs algorithms, designed to serve as a robust backend server for multi-terminal document collaboration. This implementation enhances real-time collaboration experiences across diverse user scenarios by efficiently merging updates from various terminals, extracting differential data, and supporting data archiving.

In the future, we plan to develop a complete y-server service that synchronizes data with client terminals via WebSocket. Stay tuned for updates!

Update

support y-protocols lib.

Compatibility test

Test cases are implemented in compatibility_test.go , focusing on validating cross-version and cross-language compatibility with Yjs.
Note: Encoder/decoder v2 support is pending development.

Compatibility testing passed.

package y_crdt

import (
	"bytes"
	"encoding/json"
	"testing"

	"github.com/bytedance/mockey"
)

func TestTextInsertDelete(t *testing.T) {
	// Generated via:
	//     ```js
	//        const doc = new Y.Doc()
	//        const ytext = doc.getText('type')
	//        doc..transact_mut()(function () {
	//            ytext.insert(0, 'def')
	//            ytext.insert(0, 'abc')
	//            ytext.insert(6, 'ghi')
	//            ytext.delete(2, 5)
	//        })
	//        const update = Y.encodeStateAsUpdate(doc)
	//        ytext.toString() // => 'abhi'
	//     ```
	//
	//     This way we confirm that we can decode and apply:
	//     1. blocks without left/right origin consisting of multiple characters
	//     2. blocks with left/right origin consisting of multiple characters
	//     3. delete sets

	// construct doc by golang and check to see if the result is the same as the expected.
	doc := NewDoc("guid", false, nil, nil, false)
	ytext := doc.GetText("type")
	doc.Transact(func(trans *Transaction) {
		ytext.Insert(0, "def", nil)
		ytext.Insert(0, "abc", nil)
		ytext.Insert(6, "ghi", nil)
		ytext.Delete(2, 5)
	}, nil)

	if ytext.ToString() != "abhi" {
		t.Error("expected abhi, got ", ytext.ToString())
	}
	t.Logf("construct by golang, ytext is %s", ytext.ToString())

	// the payload was generated by javascript.
	var payload = []byte{
		1, 5, 152, 234, 173, 126, 0, 1, 1, 4, 116, 121, 112, 101, 3, 68, 152, 234, 173, 126, 0, 2,
		97, 98, 193, 152, 234, 173, 126, 4, 152, 234, 173, 126, 0, 1, 129, 152, 234, 173, 126, 2,
		1, 132, 152, 234, 173, 126, 6, 2, 104, 105, 1, 152, 234, 173, 126, 2, 0, 3, 5, 2,
	}

	// apply the update and check to see if the result is the same as the expected.
	doc = NewDoc("guid", false, nil, nil, false)
	doc.Transact(func(trans *Transaction) {
		ApplyUpdate(doc, payload, nil)
	}, nil)

	ytext = doc.GetText("type")
	if ytext.ToString() != "abhi" {
		t.Errorf("expected abhi, got %s", ytext.ToString())
	}
	t.Logf("after apply update, ytext is %s", ytext.ToString())
}

func TestMapSet(t *testing.T) {
	//  Generated via:
	//     ```js
	//        const doc = new Y.Doc()
	//        const x = doc.getMap('test')
	//        x.set('k1', 'v1')
	//        x.set('k2', 'v2')
	//        const payload_v1 = Y.encodeStateAsUpdate(doc)
	//        console.log(payload_v1);
	//        const payload_v2 = Y.encodeStateAsUpdateV2(doc)
	//        console.log(payload_v2);
	//     ```

	mocker := mockey.Mock(GenerateNewClientID).Return(440166001).Build()

	// construct doc by golang and check to see if the result is the same as the expected.
	doc := NewDoc("guid", false, nil, nil, false)
	x := doc.GetMap("test").(*YMap)
	doc.Transact(func(trans *Transaction) {
		x.Set("k1", "v1")
		x.Set("k2", "v2")
	}, nil)

	content, err := json.Marshal(x.ToJson())
	if err != nil {
		t.Errorf("marshal x to json, err is %v", err)
	}

	t.Logf("construct by golang, x is %s", content)

	m := make(map[string]string)
	err = json.Unmarshal(content, &m)
	if err != nil || len(m) != 2 || m["k1"] != "v1" || m["k2"] != "v2" {
		t.Errorf("expected {\"k1\":\"v1\",\"k2\":\"v2\"}, got %s", content)
	}

	// the payload was generated by javascript.
	var payload = []byte{
		1, 2, 241, 204, 241, 209, 1, 0, 40, 1, 4, 116, 101, 115, 116, 2, 107, 49, 1, 119, 2, 118,
		49, 40, 1, 4, 116, 101, 115, 116, 2, 107, 50, 1, 119, 2, 118, 50, 0,
	}

	// encode doc(geneareted by golang) and compare with payload(generated by javascript).
	update := EncodeStateAsUpdate(doc, nil)
	t.Logf("update is %v", update)
	if !bytes.Equal(update, payload) {
		t.Errorf("expect update:%v got update:%v", payload, update)
	}

	// apply the update(v1) and check to see if the result is the same as the expected.
	mocker.UnPatch()
	doc = NewDoc("guid", false, nil, nil, false)
	doc.Transact(func(trans *Transaction) {
		ApplyUpdate(doc, payload, nil)
	}, nil)

	content, err = json.Marshal(doc.GetMap("test").ToJson())
	if err != nil {
		t.Errorf("marshal doc.GetMap(\"test\") to json, err is %v", err)
	}

	t.Logf("after apply update, x is %s", content)

	m = make(map[string]string)
	err = json.Unmarshal(content, &m)
	if err != nil || len(m) != 2 || m["k1"] != "v1" || m["k2"] != "v2" {
		t.Errorf("expected {\"k1\":\"v1\",\"k2\":\"v2\"}, got %s", content)
	}

	// decoder v2 not support yet.
}

func TestArrayInsert(t *testing.T) {
	// Generated via:
	//     ```js
	//        const doc = new Y.Doc()
	//        const x = doc.getArray('test')
	//        x.push(['a']);
	//        x.push(['b']);
	//        const payload_v1 = Y.encodeStateAsUpdate(doc)
	//        console.log(payload_v1);
	//        const payload_v2 = Y.encodeStateAsUpdateV2(doc)
	//        console.log(payload_v2);
	//     ```

	mocker := mockey.Mock(GenerateNewClientID).Return(2525665872).Build()

	// construct doc by golang and check to see if the result is the same as the expected.
	doc := NewDoc("guid", false, nil, nil, false)
	x := doc.GetArray("test")
	x.Push([]any{"a"})
	x.Push([]any{"b"})

	content, err := json.Marshal(x.ToJson())
	t.Logf("construct by golang, x is %s, err is %v", content, err)

	if !bytes.Equal(content, []byte("[\"a\",\"b\"]")) {
		t.Errorf("expected [\"a\",\"b\"], got %s", content)
	}

	// the payload was generated by javascript.
	var payload = []byte{
		1, 1, 208, 180, 170, 180, 9, 0, 8, 1, 4, 116, 101, 115, 116, 2, 119, 1, 97, 119, 1, 98, 0,
	}

	// encode doc(geneareted by golang) and compare with payload(generated by javascript).
	update := EncodeStateAsUpdate(doc, nil)
	t.Logf("update is %v", update)
	if !bytes.Equal(update, payload) {
		t.Errorf("expect update:%v got update:%v", payload, update)
	}

	// apply the update(v1) and check to see if the result is the same as the expected.
	mocker.UnPatch()
	doc = NewDoc("new doc", false, nil, nil, false)
	ApplyUpdate(doc, payload, nil)

	content, err = json.Marshal(doc.GetArray("test").ToJson())
	t.Logf("after apply update, x is %s, err is %v", content, err)

	if !bytes.Equal(content, []byte("[\"a\",\"b\"]")) {
		t.Errorf("expected [\"a\",\"b\"], got %s", content)
	}
}

func TestXmlFragmentInsert(t *testing.T) {
	//  Generated via:
	// ```js
	//    const ydoc = new Y.Doc()
	//    const yxmlFragment = ydoc.getXmlFragment('fragment-name')
	//    const yxmlNested = new Y.XmlFragment('fragment-name')
	//    const yxmlText = new Y.XmlText()
	//    yxmlFragment.insert(0, [yxmlText])
	//    yxmlFragment.firstChild === yxmlText
	//    yxmlFragment.insertAfter(yxmlText, [new Y.XmlElement('node-name')])
	//    const payload_v1 = Y.encodeStateAsUpdate(ydoc)
	//    console.log(payload_v1);
	//    const payload_v2 = Y.encodeStateAsUpdateV2(ydoc)
	//    console.log(payload_v2);
	// ```

	mockey.Mock(GenerateNewClientID).Return(2459881872).Build()

	// construct doc by golang and check to see if the result is the same as the expected.
	doc := NewDoc("guid", false, nil, nil, false)
	yxmlFragment := doc.GetXmlFragment("fragment-name").(*YXmlFragment)
	yxmlText := NewYXmlText()
	yxmlFragment.Insert(0, ArrayAny{yxmlText})

	if yxmlFragment.GetFirstChild().(*YXmlText) != yxmlText {
		t.Errorf("expected yxmlFragment.GetFirstChild() is yxmlText, got %v", yxmlFragment.GetFirstChild())
	}

	yxmlFragment.InsertAfter(yxmlText, ArrayAny{NewYXmlElement("node-name")})
	update := EncodeStateAsUpdate(doc, nil)

	var payload = []byte{
		1, 2, 144, 163, 251, 148, 9, 0, 7, 1, 13, 102, 114, 97, 103, 109, 101, 110, 116, 45, 110,
		97, 109, 101, 6, 135, 144, 163, 251, 148, 9, 0, 3, 9, 110, 111, 100, 101, 45, 110, 97, 109,
		101, 0,
	}

	if !bytes.Equal(update, payload) {
		t.Errorf("expected update:%v got update:%v", payload, update)
	}
}

func TestStateVector(t *testing.T) {
	//  Generated via:
	//   ```js
	//      const a = new Y.Doc()
	//      const ta = a.getText('test')
	//      ta.insert(0, 'abc')

	//      const b = new Y.Doc()
	//      const tb = b.getText('test')
	//      tb.insert(0, 'de')

	//      Y.applyUpdate(a, Y.encodeStateAsUpdate(b))
	//      console.log(Y.encodeStateVector(a))
	//   ```

	var payload = []byte{2, 178, 219, 218, 44, 3, 190, 212, 225, 6, 2}
	sv := DecodeStateVector(payload)

	expected := map[Number]Number{
		14182974: 2,
		93760946: 3,
	}

	for k, v := range expected {
		if sv[k] != v {
			t.Errorf("expected %v, got %v", v, sv[k])
		}
	}

	serialized := EncodeStateVector(nil, sv, NewUpdateEncoderV1())
	if !bytes.Equal(serialized, payload) {
		t.Errorf("expected: %v, got: %v", payload, serialized)
	}
}


Encoding & Decoding

Encoding

Basic Types
  • WriteByte: Write uint8 to buffer.
  • WriteVarUint: Variable-length uint64 encoding.
  • WriteVarInt: Variable-length int encoding with sign handling.
  • WriteFloat32/64: Big-endian float encoding.
  • WriteInt64: Big-endian int64 encoding.
Composite Types
  • WriteString: Write length + string data.
  • WriteObject: Write key-value count, then key-value pairs.
  • WriteArray: Write element count, then elements.
  • WriteVarUint8Array/WriteUint8Array: Write byte arrays with/without length prefix.
Universal
  • WriteAny: Type-specific encoding with flag bytes.

Decoding

Basic Types
  • readVarUint: Read variable-length uint64.
  • ReadUint8: Read uint8.
  • ReadVarInt: Restore int from variable-length bytes.
  • ReadFloat32/64: Parse big-endian floats.
  • ReadBigInt64: Parse big-endian int64.
Composite Types
  • ReadString: Read length, then string data.
  • ReadObject: Read count, then key-value pairs.
  • ReadArray: Read count, then elements.
  • ReadVarUint8Array: Read length, then byte array.
Universal
  • ReadAny: Decode based on type flag byte.

Encoding and decoding are symmetric, using variable-length and big-endian formats for efficiency.

Yjs Data Structures

YMap

  • YMap: A key-value store with efficient updates.
  • YMapItem: Represents a key-value pair in the map.
  • YMapItemMap: Maps keys to YMapItem pointers.

YArray

  • YArray: A dynamic array with efficient updates.
  • YArrayItem: Represents an element in the array.

YText

  • YText: A text document with efficient updates.
  • YTextItem: Represents a character in the text.
  • YTextItemMap: Maps positions to YTextItem pointers.

YXmlFragment

  • YXmlFragment: A fragment of an XML document.
  • YXmlFragmentItem: Represents an XML node.
  • YXmlFragmentItemMap: Maps positions to YXmlFragmentItem pointers.

Documentation

Index

Constants

View Source
const (
	BITS0 = 0
	BITS1 = 1   // low 1 bit
	BITS2 = 3   // low 2 bits
	BITS3 = 7   // low 3 bits
	BITS4 = 15  // low 4 bits
	BITS5 = 31  // low 5 bits
	BITS6 = 63  // low 6 bits
	BITS7 = 127 // low 7 bits
	BITS8 = 255 // low 8 bits
)

define the mask to get the low n bits of a byte.

View Source
const (
	BIT1 = 1   // first bit
	BIT2 = 2   // second bit
	BIT3 = 4   // third bit
	BIT4 = 8   // fourth bit
	BIT5 = 16  // fifth bit
	BIT6 = 32  // sixth bit
	BIT7 = 64  // seventh bit
	BIT8 = 128 // eighth bit
)

define the mask to get the specific bit of a byte.

View Source
const (
	RefGC             = iota // 0 GC is not ItemContent
	RefContentDeleted        // 1
	RefContentJson           // 2
	RefContentBinary         // 3
	RefContentString         // 4
	RefContentEmbed          // 5
	RefContentFormat         // 6
	RefContentType           // 7
	RefContentAny            // 8
	RefContentDoc            // 9
	RefSkip                  // 10 Skip is not ItemContent
)

RefContent define reference content type

View Source
const (
	YArrayRefID = iota
	YMapRefID
	YTextRefID
	YXmlElementRefID
	YXmlFragmentRefID
	YXmlHookRefID
	YXmlTextRefID
)

RefID define reference id

View Source
const (
	OptKeyGC       = "gc"
	OptKeyAutoLoad = "autoLoad"
	OptKeyMeta     = "meta"
)
View Source
const (
	MessageYjsSyncStep1 = 0
	MessageYjsSyncStep2 = 1
	MessageYjsUpdate    = 2
)
View Source
const (
	MessageSync = iota
	MessageAwareness
)
View Source
const (
	ActionAdd    = "add"
	ActionDelete = "delete"
	ActionUpdate = "update"
)
View Source
const DefaultNodeName = "UNDEFINED"
View Source
const (
	KeywordUndefined = "undefined"
)
View Source
const (
	MessagePermissionDenied = 0
)
View Source
const OutdatedTimeout = 30 * time.Second
View Source
const (
	RecordPositionUnit = 1024
)
View Source
const (
	StructGCRefNumber = 0
)
View Source
const StructSkipRefNumber = 10

Variables

View Source
var (
	Null      = NullType{}
	Undefined = UndefinedType{}
)
View Source
var DefaultGCFilter = func(item *Item) bool {
	return true
}
View Source
var (
	ErrInvalidData = errors.New("invalid data error")
)
View Source
var GlobalSearchMarkerTimestamp = 0
View Source
var Log = func(a ...interface{}) {
	fmt.Println(a...)
}
View Source
var Logf = func(format string, a ...interface{}) {
	fmt.Printf(format+"\n", a...)
}
View Source
var ReadAnyLookupTable = []func(decoder *bytes.Buffer) (any, error){
	undefined,
	null,
	ReadVarInt,
	ReadFloat32,
	ReadFloat64,
	ReadBigInt64,
	readFalse,
	readTrue,
	ReadVarString,
}

Functions

func AddChangedTypeToTransaction

func AddChangedTypeToTransaction(trans *Transaction, t IAbstractType, parentSub string)

If `type.parent` was added in current transaction, `type` technically did not change, it was just added and we should not fire events for `type`.

func AddEventHandlerListener

func AddEventHandlerListener(eventHandler *EventHandler, f EventListener)

Adds an event listener that is called when

func AddStruct

func AddStruct(store *StructStore, st IAbstractStruct) error

func AddToDeleteSet

func AddToDeleteSet(ds *DeleteSet, client Number, clock Number, length Number)

func ApplyAwarenessUpdate

func ApplyAwarenessUpdate(awareness *Awareness, update []byte, origin interface{})

func ApplyUpdate

func ApplyUpdate(ydoc *Doc, update []uint8, transactionOrigin interface{})

Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`.

This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder.

func ApplyUpdateV2

func ApplyUpdateV2(ydoc *Doc, update []uint8, transactionOrigin interface{}, YDecoder *UpdateDecoderV1)

Apply a document update created by, for example, `y.on('update', update => ..)` or `update = encodeStateAsUpdate()`.

This function has the same effect as `readUpdate` but accepts an Uint8Array instead of a Decoder.

func ArrayLast

func ArrayLast(a ArrayAny) (interface{}, error)

ArrayLast returns the last element of the given array. If the array is empty, it returns an error.

func CallAll

func CallAll(fs *[]func(...interface{}), args ArrayAny, i int)

CallAll calls all the functions in the given slice with the given arguments.

func CallEventHandlerListeners

func CallEventHandlerListeners(eventHandler *EventHandler, arg0, arg1 interface{})

Call all event listeners that were added via

func CallTypeObservers

func CallTypeObservers(t IAbstractType, trans *Transaction, event IEventType)

Call event listeners with an event. This will also add an event to all parents (for `.observeDeep` handlers).

func CharCodeAt

func CharCodeAt(str string, pos Number) (uint16, error)

CharCodeAt returns the Unicode code point of the character at the specified index in the given string. The index is the position of the character in the string, starting from 0. If the index is out of range, it returns an error.

func CleanupContextlessFormattingGap

func CleanupContextlessFormattingGap(trans *Transaction, item *Item)

func CleanupTransactions

func CleanupTransactions(transactionCleanups []*Transaction, i Number)

func ClearInterval

func ClearInterval(t *time.Timer)

func CompareIDs

func CompareIDs(a *ID, b *ID) bool

CompareIDs compares two IDs for equality.

func CompareRelativePositions

func CompareRelativePositions(a, b *RelativePosition) bool

func Conditional

func Conditional(cond bool, a interface{}, b interface{}) interface{}

Conditional returns a if cond is true, otherwise b.

func DecodeStateVector

func DecodeStateVector(decodedState []uint8) map[Number]Number

Read decodedState and return State as Map.

func DiffUpdate

func DiffUpdate(update []uint8, sv []uint8) []uint8

func DiffUpdateV2

func DiffUpdateV2(update []uint8, sv []uint8, YDecoder func([]byte) *UpdateDecoderV1, YEncoder func() *UpdateEncoderV1) []uint8

func DiffUpdates

func DiffUpdates(update []uint8, sv []uint8, maxUpdateSize int) [][]uint8

func DiffUpdatesV2

func DiffUpdatesV2(update []uint8, sv []uint8, YDecoder func([]byte) *UpdateDecoderV1, YEncoder func() *UpdateEncoderV1, maxUpdateSize int) [][]uint8

func EncodeAwarenessUpdate

func EncodeAwarenessUpdate(awareness *Awareness, clients []Number, states map[Number]Object) []byte

func EncodeRelativePosition

func EncodeRelativePosition(rpos *RelativePosition) []uint8

func EncodeSnapshot

func EncodeSnapshot(snapshot *Snapshot) []uint8

func EncodeSnapshotV2

func EncodeSnapshotV2(snapshot *Snapshot, encoder *UpdateEncoderV1) []uint8

func EncodeStateAsUpdate

func EncodeStateAsUpdate(doc *Doc, encodedTargetStateVector []uint8) []uint8

func EncodeStateAsUpdateV2

func EncodeStateAsUpdateV2(doc *Doc, encodedTargetStateVector []uint8, encoder *UpdateEncoderV1) []uint8

Write all the document as a single update message that can be applied on the remote document. If you specify the state of the remote client (`targetState`) it will only write the operations that are missing. Use `writeStateAsUpdate` instead if you are working with lib0/encoding.js#Encoder

func EncodeStateVector

func EncodeStateVector(doc *Doc, m map[Number]Number, encoder *UpdateEncoderV1) []uint8

func EncodeStateVectorFromUpdate

func EncodeStateVectorFromUpdate(update []uint8) []uint8

func EncodeStateVectorFromUpdateV2

func EncodeStateVectorFromUpdateV2(update []uint8, YEncoder func() *UpdateEncoderV1, YDecoder func([]byte) *UpdateDecoderV1) []uint8

func EncodeStateVectorV2

func EncodeStateVectorV2(doc *Doc, m map[Number]Number, encoder *UpdateEncoderV1) []uint8

func EqualAttrs

func EqualAttrs(a, b interface{}) bool

EqualAttrs returns true if the two given objects have the same attributes.

func EqualContentFormat

func EqualContentFormat(a, b interface{}) bool

EqualContentFormat returns true if the two given ContentFormat objects have the same attributes.

func EqualSnapshots

func EqualSnapshots(snap1, snap2 *Snapshot) bool

func FindRootTypeKey

func FindRootTypeKey(t IAbstractType) string

The top types are mapped from y.share.get(keyname) => type. `type` does not store any information about the `keyname`. This function finds the correct `keyname` for `type` and throws otherwise.

func FinishLazyStructWriting

func FinishLazyStructWriting(lazyWriter *LazyStructWriter)

Call this function when we collected all parts and want to put all the parts together. After calling this method, you can continue using the UpdateEncoder.

func FlushLazyStructWriter

func FlushLazyStructWriter(lazyWriter *LazyStructWriter)

func FollowRedone

func FollowRedone(store *StructStore, id ID) (*Item, Number)

This should return several items

func FormatText

func FormatText(trans *Transaction, parent IAbstractType, currPos *ItemTextListPosition, length Number, attributes Object)

func GenerateUpdate

func GenerateUpdate(lazyWriter *LazyStructWriter, maxUpdateSize int) []uint8

func GenerateUpdates

func GenerateUpdates(lazyWriter *LazyStructWriter, maxUpdateSize int) [][]uint8

func GetPathTo

func GetPathTo(parent IAbstractType, child IAbstractType) []interface{}

Compute the path from this type to the specified target.

@example ----------------------------------------------------------------------------

// `child` should be accessible via `type.get(path[0]).get(path[1])..`
const path = type.getPathTo(child)
// assuming `type instanceof YArray`
console.Log(path) // might look like => [2, 'key1']
child === type.get(path[0]).get(path[1])

----------------------------------------------------------------------------

func GetStateVector

func GetStateVector(store *StructStore) map[Number]Number

Return the states as a Map<client,clock>. Note that clock refers to the next expected clock id.

func GetUnixTime

func GetUnixTime() int64

GetUnixTime returns the current Unix time in milliseconds.

func InsertNegatedAttributes

func InsertNegatedAttributes(trans *Transaction, parent IAbstractType, currPos *ItemTextListPosition, negatedAttributes Object)

Negate applied formats

func InsertText

func InsertText(trans *Transaction, parent IAbstractType, currPos *ItemTextListPosition, text interface{}, attributes Object)

func InsertionSort

func InsertionSort(a []*LazyStructReader)

InsertionSort 只将第一个元素重新插入合适的位置,即,除第一个元素外,其他元素是有序的

func IntegretyCheck

func IntegretyCheck(store *StructStore) error

func IsDeleted

func IsDeleted(ds *DeleteSet, id *ID) bool

func IsGCPtr

func IsGCPtr(obj interface{}) bool

IsGCPtr returns true if the given object is a pointer to a GC.

func IsIAbstractType

func IsIAbstractType(a interface{}) bool

IsIAbstractType returns true if the given object is an IAbstractType.

func IsIDPtr

func IsIDPtr(obj interface{}) bool

IsIDPtr returns true if the given object is a pointer to an ID.

func IsItemPtr

func IsItemPtr(obj interface{}) bool

IsItemPtr returns true if the given object is a pointer to an Item.

func IsNull

func IsNull(obj any) bool

IsNull returns true if the given object is null. In javascript, null indicate that the variable has been initialized and the value is null. In golang, we define an object is null if the object is a pointer kind and the value is nil or its type is Null.

func IsParentOf

func IsParentOf(parent IAbstractType, child *Item) bool

Check if `parent` is a parent of `child`.

func IsPtr

func IsPtr(obj any) bool

IsPtr returns true if the given object is a pointer.

func IsSameType

func IsSameType(a interface{}, b interface{}) bool

IsSameType returns true if the given two objects are the same type.

func IsString

func IsString(obj interface{}) bool

IsString returns true if the given object is a string.

func IsUndefined

func IsUndefined(obj any) bool

IsUndefined returns true if the given object is undefined. In javascript, undefined indicate that the variable has not been initialized. In golang, a nil any(=interface{}) value indicates that the variable has not been initialized. So, we define an object is undefined if its value is nil or its type is Undefined.

func IsVisible

func IsVisible(item *Item, snapshot *Snapshot) bool

func IsYString

func IsYString(obj interface{}) bool

IsYString returns true if the given object is a YString.

func IterateDeletedStructs

func IterateDeletedStructs(trans *Transaction, ds *DeleteSet, f func(s IAbstractStruct))

Iterate over all structs that the DeleteSet gc's. f func(*GC|*Item)

func IterateStructs

func IterateStructs(trans *Transaction, ss *[]IAbstractStruct, clockStart Number, length Number, f func(s IAbstractStruct))

Iterate over a range of structs

func JsonObject

func JsonObject(data string) interface{}

func JsonString

func JsonString(object interface{}) string

func KeepItem

func KeepItem(item *Item, keep bool)

Make sure that neither item nor any of its parents is ever deleted.

This property does not persist when storing it into a database or when sending it to other peers

func LogUpdate

func LogUpdate(update []uint8, YDecoder func([]byte) *UpdateDecoderV1)

func LogUpdateV2

func LogUpdateV2(update []uint8, YDecoder func([]byte) *UpdateDecoderV1)

func MapAny

func MapAny(m map[Number]Number, f func(key, value Number) bool) bool

MapAny returns true if the given map satisfies the given function.

func MapSortedRange

func MapSortedRange(m map[Number]Number, isInc bool, f func(key, value Number))

MergeSortedRange merges two sorted ranges of the given map. The isInc parameter determines the order of the ranges.

func MergeString

func MergeString(str1, str2 string) string

MergeString merges two strings.

func MergeUpdates

func MergeUpdates(updates [][]uint8, YDecoder func([]byte) *UpdateDecoderV1, YEncoder func() *UpdateEncoderV1, stopIfError bool) []uint8

func MergeUpdatesV2

func MergeUpdatesV2(updates [][]uint8, YDecoder func([]byte) *UpdateDecoderV1, YEncoder func() *UpdateEncoderV1, stopIfError bool) []uint8

func MinimizeAttributeChanges

func MinimizeAttributeChanges(currPos *ItemTextListPosition, attributes Object)

func ModifyAwarenessUpdate

func ModifyAwarenessUpdate(update []byte, modify func(interface{}) interface{}) []byte

Modify the content of an awareness update before re-encoding it to an awareness update.

This might be useful when you have a central server that wants to ensure that clients cant hijack somebody elses identity.

func NewDecoder

func NewDecoder(buf []byte) *bytes.Buffer

NewDecoder creates a new decoder.

func NewEncoder

func NewEncoder() *bytes.Buffer

NewEncoder creates a new UpdateEncoderV1 instance.

func OverwriteMarker

func OverwriteMarker(marker *ArraySearchMarker, p *Item, index Number)

This is rather complex so this function is the only thing that should overwrite a marker

func ParseUpdateMeta

func ParseUpdateMeta(update []uint8) (map[Number]Number, map[Number]Number)

func ParseUpdateMetaV2

func ParseUpdateMetaV2(update []uint8, YDecoder func([]byte) *UpdateDecoderV1) (map[Number]Number, map[Number]Number)

func ReadAndApplyDeleteSet

func ReadAndApplyDeleteSet(decoder *UpdateDecoderV1, trans *Transaction, store *StructStore) []uint8

func ReadAny

func ReadAny(decoder *bytes.Buffer) (any, error)

ReadAny is the general decoding dispatcher that uses ReadAnyLookupTable.

func ReadArray

func ReadArray(decoder *bytes.Buffer) (any, error)

ReadArray decodes an array<any> from the decoder buffer.

func ReadAuthMessage

func ReadAuthMessage(decoder *bytes.Buffer, doc *Doc, permissionDeniedHandler func(doc *Doc, reason string))

func ReadBigInt64

func ReadBigInt64(decoder *bytes.Buffer) (any, error)

ReadBigInt64 reads an 8-byte int64 from the decoder buffer using big-endian encoding.

func ReadClientsStructRefs

func ReadClientsStructRefs(decoder *UpdateDecoderV1, doc *Doc) (map[Number]*ClientStructRef, error)

func ReadFloat32

func ReadFloat32(decoder *bytes.Buffer) (any, error)

ReadFloat32 reads a 4-byte float32 from the decoder buffer using big-endian encoding.

func ReadFloat64

func ReadFloat64(decoder *bytes.Buffer) (any, error)

ReadFloat64 reads an 8-byte float64 from the decoder buffer using big-endian encoding.

func ReadObject

func ReadObject(decoder *bytes.Buffer) (any, error)

ReadObject decodes an object<string, any> from the decoder buffer.

func ReadStateVector

func ReadStateVector(decoder *UpdateDecoderV1) map[Number]Number

Read state vector from Decoder and return as Map

func ReadString

func ReadString(decoder *bytes.Buffer) (string, error)

ReadString reads a variable-length string from the decoder buffer.

func ReadSyncMessage

func ReadSyncMessage(decoder *UpdateDecoderV1, encoder *UpdateEncoderV1, doc *Doc, transactionOrigin interface{}) int

ReadSyncMessage Read and apply Structs and then DeleteStore to a y instance.

func ReadSyncStep1

func ReadSyncStep1(decoder *UpdateDecoderV1, encoder *UpdateEncoderV1, doc *Doc)

Read SyncStep1 message and reply with SyncStep2.

func ReadSyncStep2

func ReadSyncStep2(decoder *UpdateDecoderV1, doc *Doc, transactionOrigin interface{})

func ReadUint8

func ReadUint8(decoder *bytes.Buffer) (uint8, error)

ReadUint8 reads and returns a single uint8 from the decoder buffer.

func ReadUpdate

func ReadUpdate(decoder *UpdateDecoderV1, ydoc *Doc, transactionOrigin interface{})

Read and apply a document update. This function has the same effect as `applyUpdate` but accepts an decoder.

func ReadUpdateV2

func ReadUpdateV2(decoder *UpdateDecoderV1, ydoc *Doc, transactionOrigin interface{}, structDecoder *UpdateDecoderV1)

Read and apply a document update. This function has the same effect as `applyUpdate` but accepts an decoder.

func ReadVarInt

func ReadVarInt(decoder *bytes.Buffer) (any, error)

ReadVarInt reads and returns a varint-encoded integer from the decoder buffer.

func ReadVarString

func ReadVarString(decoder *bytes.Buffer) (any, error)

ReadVarString decodes a variable-length string from the decoder buffer. First reads the string length as a Uvarint, then reads the corresponding bytes.

func ReadVarUint

func ReadVarUint(decoder *bytes.Buffer) uint64

ReadVarUint is a wrapper around readVarUint that returns the decoded uint64.

func ReadVarUint8Array

func ReadVarUint8Array(decoder *bytes.Buffer) (any, error)

ReadVarUnit8Array decodes a Uint8Array (byte slice) from the decoder buffer.

func RefreshMarkerTimestamp

func RefreshMarkerTimestamp(marker *ArraySearchMarker)

func RemoveAllEventHandlerListeners

func RemoveAllEventHandlerListeners(eventHandler *EventHandler)

Removes all event listeners.

func RemoveAwarenessStates

func RemoveAwarenessStates(awareness *Awareness, clients []Number, origin interface{})

Mark (remote) clients as inactive and remove them from the list of active peers. This change will be propagated to remote clients.

func RemoveEventHandlerListener

func RemoveEventHandlerListener(eventHandler *EventHandler, f EventListener)

Removes an event listener.

func ReplaceChar

func ReplaceChar(str string, pos Number, char uint16) string

ReplaceChar replaces the character at the specified index in the given string with the given character.

func ReplaceStruct

func ReplaceStruct(store *StructStore, item IAbstractStruct, newItem IAbstractStruct) error

Replace item(*GC|*Item) with newItem(*GC|*Item) in store

func SortAndMergeDeleteSet

func SortAndMergeDeleteSet(ds *DeleteSet)

func SpliceStruct

func SpliceStruct(ss *[]IAbstractStruct, start Number, deleteCount Number, elements []IAbstractStruct)

SpliceStruct inserts elements into a slice at the specified start index, deleting deleteCount elements if deleteCount is greater than 0. It returns the deleted elements if deleteCount is greater than 0, otherwise it returns nil.

func SpliceStructInner

func SpliceStructInner(ss *[]IAbstractStruct, start Number, deleteCount Number, elements []IAbstractStruct)

SpliceStructInner copies the elements to be inserted into a new slice, and then appends the new slice to the original slice. It returns the deleted elements if deleteCount is greater than 0, otherwise it returns nil. The capacity of the original slice is not expanded.

func SplitSnapshotAffectedStructs

func SplitSnapshotAffectedStructs(trans *Transaction, snapshot *Snapshot)

func StringHeader

func StringHeader(str string, offset Number) string

StringHeader returns the substring of the given string from the beginning to the offset.

func StringTail

func StringTail(str string, offset Number) string

StringTail returns the substring of the given string from the offset to the end.

func Transact

func Transact(doc *Doc, f func(trans *Transaction), origin interface{}, local bool)

Implements the functionality of `y.transact(()=>{..})`

default parameters: origin = nil, local = true

func TryGc

func TryGc(ds *DeleteSet, store *StructStore, gcFilter func(item *Item) bool)

func TryGcDeleteSet

func TryGcDeleteSet(ds *DeleteSet, store *StructStore, gcFilter func(item *Item) bool)

func TryMergeDeleteSet

func TryMergeDeleteSet(ds *DeleteSet, store *StructStore)

func TryToMergeWithLeft

func TryToMergeWithLeft(structs *[]IAbstractStruct, pos Number)

func TypeListDelete

func TypeListDelete(trans *Transaction, parent IAbstractType, index Number, length Number) error

func TypeListForEach

func TypeListForEach(t IAbstractType, f func(interface{}, Number, IAbstractType))

Executes a provided function on once on overy element of this YArray.

func TypeListForEachSnapshot

func TypeListForEachSnapshot(t IAbstractType, f func(interface{}, Number, IAbstractType), snapshot *Snapshot)

Executes a provided function on once on overy element of this YArray. Operates on a snapshotted state of the document.

func TypeListGet

func TypeListGet(t IAbstractType, index Number) interface{}

func TypeListInsertGenerics

func TypeListInsertGenerics(trans *Transaction, parent IAbstractType, index Number, content ArrayAny) error

func TypeListInsertGenericsAfter

func TypeListInsertGenericsAfter(trans *Transaction, parent IAbstractType, referenceItem *Item, content ArrayAny) error

func TypeMapDelete

func TypeMapDelete(trans *Transaction, parent IAbstractType, key string)

func TypeMapGet

func TypeMapGet(parent IAbstractType, key string) interface{}

func TypeMapGetSnapshot

func TypeMapGetSnapshot(parent IAbstractType, key string, snapshot *Snapshot) interface{}

func TypeMapHas

func TypeMapHas(parent IAbstractType, key string) bool

func TypeMapSet

func TypeMapSet(trans *Transaction, parent IAbstractType, key string, value interface{}) error

func UpdateCurrentAttributes

func UpdateCurrentAttributes(currentAttributes Object, format *ContentFormat)

func UpdateMarkerChanges

func UpdateMarkerChanges(searchMarker *[]*ArraySearchMarker, index Number, length Number)

Update markers when a change happened. This should be called before doing a deletion!

func VenusApplyAwarenessUpdate

func VenusApplyAwarenessUpdate(awareness *Awareness, update []byte)

VenusApplyAwarenessUpdate this method is belong golang venus library. Apply awareness' update without emit 'update' and 'change' event.

func WriteAny

func WriteAny(encoder *bytes.Buffer, any any) error

WriteAny writes any type to the encoder buffer.

func WriteArray

func WriteArray(encoder *bytes.Buffer, array []any) error

WriteArray writes an array(any) to the encoder buffer.

func WriteByte

func WriteByte(encoder *bytes.Buffer, number uint8)

WriteByte writes a single uint8 number to the encoder buffer.

func WriteClientsStructs

func WriteClientsStructs(encoder *UpdateEncoderV1, store *StructStore, _sm map[Number]Number)

func WriteDeleteSet

func WriteDeleteSet(encoder *UpdateEncoderV1, ds *DeleteSet)

func WriteDeleteSetV2

func WriteDeleteSetV2(encoder *UpdateEncoderV2, ds *DeleteSet)

func WriteDocumentStateVector

func WriteDocumentStateVector(encoder *UpdateEncoderV1, doc *Doc)

func WriteFloat32

func WriteFloat32(encoder *bytes.Buffer, f float32)

WriteFloat32 writes a 4-byte float32 to the encoder buffer using big-endian encoding.

func WriteFloat64

func WriteFloat64(encoder *bytes.Buffer, f float64)

WriteFloat64 writes an 8-byte float64 to the encoder buffer using big-endian encoding.

func WriteInt64

func WriteInt64(encoder *bytes.Buffer, n int64)

WriteInt64 writes an 8-byte int64 to the encoder buffer using big-endian encoding.

func WriteObject

func WriteObject(encoder *bytes.Buffer, obj Object) error

WriteObject writes an object to the encoder buffer.

func WritePermissionDenied

func WritePermissionDenied(encoder *bytes.Buffer, reason string)

func WriteRelativePosition

func WriteRelativePosition(encoder *UpdateEncoderV1, rpos *RelativePosition) error

func WriteStateAsUpdate

func WriteStateAsUpdate(encoder *UpdateEncoderV1, doc *Doc, targetStateVector map[Number]Number)

Write all the document as a single update message. If you specify the state of the remote client (`targetStateVector`) it will only write the operations that are missing.

func WriteString

func WriteString(encoder *bytes.Buffer, str string) error

WriteString writes a variable-length string to the encoder buffer.

func WriteStructToLazyStructWriter

func WriteStructToLazyStructWriter(lazyWriter *LazyStructWriter, s IAbstractStruct, offset Number)

func WriteStructs

func WriteStructs(encoder *UpdateEncoderV1, structs *[]IAbstractStruct, client, clock Number)

func WriteStructsFromTransaction

func WriteStructsFromTransaction(encoder *UpdateEncoderV1, trans *Transaction)

func WriteSyncStep1

func WriteSyncStep1(encoder *UpdateEncoderV1, doc *Doc)

Create a sync step 1 message based on the state of the current shared document.

func WriteSyncStep1FromUpdate

func WriteSyncStep1FromUpdate(encoder *UpdateEncoderV1, update []uint8)

func WriteSyncStep2

func WriteSyncStep2(encoder *UpdateEncoderV1, doc *Doc, encodedStateVector []byte)

func WriteSyncStep2FromUpdate

func WriteSyncStep2FromUpdate(encoder *UpdateEncoderV1, update []byte, encodedStateVector []byte)

func WriteUint8Array

func WriteUint8Array(encoder *bytes.Buffer, buf []uint8)

WriteUint8Array writes a byte array to the encoder buffer. The first byte is the length of the array, and the following bytes are the array elements.

func WriteUpdate

func WriteUpdate(encoder *UpdateEncoderV1, update []byte)

func WriteUpdateMessageFromTransaction

func WriteUpdateMessageFromTransaction(encoder *UpdateEncoderV1, trans *Transaction) bool

func WriteVarInt

func WriteVarInt(encoder *bytes.Buffer, number int)

WriteVarInt writes a variable-length int64 number to the encoder buffer.

func WriteVarUint

func WriteVarUint(encoder *bytes.Buffer, number uint64)

WriteVarUint writes a variable-length uint64 number to the encoder buffer.

func WriteVarUint8Array

func WriteVarUint8Array(encoder *bytes.Buffer, buf []uint8)

WriteUint8Array writes a byte array to the encoder buffer. The first byte is the length of the array, and the following bytes are the array elements.

Types

type AbsolutePosition

type AbsolutePosition struct {
	Type  IAbstractType
	Index Number
	Assoc Number
}

func CreateAbsolutePositionFromRelativePosition

func CreateAbsolutePositionFromRelativePosition(rpos *RelativePosition, doc *Doc) *AbsolutePosition

func NewAbsolutePosition

func NewAbsolutePosition(t IAbstractType, index, assoc Number) *AbsolutePosition

type AbstractStruct

type AbstractStruct struct {
	ID     ID
	Length Number
}

func (*AbstractStruct) Deleted

func (s *AbstractStruct) Deleted() bool

func (*AbstractStruct) GetID

func (s *AbstractStruct) GetID() *ID

func (*AbstractStruct) GetLength

func (s *AbstractStruct) GetLength() Number

func (*AbstractStruct) GetMissing

func (s *AbstractStruct) GetMissing(trans *Transaction, store *StructStore) (Number, error)

func (*AbstractStruct) Integrate

func (s *AbstractStruct) Integrate(trans *Transaction, offset Number)

func (*AbstractStruct) MergeWith

func (s *AbstractStruct) MergeWith(right IAbstractStruct) bool

Merge this struct with the item to the right. This method is already assuming that `this.id.clock + this.length === this.id.clock`. Also this method does *not* remove right from StructStore! @param {AbstractStruct} right @return {boolean} whether this merged with right

func (*AbstractStruct) SetLength

func (s *AbstractStruct) SetLength(length Number)

func (*AbstractStruct) Write

func (s *AbstractStruct) Write(encoder *UpdateEncoderV1, offset Number)

type AbstractType

type AbstractType struct {
	Item         *Item
	Map          map[string]*Item
	Start        *Item
	Doc          *Doc
	Length       Number
	EH           *EventHandler // event handlers
	DEH          *EventHandler // deep event handlers
	SearchMarker []*ArraySearchMarker
}

func (*AbstractType) CallObserver

func (t *AbstractType) CallObserver(trans *Transaction, parentSubs Set)

Creates YEvent and calls all type observers. Must be implemented by each type.

func (*AbstractType) Clone

func (t *AbstractType) Clone() IAbstractType

func (*AbstractType) Copy

func (t *AbstractType) Copy() IAbstractType

func (*AbstractType) First

func (t *AbstractType) First() *Item

The first non-deleted item

func (*AbstractType) GetDEH

func (t *AbstractType) GetDEH() *EventHandler

func (*AbstractType) GetDoc

func (t *AbstractType) GetDoc() *Doc

func (*AbstractType) GetEH

func (t *AbstractType) GetEH() *EventHandler

func (*AbstractType) GetItem

func (t *AbstractType) GetItem() *Item

func (*AbstractType) GetLength

func (t *AbstractType) GetLength() Number

func (*AbstractType) GetMap

func (t *AbstractType) GetMap() map[string]*Item

func (*AbstractType) GetSearchMarker

func (t *AbstractType) GetSearchMarker() *[]*ArraySearchMarker

func (*AbstractType) Integrate

func (t *AbstractType) Integrate(y *Doc, item *Item)

Integrate this type into the Yjs instance.

* Save this struct in the os * This type is sent to other client * Observer functions are fired

func (*AbstractType) Observe

func (t *AbstractType) Observe(f func(interface{}, interface{}))

Observe all events that are created on this type.

func (*AbstractType) ObserveDeep

func (t *AbstractType) ObserveDeep(f func(interface{}, interface{}))

Observe all events that are created by this type and its children.

func (*AbstractType) Parent

func (t *AbstractType) Parent() IAbstractType

func (*AbstractType) SetLength

func (t *AbstractType) SetLength(number Number)

func (*AbstractType) SetMap

func (t *AbstractType) SetMap(m map[string]*Item)

func (*AbstractType) SetSearchMarker

func (t *AbstractType) SetSearchMarker(marker []*ArraySearchMarker)

func (*AbstractType) SetStartItem

func (t *AbstractType) SetStartItem(item *Item)

func (*AbstractType) StartItem

func (t *AbstractType) StartItem() *Item

func (*AbstractType) ToJson

func (t *AbstractType) ToJson() interface{}

func (*AbstractType) Unobserve

func (t *AbstractType) Unobserve(f func(interface{}, interface{}))

Unregister an observer function.

func (*AbstractType) UnobserveDeep

func (t *AbstractType) UnobserveDeep(f func(interface{}, interface{}))

Unregister an observer function.

func (*AbstractType) UpdateLength

func (t *AbstractType) UpdateLength(n Number)

func (*AbstractType) Write

func (t *AbstractType) Write(encoder *UpdateEncoderV1)

type ArrayAny

type ArrayAny = []any

js Array<any>

func SpliceArray

func SpliceArray(a *ArrayAny, start Number, deleteCount Number, elements ArrayAny) ArrayAny

SpliceArray inserts elements into a slice at the specified start index, deleting deleteCount elements if deleteCount is greater than 0. It returns the deleted elements if deleteCount is greater than 0, otherwise it returns nil.

func SpliceArrayInner

func SpliceArrayInner(a *ArrayAny, start Number, deleteCount Number, elements ArrayAny) ArrayAny

SpliceArrayInner copies the elements to be inserted into a new slice, and then appends the new slice to the original slice.

func TypeListMap

func TypeListMap(t IAbstractType, f func(c interface{}, i Number, _ IAbstractType) interface{}) ArrayAny

func TypeListSlice

func TypeListSlice(t IAbstractType, start, end Number) ArrayAny

func TypeListToArray

func TypeListToArray(t IAbstractType) ArrayAny

func TypeListToArraySnapshot

func TypeListToArraySnapshot(t IAbstractType, snapshot *Snapshot) ArrayAny

func Unshift

func Unshift(a ArrayAny, e interface{}) ArrayAny

Unshift adds the given element to the beginning of the given array.

type ArraySearchMarker

type ArraySearchMarker struct {
	P         *Item
	Index     Number
	Timestamp Number
}

A unique timestamp that identifies each marker. Time is relative,.. this is more like an ever-increasing clock.

func FindMarker

func FindMarker(yarray IAbstractType, index Number) *ArraySearchMarker

Search marker help us to find positions in the associative array faster.

They speed up the process of finding a position without much bookkeeping.

A maximum of `maxSearchMarker` objects are created.

This function always returns a refreshed marker (updated timestamp)

func MarkPosition

func MarkPosition(searchMarker *[]*ArraySearchMarker, p *Item, index Number) *ArraySearchMarker

func NewArraySearchMarker

func NewArraySearchMarker(p *Item, index Number) *ArraySearchMarker

type Awareness

type Awareness struct {
	*Observable
	Doc      *Doc
	ClientID Number
	States   map[Number]Object
	Meta     map[Number]Object
}

func NewAwareness

func NewAwareness(doc *Doc) *Awareness

func (*Awareness) Destroy

func (a *Awareness) Destroy()

func (*Awareness) GetLocalState

func (a *Awareness) GetLocalState() Object

func (*Awareness) GetStates

func (a *Awareness) GetStates() map[Number]Object

func (*Awareness) SetLocalState

func (a *Awareness) SetLocalState(state Object)

func (*Awareness) SetLocalStateField

func (a *Awareness) SetLocalStateField(field string, value interface{})

type ClientStruct

type ClientStruct struct {
	Written      Number
	RestEncoder  []uint8
	PositionList []PositionInfo
	Client       Number
	Start        int
	End          int
}

type ClientStructRef

type ClientStructRef struct {
	I    Number
	Refs []IAbstractStruct
}

type ContentAny

type ContentAny struct {
	Arr ArrayAny
}

func NewContentAny

func NewContentAny(arr ArrayAny) *ContentAny

func (*ContentAny) Copy

func (c *ContentAny) Copy() IAbstractContent

func (*ContentAny) Delete

func (c *ContentAny) Delete(trans *Transaction)

func (*ContentAny) GC

func (c *ContentAny) GC(store *StructStore)

func (*ContentAny) GetContent

func (c *ContentAny) GetContent() ArrayAny

func (*ContentAny) GetLength

func (c *ContentAny) GetLength() Number

func (*ContentAny) GetRef

func (c *ContentAny) GetRef() uint8

func (*ContentAny) Integrate

func (c *ContentAny) Integrate(trans *Transaction, item *Item)

func (*ContentAny) IsCountable

func (c *ContentAny) IsCountable() bool

func (*ContentAny) MergeWith

func (c *ContentAny) MergeWith(right IAbstractContent) bool

func (*ContentAny) Splice

func (c *ContentAny) Splice(offset Number) IAbstractContent

func (*ContentAny) Write

func (c *ContentAny) Write(encoder *UpdateEncoderV1, offset Number) error

type ContentBinary

type ContentBinary struct {
	Content []uint8
}

func NewContentBinary

func NewContentBinary(content []uint8) *ContentBinary

func (*ContentBinary) Copy

func (c *ContentBinary) Copy() IAbstractContent

func (*ContentBinary) Delete

func (c *ContentBinary) Delete(trans *Transaction)

func (*ContentBinary) GC

func (c *ContentBinary) GC(store *StructStore)

func (*ContentBinary) GetContent

func (c *ContentBinary) GetContent() ArrayAny

func (*ContentBinary) GetLength

func (c *ContentBinary) GetLength() Number

func (*ContentBinary) GetRef

func (c *ContentBinary) GetRef() uint8

func (*ContentBinary) Integrate

func (c *ContentBinary) Integrate(trans *Transaction, item *Item)

func (*ContentBinary) IsCountable

func (c *ContentBinary) IsCountable() bool

func (*ContentBinary) MergeWith

func (c *ContentBinary) MergeWith(right IAbstractContent) bool

func (*ContentBinary) Splice

func (c *ContentBinary) Splice(offset Number) IAbstractContent

func (*ContentBinary) Write

func (c *ContentBinary) Write(encoder *UpdateEncoderV1, offset Number) error

type ContentDeleted

type ContentDeleted struct {
	Length Number
}

func NewContentDeleted

func NewContentDeleted(length Number) *ContentDeleted

func (*ContentDeleted) Copy

func (c *ContentDeleted) Copy() IAbstractContent

func (*ContentDeleted) Delete

func (c *ContentDeleted) Delete(trans *Transaction)

func (*ContentDeleted) GC

func (c *ContentDeleted) GC(store *StructStore)

func (*ContentDeleted) GetContent

func (c *ContentDeleted) GetContent() ArrayAny

func (*ContentDeleted) GetLength

func (c *ContentDeleted) GetLength() Number

func (*ContentDeleted) GetRef

func (c *ContentDeleted) GetRef() uint8

func (*ContentDeleted) Integrate

func (c *ContentDeleted) Integrate(trans *Transaction, item *Item)

func (*ContentDeleted) IsCountable

func (c *ContentDeleted) IsCountable() bool

func (*ContentDeleted) MergeWith

func (c *ContentDeleted) MergeWith(right IAbstractContent) bool

func (*ContentDeleted) Splice

func (c *ContentDeleted) Splice(offset Number) IAbstractContent

func (*ContentDeleted) Write

func (c *ContentDeleted) Write(encoder *UpdateEncoderV1, offset Number) error

type ContentDoc

type ContentDoc struct {
	Doc  *Doc
	Opts Object
}

func NewContentDoc

func NewContentDoc(doc *Doc) *ContentDoc

func (*ContentDoc) Copy

func (c *ContentDoc) Copy() IAbstractContent

func (*ContentDoc) Delete

func (c *ContentDoc) Delete(trans *Transaction)

func (*ContentDoc) GC

func (c *ContentDoc) GC(store *StructStore)

func (*ContentDoc) GetContent

func (c *ContentDoc) GetContent() ArrayAny

func (*ContentDoc) GetLength

func (c *ContentDoc) GetLength() Number

func (*ContentDoc) GetRef

func (c *ContentDoc) GetRef() uint8

func (*ContentDoc) Integrate

func (c *ContentDoc) Integrate(trans *Transaction, item *Item)

func (*ContentDoc) IsCountable

func (c *ContentDoc) IsCountable() bool

func (*ContentDoc) MergeWith

func (c *ContentDoc) MergeWith(right IAbstractContent) bool

func (*ContentDoc) Splice

func (c *ContentDoc) Splice(offset Number) IAbstractContent

func (*ContentDoc) Write

func (c *ContentDoc) Write(encoder *UpdateEncoderV1, offset Number) error

type ContentEmbed

type ContentEmbed struct {
	Embed interface{}
}

func NewContentEmbed

func NewContentEmbed(embed interface{}) *ContentEmbed

func (*ContentEmbed) Copy

func (c *ContentEmbed) Copy() IAbstractContent

func (*ContentEmbed) Delete

func (c *ContentEmbed) Delete(trans *Transaction)

func (*ContentEmbed) GC

func (c *ContentEmbed) GC(store *StructStore)

func (*ContentEmbed) GetContent

func (c *ContentEmbed) GetContent() ArrayAny

func (*ContentEmbed) GetLength

func (c *ContentEmbed) GetLength() Number

func (*ContentEmbed) GetRef

func (c *ContentEmbed) GetRef() uint8

func (*ContentEmbed) Integrate

func (c *ContentEmbed) Integrate(trans *Transaction, item *Item)

func (*ContentEmbed) IsCountable

func (c *ContentEmbed) IsCountable() bool

func (*ContentEmbed) MergeWith

func (c *ContentEmbed) MergeWith(right IAbstractContent) bool

func (*ContentEmbed) Splice

func (c *ContentEmbed) Splice(offset Number) IAbstractContent

func (*ContentEmbed) Write

func (c *ContentEmbed) Write(encoder *UpdateEncoderV1, offset Number) error

type ContentFormat

type ContentFormat struct {
	Key   string
	Value interface{}
}

func NewContentFormat

func NewContentFormat(key string, value interface{}) *ContentFormat

func (*ContentFormat) Copy

func (c *ContentFormat) Copy() IAbstractContent

func (*ContentFormat) Delete

func (c *ContentFormat) Delete(trans *Transaction)

func (*ContentFormat) GC

func (c *ContentFormat) GC(store *StructStore)

func (*ContentFormat) GetContent

func (c *ContentFormat) GetContent() ArrayAny

func (*ContentFormat) GetLength

func (c *ContentFormat) GetLength() Number

func (*ContentFormat) GetRef

func (c *ContentFormat) GetRef() uint8

func (*ContentFormat) Integrate

func (c *ContentFormat) Integrate(trans *Transaction, item *Item)

func (*ContentFormat) IsCountable

func (c *ContentFormat) IsCountable() bool

func (*ContentFormat) MergeWith

func (c *ContentFormat) MergeWith(right IAbstractContent) bool

func (*ContentFormat) Splice

func (c *ContentFormat) Splice(offset Number) IAbstractContent

func (*ContentFormat) Write

func (c *ContentFormat) Write(encoder *UpdateEncoderV1, offset Number) error

type ContentJson

type ContentJson struct {
	Arr ArrayAny
}

func NewContentJson

func NewContentJson(arr ArrayAny) *ContentJson

func (*ContentJson) Copy

func (c *ContentJson) Copy() IAbstractContent

func (*ContentJson) Delete

func (c *ContentJson) Delete(trans *Transaction)

func (*ContentJson) GC

func (c *ContentJson) GC(store *StructStore)

func (*ContentJson) GetContent

func (c *ContentJson) GetContent() ArrayAny

func (*ContentJson) GetLength

func (c *ContentJson) GetLength() Number

func (*ContentJson) GetRef

func (c *ContentJson) GetRef() uint8

func (*ContentJson) Integrate

func (c *ContentJson) Integrate(trans *Transaction, item *Item)

func (*ContentJson) IsCountable

func (c *ContentJson) IsCountable() bool

func (*ContentJson) MergeWith

func (c *ContentJson) MergeWith(right IAbstractContent) bool

func (*ContentJson) Splice

func (c *ContentJson) Splice(offset Number) IAbstractContent

func (*ContentJson) Write

func (c *ContentJson) Write(encoder *UpdateEncoderV1, offset Number) error

type ContentString

type ContentString struct {
	Str string
}

func NewContentString

func NewContentString(str string) *ContentString

func (*ContentString) Copy

func (c *ContentString) Copy() IAbstractContent

func (*ContentString) Delete

func (c *ContentString) Delete(trans *Transaction)

func (*ContentString) GC

func (c *ContentString) GC(store *StructStore)

func (*ContentString) GetContent

func (c *ContentString) GetContent() ArrayAny

func (*ContentString) GetLength

func (c *ContentString) GetLength() Number

func (*ContentString) GetRef

func (c *ContentString) GetRef() uint8

func (*ContentString) Integrate

func (c *ContentString) Integrate(trans *Transaction, item *Item)

func (*ContentString) IsCountable

func (c *ContentString) IsCountable() bool

func (*ContentString) MergeWith

func (c *ContentString) MergeWith(right IAbstractContent) bool

func (*ContentString) Splice

func (c *ContentString) Splice(offset Number) IAbstractContent

func (*ContentString) Write

func (c *ContentString) Write(encoder *UpdateEncoderV1, offset Number) error

type ContentType

type ContentType struct {
	Type IAbstractType
}

func NewContentType

func NewContentType(t IAbstractType) *ContentType

func (*ContentType) Copy

func (c *ContentType) Copy() IAbstractContent

func (*ContentType) Delete

func (c *ContentType) Delete(trans *Transaction)

func (*ContentType) GC

func (c *ContentType) GC(store *StructStore)

func (*ContentType) GetContent

func (c *ContentType) GetContent() ArrayAny

func (*ContentType) GetLength

func (c *ContentType) GetLength() Number

func (*ContentType) GetRef

func (c *ContentType) GetRef() uint8

func (*ContentType) Integrate

func (c *ContentType) Integrate(trans *Transaction, item *Item)

func (*ContentType) IsCountable

func (c *ContentType) IsCountable() bool

func (*ContentType) MergeWith

func (c *ContentType) MergeWith(right IAbstractContent) bool

func (*ContentType) Splice

func (c *ContentType) Splice(offset Number) IAbstractContent

func (*ContentType) Write

func (c *ContentType) Write(encoder *UpdateEncoderV1, offset Number) error

type CurrWrite

type CurrWrite struct {
	S      IAbstractStruct
	Offset Number
}

type DSEncoderV1

type DSEncoderV1 struct {
	RestEncoder *bytes.Buffer
}

func (*DSEncoderV1) ResetDsCurVal

func (v1 *DSEncoderV1) ResetDsCurVal()

ResetDsCurVal resets the current value of DeleteSet.

func (*DSEncoderV1) ToUint8Array

func (v1 *DSEncoderV1) ToUint8Array() []uint8

ToUint8Array returns the encoded bytes.

func (*DSEncoderV1) WriteDsClock

func (v1 *DSEncoderV1) WriteDsClock(clock Number)

WriteDsClock writes the clock value of DeleteSet.

func (*DSEncoderV1) WriteDsLen

func (v1 *DSEncoderV1) WriteDsLen(length Number)

WriteDsLen writes the length of DeleteSet.

type DSEncoderV2

type DSEncoderV2 struct {
	RestEncoder *bytes.Buffer
	DsCurrVal   Number
}

func (*DSEncoderV2) ResetDsCurVal

func (v2 *DSEncoderV2) ResetDsCurVal()

func (*DSEncoderV2) ToUint8Array

func (v2 *DSEncoderV2) ToUint8Array() []uint8

func (*DSEncoderV2) WriteDsClock

func (v2 *DSEncoderV2) WriteDsClock(clock Number)

func (*DSEncoderV2) WriteDsLen

func (v2 *DSEncoderV2) WriteDsLen(length Number)

type DeleteItem

type DeleteItem struct {
	Clock  Number
	Length Number
}

func NewDeleteItem

func NewDeleteItem(clock Number, length Number) *DeleteItem

type DeleteSet

type DeleteSet struct {
	Clients map[Number][]*DeleteItem
}

func MergeDeleteSets

func MergeDeleteSets(dss []*DeleteSet) *DeleteSet

func NewDeleteSet

func NewDeleteSet() *DeleteSet

func NewDeleteSetFromStructStore

func NewDeleteSetFromStructStore(ss *StructStore) *DeleteSet

func ReadDeleteSet

func ReadDeleteSet(decoder *UpdateDecoderV1) *DeleteSet

type Doc

type Doc struct {
	*Observable
	Guid     string
	ClientID Number

	GC           bool
	GCFilter     func(item *Item) bool
	Share        map[string]IAbstractType
	Store        *StructStore
	Trans        *Transaction
	TransCleanup []*Transaction
	SubDocs      Set
	Item         *Item // If this document is a subdocument - a document integrated into another document - then _item is defined.
	ShouldLoad   bool
	AutoLoad     bool
	Meta         interface{}
}

func CreateDocFromSnapshot

func CreateDocFromSnapshot(originDoc *Doc, snapshot *Snapshot, newDoc *Doc) (*Doc, error)

func NewDoc

func NewDoc(guid string, gc bool, gcFilter func(item *Item) bool, meta interface{}, autoLoad bool) *Doc

func (*Doc) Destroy

func (doc *Doc) Destroy()

Emit `destroy` event and unregister all event handlers.

func (*Doc) Get

func (doc *Doc) Get(name string, typeConstructor TypeConstructor) (IAbstractType, error)

Define a shared data type.

Multiple calls of `y.get(name, TypeConstructor)` yield the same result and do not overwrite each other. I.e. `y.define(name, Y.Array) === y.define(name, Y.Array)`

After this method is called, the type is also available on `y.share.get(name)`.

Best Practices: Define all types right after the Yjs instance is created and store them in a separate object. Also use the typed methods `getText(name)`, `getArray(name)`, ..

example

const y = new Y(..)
const appState = {
  document: y.getText('document')
  comments: y.getArray('comments')
}

func (*Doc) GetArray

func (doc *Doc) GetArray(name string) *YArray

func (*Doc) GetMap

func (doc *Doc) GetMap(name string) IAbstractType

func (*Doc) GetSubdocGuids

func (doc *Doc) GetSubdocGuids() Set

func (*Doc) GetSubdocs

func (doc *Doc) GetSubdocs() Set

func (*Doc) GetText

func (doc *Doc) GetText(name string) *YText

func (*Doc) GetXmlFragment

func (doc *Doc) GetXmlFragment(name string) IAbstractType

func (*Doc) Load

func (doc *Doc) Load()

Notify the parent document that you request to load data into this subdocument (if it is a subdocument).

`load()` might be used in the future to request any provider to load the most current data.
It is safe to call `load()` multiple times.

func (*Doc) Off

func (doc *Doc) Off(eventName string, handler *ObserverHandler)

func (*Doc) On

func (doc *Doc) On(eventName string, handler *ObserverHandler)

func (*Doc) ToJson

func (doc *Doc) ToJson() Object

Converts the entire document into a js object, recursively traversing each yjs type Doesn't log types that have not been defined (using ydoc.getType(..)).

Do not use this method and rather call toJSON directly on the shared types.

func (*Doc) Transact

func (doc *Doc) Transact(f func(trans *Transaction), origin interface{})

Changes that happen inside of a transaction are bundled. This means that the observer fires _after_ the transaction is finished and that all changes that happened inside of the transaction are sent as one message to the other peers.

type EventAction

type EventAction struct {
	Action   string
	OldValue interface{}
	NewValue interface{}
}

type EventHandler

type EventHandler struct {
	L []EventListener
}

func NewEventHandler

func NewEventHandler() *EventHandler

type EventListener

type EventListener func(interface{}, interface{})

type EventOperator

type EventOperator struct {
	Insert     interface{} // string | Array<any>
	Retain     Number
	Delete     Number
	Attributes Object

	IsInsertDefined     bool
	IsRetainDefined     bool
	IsDeleteDefined     bool
	IsAttributesDefined bool
}

type GC

type GC struct {
	AbstractStruct
}

func NewGC

func NewGC(id ID, length Number) *GC

func (*GC) Delete

func (gc *GC) Delete()

func (*GC) Deleted

func (gc *GC) Deleted() bool

func (*GC) GetMissing

func (gc *GC) GetMissing(trans *Transaction, store *StructStore) (Number, error)

func (*GC) Integrate

func (gc *GC) Integrate(trans *Transaction, offset Number)

func (*GC) MergeWith

func (gc *GC) MergeWith(right IAbstractStruct) bool

func (*GC) Write

func (gc *GC) Write(encoder *UpdateEncoderV1, offset Number)

type IAbstractContent

type IAbstractContent interface {
	GetLength() Number
	GetContent() ArrayAny
	IsCountable() bool
	Copy() IAbstractContent
	Splice(offset Number) IAbstractContent
	MergeWith(right IAbstractContent) bool
	Integrate(trans *Transaction, item *Item)
	Delete(trans *Transaction)
	GC(store *StructStore)
	Write(encoder *UpdateEncoderV1, offset Number) error
	GetRef() uint8
}

func ReadContentAny

func ReadContentAny(decoder *UpdateDecoderV1) (IAbstractContent, error)

func ReadContentBinary

func ReadContentBinary(decoder *UpdateDecoderV1) (IAbstractContent, error)

func ReadContentDeleted

func ReadContentDeleted(decoder *UpdateDecoderV1) (IAbstractContent, error)

func ReadContentDoc

func ReadContentDoc(decoder *UpdateDecoderV1) (IAbstractContent, error)

func ReadContentEmbed

func ReadContentEmbed(decoder *UpdateDecoderV1) (IAbstractContent, error)

func ReadContentFormat

func ReadContentFormat(decoder *UpdateDecoderV1) (IAbstractContent, error)

func ReadContentJson

func ReadContentJson(decoder *UpdateDecoderV1) (IAbstractContent, error)

func ReadContentString

func ReadContentString(decoder *UpdateDecoderV1) (IAbstractContent, error)

func ReadContentType

func ReadContentType(decoder *UpdateDecoderV1) (IAbstractContent, error)

func ReadItemContent

func ReadItemContent(decoder *UpdateDecoderV1, info uint8) IAbstractContent

type IAbstractStruct

type IAbstractStruct interface {
	GetID() *ID
	GetLength() Number
	SetLength(length Number)
	Deleted() bool
	MergeWith(right IAbstractStruct) bool
	Write(encoder *UpdateEncoderV1, offset Number)
	Integrate(trans *Transaction, offset Number)
	GetMissing(trans *Transaction, store *StructStore) (Number, error)
}

func Find

func Find(store *StructStore, id ID) (IAbstractStruct, error)

func GetItem

func GetItem(store *StructStore, id ID) IAbstractStruct

func SliceStruct

func SliceStruct(left IAbstractStruct, diff Number) IAbstractStruct

type IAbstractType

type IAbstractType interface {
	GetLength() Number
	GetItem() *Item
	GetMap() map[string]*Item
	StartItem() *Item
	SetStartItem(item *Item)
	GetDoc() *Doc
	UpdateLength(n Number)
	SetSearchMarker(mark []*ArraySearchMarker)
	Parent() IAbstractType
	Integrate(doc *Doc, item *Item)
	Copy() IAbstractType
	Clone() IAbstractType
	Write(encoder *UpdateEncoderV1)
	First() *Item
	CallObserver(trans *Transaction, parentSubs Set)
	Observe(f func(interface{}, interface{}))
	ObserveDeep(f func(interface{}, interface{}))
	Unobserve(f func(interface{}, interface{}))
	UnobserveDeep(f func(interface{}, interface{}))
	ToJson() interface{}
	GetDEH() *EventHandler
	GetEH() *EventHandler
	SetMap(map[string]*Item)
	SetLength(number Number)
	GetSearchMarker() *[]*ArraySearchMarker
}

func NewAbstractType

func NewAbstractType() IAbstractType

func NewYArrayType

func NewYArrayType() IAbstractType

func NewYMapType

func NewYMapType() IAbstractType

func NewYTextType

func NewYTextType() IAbstractType

func NewYXmlFragmentType

func NewYXmlFragmentType() IAbstractType

type ID

type ID struct {
	AbstractType
	Client Number // client ID
	Clock  Number // unique per client id, continuous number
}

func GenID

func GenID(client Number, clock Number) ID

GenID generates a new ID with the given client and clock values.

func GetItemID

func GetItemID(item *Item) *ID

func GetItemLastID

func GetItemLastID(item *Item) *ID

func NextID

func NextID(trans *Transaction) ID

type IEventType

type IEventType interface {
	GetTarget() IAbstractType
	GetCurrentTarget() IAbstractType
	SetCurrentTarget(t IAbstractType)
	Path() []interface{}
}

func ArrayFilter

func ArrayFilter(a []IEventType, filter func(e IEventType) bool) []IEventType

ArrayFilter filters the elements of the given array by the given filter function. It returns a new array that contains the elements that satisfy the filter function.

type IXmlType

type IXmlType interface {
	ToString() string
}

type Item

type Item struct {
	AbstractStruct
	Origin      *ID   // The item that was originally to the left of this item.
	Left        *Item // The item that is currently to the left of this item.
	Right       *Item // The item that is currently to the right of this item.
	RightOrigin *ID   // The item that was originally to the right of this item.

	// Is a type if integrated, is null if it is possible to copy parent from
	// left or right, is ID before integration to search for it.
	Parent interface{} // AbstractType<any> | ID

	// If the parent refers to this item with some kind of key (e.g. YMap, the
	// key is specified here. The key is then used to refer to the list in which
	// to insert this item. If `parentSub = null` type._start is the list in
	// which to insert to. Otherwise it is `parent._map`.
	ParentSub string

	// If this type's effect is reundone this type refers to the type that undid
	// this operation.
	Redone *ID

	Content IAbstractContent

	Info uint8 // BIT1, BIT2, BIT3, BIT4 - mark node as fast-search-marker
}

Abstract class that represents any content.

func GetItemCleanEnd

func GetItemCleanEnd(trans *Transaction, store *StructStore, id ID) *Item

Expects that id is actually in store. This function throws or is an infinite loop otherwise.

func GetItemCleanStart

func GetItemCleanStart(trans *Transaction, id ID) *Item

Expects that id is actually in store. This function throws or is an infinite loop otherwise.

func GetTypeChildren

func GetTypeChildren(t IAbstractType) []*Item

Accumulate all (list) children of a type and return them as an Array.

func NewItem

func NewItem(id ID, left *Item, origin *ID, right *Item, rightOrigin *ID,
	parent IAbstractType, parentSub string, content IAbstractContent) *Item

func RedoItem

func RedoItem(trans *Transaction, item *Item, redoItems Set) *Item

Redoes the effect of this operation.

func SplitItem

func SplitItem(trans *Transaction, leftItem *Item, diff Number) *Item

Split leftItem into two items.

func (*Item) Countable

func (item *Item) Countable() bool

func (*Item) Delete

func (item *Item) Delete(trans *Transaction)

Mark this Item as deleted.

func (*Item) Deleted

func (item *Item) Deleted() bool

Whether this item was deleted or not.

func (*Item) GC

func (item *Item) GC(store *StructStore, parentGCd bool)

func (*Item) GetMissing

func (item *Item) GetMissing(trans *Transaction, store *StructStore) (Number, error)

Return the creator clientID of the missing op or define missing items and return null.

func (*Item) Integrate

func (item *Item) Integrate(trans *Transaction, offset Number)

func (*Item) Keep

func (item *Item) Keep() bool

If true, do not garbage collect this Item.

func (*Item) LastID

func (item *Item) LastID() *ID

Computes the last content address of this Item

func (*Item) MarkDeleted

func (item *Item) MarkDeleted()

func (*Item) Marker

func (item *Item) Marker() bool

This is used to mark the item as an indexed fast-search marker

func (*Item) MergeWith

func (item *Item) MergeWith(right IAbstractStruct) bool

Try to merge two items

func (*Item) Next

func (item *Item) Next() *Item

Returns the next non-deleted item

func (*Item) Prev

func (item *Item) Prev() *Item

Returns the previous non-deleted item

func (*Item) SetCountable

func (item *Item) SetCountable(countable bool)

func (*Item) SetDeleted

func (item *Item) SetDeleted(deleted bool)

func (*Item) SetKeep

func (item *Item) SetKeep(keep bool)

func (*Item) SetMarker

func (item *Item) SetMarker(marked bool)

func (*Item) Write

func (item *Item) Write(encoder *UpdateEncoderV1, offset Number)

Transform the properties of this type to binary and write it to an BinaryEncoder.

This is called when this Item is sent to a remote peer.

type ItemTextListPosition

type ItemTextListPosition struct {
	Left              *Item
	Right             *Item
	Index             Number
	CurrentAttributes Object
}

func DeleteText

func DeleteText(trans *Transaction, currPos *ItemTextListPosition, length Number) *ItemTextListPosition

func FindNextPosition

func FindNextPosition(trans *Transaction, pos *ItemTextListPosition, count Number) *ItemTextListPosition

func FindPosition

func FindPosition(trans *Transaction, parent IAbstractType, index Number) *ItemTextListPosition

func NewItemTextListPosition

func NewItemTextListPosition(left, right *Item, index Number, currentAttributes Object) *ItemTextListPosition

func (*ItemTextListPosition) Forward

func (it *ItemTextListPosition) Forward() error

Only call this if you know that this.right is defined

type LazyStructReader

type LazyStructReader struct {
	Gen         func() IAbstractStruct
	Curr        IAbstractStruct
	Done        bool
	FilterSkips bool
}

func NewLazyStructReader

func NewLazyStructReader(decoder *UpdateDecoderV1, filterSkips bool, stopIfError bool) *LazyStructReader

func (*LazyStructReader) Next

type LazyStructReaderGenerator

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

func CreateLazyStructReaderGenerator

func CreateLazyStructReaderGenerator(decoder *UpdateDecoderV1, stopIfError bool) LazyStructReaderGenerator

func (LazyStructReaderGenerator) Next

type LazyStructWriter

type LazyStructWriter struct {
	CurrClient Number
	StartClock Number
	Written    Number
	Encoder    *UpdateEncoderV1

	// We want to write operations lazily, but also we need to know beforehand how many operations we want to write for each client.
	//
	//  This kind of meta-information (#clients, #structs-per-client-written) is written to the restEncoder.
	//
	//  We fragment the restEncoder and store a slice of it per-client until we know how many clients there are.
	//  When we flush (toUint8Array) we write the restEncoder using the fragments and the meta-information.
	ClientStructs      []ClientStruct
	NeedRecordPosition bool
	PositionList       []PositionInfo
}

func NewLazyStructWriter

func NewLazyStructWriter(encoder *UpdateEncoderV1) *LazyStructWriter

type NullType

type NullType struct {
}

js null

type Number

type Number = int

js Number

func AwarenessStatesKeys

func AwarenessStatesKeys(states map[Number]Object) []Number

func BinarySearch

func BinarySearch(ss []IAbstractStruct, clock Number, begin, end Number) (Number, error)

func CleanupFormattingGap

func CleanupFormattingGap(trans *Transaction, start *Item, end *Item, startAttributes Object, endAttributes Object) Number

Call this function after string content has been deleted in order to clean up formatting Items.

func CleanupYTextFormatting

func CleanupYTextFormatting(t *YText) Number

This function is experimental and subject to change / be removed.

Ideally, we don't need this function at all. Formatting attributes should be cleaned up automatically after each change. This function iterates twice over the complete YText type and removes unnecessary formatting attributes. This is also helpful for testing.

This function won't be exported anymore as soon as there is confidence that the YText type works as intended.

func FindIndex

func FindIndex(a ArrayAny, filter func(e interface{}) bool) Number

FindIndex returns the index of the first element in the given array that satisfies the given filter function.

func FindIndexCleanStart

func FindIndexCleanStart(trans *Transaction, ss *[]IAbstractStruct, clock Number) (Number, error)

ss可能会被切割,所以需要按指针传递

func FindIndexDS

func FindIndexDS(dis []*DeleteItem, clock Number) (Number, error)

func FindIndexSS

func FindIndexSS(ss []IAbstractStruct, clock Number) (Number, error)

func GenerateNewClientID

func GenerateNewClientID() Number

GenerateNewClientID generates a new client ID.

func GetState

func GetState(store *StructStore, client Number) Number

func Max

func Max(a, b Number) Number

Max returns the maximum value of a and b.

func Min

func Min(a, b Number) Number

Min returns the minimum value of a and b.

func StringLength

func StringLength(str string) Number

StringLength returns the length of the given string in utf16 code points.

type NumberSlice

type NumberSlice []Number

js NumberSlice

func (NumberSlice) Filter

func (ns NumberSlice) Filter(cond func(number Number) bool) NumberSlice

Filter returns a new slice containing all elements for which the given function returns true.

func (NumberSlice) Len

func (ns NumberSlice) Len() int

Len returns the length of the slice.

func (NumberSlice) Less

func (ns NumberSlice) Less(i, j int) bool

Less returns true if the element at index i is less than the element at index j.

func (NumberSlice) Swap

func (ns NumberSlice) Swap(i, j int)

Swap swaps the elements at index i and j.

type Object

type Object = map[string]any

js Object

func InsertAttributes

func InsertAttributes(trans *Transaction, parent IAbstractType, currPos *ItemTextListPosition, attributes Object) Object

func NewObject

func NewObject() Object

NewObject returns a new object.

func RelativePositionToJSON

func RelativePositionToJSON(rpos *RelativePosition) Object

func TypeMapGetAll

func TypeMapGetAll(parent IAbstractType) Object

type Observable

type Observable struct {
	Observers map[interface{}]Set
}

func NewObservable

func NewObservable() *Observable

func (*Observable) Destroy

func (o *Observable) Destroy()

func (*Observable) Emit

func (o *Observable) Emit(name interface{}, v ...interface{})

func (*Observable) Off

func (o *Observable) Off(name interface{}, handler *ObserverHandler)

func (*Observable) On

func (o *Observable) On(name interface{}, handle *ObserverHandler)

func (*Observable) Once

func (o *Observable) Once(name interface{}, handler *ObserverHandler)

type ObserverHandler

type ObserverHandler struct {
	Once     bool
	Callback func(v ...interface{})
}

func NewObserverHandler

func NewObserverHandler(f func(v ...interface{})) *ObserverHandler

type PermanentUserData

type PermanentUserData struct {
	YUsers  IAbstractType
	Doc     *Doc
	Clients map[Number]string
	Dss     map[string]*DeleteSet
}

func NewPermanentUserData

func NewPermanentUserData(doc *Doc, storeType IAbstractType) *PermanentUserData

func (*PermanentUserData) GetUserByClientID

func (p *PermanentUserData) GetUserByClientID(clientID Number) string

func (*PermanentUserData) GetUserByDeletedID

func (p *PermanentUserData) GetUserByDeletedID(id *ID) string

func (*PermanentUserData) SetUserMapping

func (p *PermanentUserData) SetUserMapping(doc *Doc, clientID Number, userDescription string, filer func(trans *Transaction, set *DeleteSet) bool)

type PositionInfo

type PositionInfo struct {
	Clock     Number
	StartByte int
	StructNo  int
}

type RelativePosition

type RelativePosition struct {
	Type  *ID
	Tname string
	Item  *ID

	// A relative position is associated to a specific character. By default
	// assoc >= 0, the relative position is associated to the character
	// after the meant position.
	// I.e. position 1 in 'ab' is associated to character 'b'.
	//
	// If assoc < 0, then the relative position is associated to the caharacter
	// before the meant position.
	Assoc Number
}

func CreateRelativePositionFromJSON

func CreateRelativePositionFromJSON(json Object) *RelativePosition

func DecodeRelativePosition

func DecodeRelativePosition(uint8Array []uint8) *RelativePosition

func NewRelativePosition

func NewRelativePosition(t IAbstractType, item *ID, assoc Number) *RelativePosition

func NewRelativePositionFromTypeIndex

func NewRelativePositionFromTypeIndex(tp IAbstractType, index, assoc Number) *RelativePosition

Create a relativePosition based on a absolute position.

func ReadRelativePosition

func ReadRelativePosition(decoder *UpdateDecoderV1) *RelativePosition

type RestStructs

type RestStructs struct {
	Missing map[Number]Number
	Update  []uint8
}

func IntegrateStructs

func IntegrateStructs(trans *Transaction, store *StructStore, clientsStructRefs map[Number]*ClientStructRef) *RestStructs

Resume computing structs generated by struct readers.

While there is something to do, we integrate structs in this order 1. top element on stack, if stack is not empty 2. next element from current struct reader (if empty, use next struct reader)

If struct causally depends on another struct (ref.missing), we put next reader of `ref.id.client` on top of stack.

At some point we find a struct that has no causal dependencies, then we start emptying the stack.

It is not possible to have circles: i.e. struct1 (from client1) depends on struct2 (from client2) depends on struct3 (from client1). Therefore the max stack size is eqaul to `structReaders.length`.

This method is implemented in a way so that we can resume computation if this update causally depends on another update.

func NewRestStructs

func NewRestStructs() *RestStructs

type Set

type Set map[any]bool

js Set<any>

func NewSet

func NewSet() Set

NewSet returns a new set.

func (Set) Add

func (s Set) Add(e any)

Add adds the given element to the set.

func (Set) Delete

func (s Set) Delete(e any)

Delete deletes the given element from the set.

func (Set) Has

func (s Set) Has(e any) bool

Has returns true if the given element is in the set.

func (Set) Range

func (s Set) Range(f func(element any))

Range calls the given function for each element in the set.

type Skip

type Skip struct {
	AbstractStruct
}

func NewSkip

func NewSkip(id ID, length Number) *Skip

func (*Skip) Delete

func (s *Skip) Delete()

func (*Skip) Deleted

func (s *Skip) Deleted() bool

func (*Skip) GetMissing

func (s *Skip) GetMissing(trans *Transaction, store *StructStore) (Number, error)

func (*Skip) Integrate

func (s *Skip) Integrate(trans *Transaction, offset Number)

func (*Skip) MergeWith

func (s *Skip) MergeWith(right IAbstractStruct) bool

func (*Skip) Write

func (s *Skip) Write(encoder *UpdateEncoderV1, offset Number)

type Snapshot

type Snapshot struct {
	Ds *DeleteSet
	Sv map[Number]Number // state map
}

func DecodeSnapshot

func DecodeSnapshot(buf []uint8) *Snapshot

func DecodeSnapshotV2

func DecodeSnapshotV2(buf []uint8) *Snapshot

func EmptySnapshot

func EmptySnapshot() *Snapshot

func NewSnapshot

func NewSnapshot(ds *DeleteSet, sv map[Number]Number) *Snapshot

func NewSnapshotByDoc

func NewSnapshotByDoc(doc *Doc) *Snapshot

snapshot(doc)

type StackItem

type StackItem struct {
	Insertions *DeleteSet
	Deletions  *DeleteSet
	Meta       map[interface{}]interface{} // Use this to save and restore metadata like selection range
}

func NewStackItem

func NewStackItem(deletes *DeleteSet, insertions *DeleteSet) *StackItem

func PopStackItem

func PopStackItem(undoManager *UndoManager, stack []*StackItem, eventType string) *StackItem

type StructStore

type StructStore struct {
	Clients        map[Number]*[]IAbstractStruct
	PendingStructs *RestStructs
	PendingDs      []uint8
}

func NewStructStore

func NewStructStore() *StructStore

func (*StructStore) GetStructs

func (ss *StructStore) GetStructs(client Number) []IAbstractStruct

type Transaction

type Transaction struct {
	// The yjs instance
	Doc *Doc

	// Describes the set of deleted items by ids
	DeleteSet *DeleteSet

	// Holds the state before the transaction started
	BeforeState map[Number]Number

	// Holds the state after the transaction
	AfterState map[Number]Number

	// All types that were directly modified (property added or child inserted/deleted).
	// New types are not included in this Set. Maps from type to parentSubs
	// (`item.parentSub = null` for YArray).
	Changed map[interface{}]Set

	// Stores the events for the types that observe also child elements.
	// It is mainly used by `observeDeep`.
	ChangedParentTypes map[interface{}][]IEventType

	// Stores the events for the types that observe also child elements.
	// It is mainly used by `observeDeep`.
	MergeStructs []IAbstractStruct

	Origin interface{}

	// Stores meta information on the transaction
	Meta map[interface{}]Set

	// Whether this change originates from this doc.
	Local bool

	SubdocsAdded   Set
	SubdocsRemoved Set
	SubdocsLoaded  Set
}

func NewTransaction

func NewTransaction(doc *Doc, origin interface{}, local bool) *Transaction

type TypeConstructor

type TypeConstructor = func() IAbstractType

type UndefinedType

type UndefinedType struct {
}

js undefined

type UndoManager

type UndoManager struct {
	*Observable
	Scopes         []IAbstractType
	DeleteFilter   func(item *Item) bool
	TrackedOrigins Set
	UndoStack      []*StackItem
	RedoStack      []*StackItem

	// Whether the client is currently undoing (calling UndoManager.undo)
	Undoing    bool
	Redoing    bool
	LastChange Number
}

@typedef {Object} UndoManagerOptions @property {number} [UndoManagerOptions.captureTimeout=500] @property {function(Item):boolean} [UndoManagerOptions.deleteFilter=()=>true] Sometimes it is necessary to filter whan an Undo/Redo operation can delete. If this filter returns false, the type/item won't be deleted even it is in the undo/redo scope. @property {Set<any>} [UndoManagerOptions.trackedOrigins=new Set([null])]

Fires 'stack-item-added' event when a stack item was added to either the undo- or
the redo-stack. You may store additional stack information via the
metadata property on `event.stackItem.meta` (it is a `Map` of metadata properties).
Fires 'stack-item-popped' event when a stack item was popped from either the
undo- or the redo-stack. You may restore the saved stack information from `event.stackItem.meta`.

@extends {Observable<'stack-item-added'|'stack-item-popped'>}

func NewUndoManager

func NewUndoManager(typeScope IAbstractType, captureTimeout Number, deleteFilter func(item *Item) bool, trackedOrigins Set) *UndoManager

func (*UndoManager) Clear

func (u *UndoManager) Clear()

func (*UndoManager) GetDoc

func (u *UndoManager) GetDoc() *Doc

func (*UndoManager) Redo

func (u *UndoManager) Redo() *StackItem

Redo last undo operation.

func (*UndoManager) StopCapturing

func (u *UndoManager) StopCapturing()

UndoManager merges Undo-StackItem if they are created within time-gap smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next StackItem won't be merged.

@example

// without stopCapturing
ytext.insert(0, 'a')
ytext.insert(1, 'b')
um.undo()
ytext.toString() // => '' (note that 'ab' was removed)
// with stopCapturing
ytext.insert(0, 'a')
um.stopCapturing()
ytext.insert(0, 'b')
um.undo()
ytext.toString() // => 'a' (note that only 'b' was removed)

func (*UndoManager) Undo

func (u *UndoManager) Undo() *StackItem

Undo last changes on type.

type UpdateDecoderV1

type UpdateDecoderV1 struct {
	RestDecoder *bytes.Buffer
}

func NewUpdateDecoderV1

func NewUpdateDecoderV1(buf []byte) *UpdateDecoderV1

NewUpdateDecoderV1 creates a new UpdateDecoderV1.

func (*UpdateDecoderV1) ReadAny

func (v1 *UpdateDecoderV1) ReadAny() (any, error)

ReadAny reads the any of Item.

func (*UpdateDecoderV1) ReadBuf

func (v1 *UpdateDecoderV1) ReadBuf() ([]uint8, error)

ReadBuf reads the buf of Item.

func (*UpdateDecoderV1) ReadClient

func (v1 *UpdateDecoderV1) ReadClient() (Number, error)

ReadClient reads the client of Item.

func (*UpdateDecoderV1) ReadDsClock

func (v1 *UpdateDecoderV1) ReadDsClock() (Number, error)

ReadDsClock reads the clock value of DeleteSet.

func (*UpdateDecoderV1) ReadDsLen

func (v1 *UpdateDecoderV1) ReadDsLen() (Number, error)

ReadDsLen reads the length of DeleteSet.

func (*UpdateDecoderV1) ReadID

func (v1 *UpdateDecoderV1) ReadID() (*ID, error)

ReadID reads the ID of Item.

func (*UpdateDecoderV1) ReadInfo

func (v1 *UpdateDecoderV1) ReadInfo() (uint8, error)

ReadInfo reads the info of Item.

func (*UpdateDecoderV1) ReadJson

func (v1 *UpdateDecoderV1) ReadJson() (interface{}, error)

ReadJson reads the json of Item.

func (*UpdateDecoderV1) ReadKey

func (v1 *UpdateDecoderV1) ReadKey() (string, error)

ReadKey reads the key of Item.

func (*UpdateDecoderV1) ReadLeftID

func (v1 *UpdateDecoderV1) ReadLeftID() (*ID, error)

ReadLeftID reads the left ID of Item.

func (*UpdateDecoderV1) ReadLen

func (v1 *UpdateDecoderV1) ReadLen() (Number, error)

ReadLen reads the length of Item.

func (*UpdateDecoderV1) ReadParentInfo

func (v1 *UpdateDecoderV1) ReadParentInfo() (bool, error)

ReadParentInfo reads the parent info of Item.

func (*UpdateDecoderV1) ReadRightID

func (v1 *UpdateDecoderV1) ReadRightID() (*ID, error)

ReadRightID reads the right ID of Item.

func (*UpdateDecoderV1) ReadString

func (v1 *UpdateDecoderV1) ReadString() (string, error)

ReadString reads the string of Item.

func (*UpdateDecoderV1) ReadTypeRef

func (v1 *UpdateDecoderV1) ReadTypeRef() (uint8, error)

ReadTypeRef reads the type ref of Item.

func (*UpdateDecoderV1) ResetDsCurVal

func (v1 *UpdateDecoderV1) ResetDsCurVal()

ResetDsCurVal resets the current value of DeleteSet.

type UpdateEncoderV1

type UpdateEncoderV1 struct {
	DSEncoderV1
}

func NewUpdateEncoderV1

func NewUpdateEncoderV1() *UpdateEncoderV1

NewUpdateEncoderV1 creates a new UpdateEncoderV1 instance.

func WriteStateVector

func WriteStateVector(encoder *UpdateEncoderV1, sv map[Number]Number) *UpdateEncoderV1

func (*UpdateEncoderV1) WriteAny

func (v1 *UpdateEncoderV1) WriteAny(any any)

WriteAny writes the any of Item.

func (*UpdateEncoderV1) WriteBuf

func (v1 *UpdateEncoderV1) WriteBuf(buf []uint8)

WriteBuf writes the buf of Item.

func (*UpdateEncoderV1) WriteClient

func (v1 *UpdateEncoderV1) WriteClient(client Number)

WriteClient writes the client of Item.

func (*UpdateEncoderV1) WriteID

func (v1 *UpdateEncoderV1) WriteID(id *ID)

WriteID writes the ID of Item.

func (*UpdateEncoderV1) WriteInfo

func (v1 *UpdateEncoderV1) WriteInfo(info uint8)

WriteInfo writes the info of Item.

func (*UpdateEncoderV1) WriteJson

func (v1 *UpdateEncoderV1) WriteJson(embed interface{}) error

WriteJson writes the json of Item.

func (*UpdateEncoderV1) WriteKey

func (v1 *UpdateEncoderV1) WriteKey(key string) error

WriteKey writes the key of Item.

func (*UpdateEncoderV1) WriteLeftID

func (v1 *UpdateEncoderV1) WriteLeftID(id *ID)

WriteLeftID writes the left ID of Item.

func (*UpdateEncoderV1) WriteLen

func (v1 *UpdateEncoderV1) WriteLen(length Number)

WriteLen write len of a struct - well suited for Opt RLE encoder.

func (*UpdateEncoderV1) WriteParentInfo

func (v1 *UpdateEncoderV1) WriteParentInfo(isYKey bool)

WriteParentInfo writes the parent info of Item.

func (*UpdateEncoderV1) WriteRightID

func (v1 *UpdateEncoderV1) WriteRightID(id *ID)

WriteRightID writes the right ID of Item.

func (*UpdateEncoderV1) WriteString

func (v1 *UpdateEncoderV1) WriteString(str string) error

WriteString writes the string of Item.

func (*UpdateEncoderV1) WriteTypeRef

func (v1 *UpdateEncoderV1) WriteTypeRef(info uint8)

WriteTypeRef writes the type ref of Item.

type UpdateEncoderV2

type UpdateEncoderV2 struct {
	DSEncoderV2
}

func NewUpdateEncoderV2

func NewUpdateEncoderV2() *UpdateEncoderV2

func (*UpdateEncoderV2) ToUint8Array

func (v2 *UpdateEncoderV2) ToUint8Array() []uint8

type UpdateHandler

type UpdateHandler func([]byte)

type WSSharedDoc

type WSSharedDoc struct {
	*Doc
	Awareness *Awareness
	// contains filtered or unexported fields
}

func NewWSSharedDoc

func NewWSSharedDoc(docID string, awarenessHandler UpdateHandler, docHandler UpdateHandler) *WSSharedDoc

type YArray

type YArray struct {
	AbstractType
	PrelimContent ArrayAny
	SearchMaker   []*ArraySearchMarker
}

A shared Array implementation.

func NewYArray

func NewYArray() *YArray

func (*YArray) CallObserver

func (y *YArray) CallObserver(trans *Transaction, parentSubs Set)

Creates YArrayEvent and calls observers.

func (*YArray) Clone

func (y *YArray) Clone() IAbstractType

func (*YArray) Copy

func (y *YArray) Copy() IAbstractType

func (*YArray) Delete

func (y *YArray) Delete(index, length Number)

Deletes elements starting from an index.

func (*YArray) ForEach

func (y *YArray) ForEach(f func(interface{}, Number, IAbstractType))

Executes a provided function on once on overy element of this YArray.

func (*YArray) From

func (y *YArray) From(items ArrayAny) *YArray

Construct a new YArray containing the specified items.

func (*YArray) Get

func (y *YArray) Get(index Number) interface{}

Returns the i-th element from a YArray.

func (*YArray) GetLength

func (y *YArray) GetLength() Number

func (*YArray) Insert

func (y *YArray) Insert(index Number, content ArrayAny)

Inserts new content at an index.

Important: This function expects an array of content. Not just a content object. The reason for this "weirdness" is that inserting several elements is very efficient when it is done as a single operation.

@example
 // Insert character 'a' at position 0
 yarray.insert(0, ['a'])
 // Insert numbers 1, 2 at position 1
 yarray.insert(1, [1, 2])

func (*YArray) Integrate

func (y *YArray) Integrate(doc *Doc, item *Item)

Integrate this type into the Yjs instance.

Save this struct in the os
This type is sent to other client
Observer functions are fired

func (*YArray) Map

func (y *YArray) Map(f func(interface{}, Number, IAbstractType) interface{}) ArrayAny

Returns an Array with the result of calling a provided function on every element of this YArray.

func (*YArray) Push

func (y *YArray) Push(content ArrayAny)

Appends content to this YArray.

func (*YArray) Range

func (y *YArray) Range(f func(item *Item))

func (*YArray) Splice

func (y *YArray) Splice(start, end Number) ArrayAny

Transforms this YArray to a JavaScript Array.

func (*YArray) ToArray

func (y *YArray) ToArray() ArrayAny

Transforms this YArray to a JavaScript Array.

func (*YArray) ToJson

func (y *YArray) ToJson() interface{}

Transforms this Shared Type to a JSON object.

func (*YArray) Unshift

func (y *YArray) Unshift(content ArrayAny)

Preppends content to this YArray.

func (*YArray) Write

func (y *YArray) Write(encoder *UpdateEncoderV1)

type YArrayEvent

type YArrayEvent struct {
	YEvent
	YTrans *Transaction
}

Event that describes the changes on a YArray

func NewYArrayEvent

func NewYArrayEvent(yarray *YArray, trans *Transaction) *YArrayEvent

type YEvent

type YEvent struct {
	Target        IAbstractType // The type on which this event was created on.
	CurrentTarget IAbstractType // The current target on which the observe callback is called.
	Trans         *Transaction  // The transaction that triggered this event.
	Changes       Object
	Keys          map[string]EventAction // Map<string, { action: 'add' | 'update' | 'delete', oldValue: any, newValue: any }>}
	// contains filtered or unexported fields
}

YEvent describes the changes on a YType.

func NewDefaultYEvent

func NewDefaultYEvent() *YEvent

func NewYEvent

func NewYEvent(target IAbstractType, trans *Transaction) *YEvent

func (*YEvent) Adds

func (y *YEvent) Adds(s IAbstractStruct) bool

Check if a struct is added by this event. In contrast to change.deleted, this method also returns true if the struct was added and then deleted.

func (*YEvent) Deletes

func (y *YEvent) Deletes(s IAbstractStruct) bool

Check if a struct is deleted by this event. In contrast to change.deleted, this method also returns true if the struct was added and then deleted.

func (*YEvent) GetChanges

func (y *YEvent) GetChanges() Object

func (*YEvent) GetCurrentTarget

func (y *YEvent) GetCurrentTarget() IAbstractType

func (*YEvent) GetDelta

func (y *YEvent) GetDelta() []EventOperator

func (*YEvent) GetKeys

func (y *YEvent) GetKeys() map[string]EventAction

func (*YEvent) GetTarget

func (y *YEvent) GetTarget() IAbstractType

func (*YEvent) Path

func (y *YEvent) Path() []interface{}

Computes the path from `y` to the changed type.

@todo v14 should standardize on path: Array<{parent, index}> because that is easier to work with.

The following property holds: @example ----------------------------------------------------------------------------

let type = y
event.path.forEach(dir => {
  type = type.get(dir)
})
type === event.target // => true

----------------------------------------------------------------------------

func (*YEvent) SetCurrentTarget

func (y *YEvent) SetCurrentTarget(t IAbstractType)

type YMap

type YMap struct {
	AbstractType
	PrelimContent map[string]interface{}
}

A shared Map implementation.

func NewYMap

func NewYMap(entries map[string]interface{}) *YMap

func (*YMap) CallObserver

func (y *YMap) CallObserver(trans *Transaction, parentSubs Set)

Creates YMapEvent and calls observers.

func (*YMap) Clear

func (y *YMap) Clear()

Removes all elements from this YMap.

func (*YMap) Clone

func (y *YMap) Clone() IAbstractType

func (*YMap) Copy

func (y *YMap) Copy() IAbstractType

func (*YMap) Delete

func (y *YMap) Delete(key string)

Remove a specified element from this YMap.

func (*YMap) Entries

func (y *YMap) Entries() map[string]interface{}

Returns an Iterator of [key, value] pairs

func (*YMap) ForEach

func (y *YMap) ForEach(f func(string, interface{}, *YMap)) Object

Executes a provided function on once on every key-value pair.

func (*YMap) Get

func (y *YMap) Get(key string) interface{}

Returns a specified element from this YMap.

func (*YMap) GetSize

func (y *YMap) GetSize() Number

Returns the size of the YMap (count of key/value pairs)

func (*YMap) Has

func (y *YMap) Has(key string) bool

func (*YMap) Integrate

func (y *YMap) Integrate(doc *Doc, item *Item)

Integrate this type into the Yjs instance.

Save this struct in the os
This type is sent to other client
Observer functions are fired

func (*YMap) Keys

func (y *YMap) Keys() []string

Returns the keys for each element in the YMap Type.

func (*YMap) Range

func (y *YMap) Range(f func(key string, val interface{}))

func (*YMap) Set

func (y *YMap) Set(key string, value interface{}) interface{}

Adds or updates an element with a specified key and value.

func (*YMap) ToJson

func (y *YMap) ToJson() interface{}

Transforms this Shared Type to a JSON object.

func (*YMap) Values

func (y *YMap) Values() []interface{}

Returns the values for each element in the YMap Type.

func (*YMap) Write

func (y *YMap) Write(encoder *UpdateEncoderV1)

type YMapEvent

type YMapEvent struct {
	YEvent
	KeysChanged Set
}

Event that describes the changes on a YMap.

func NewYMapEvent

func NewYMapEvent(ymap *YMap, trans *Transaction, subs Set) *YMapEvent

func (*YMapEvent) GetChanges

func (y *YMapEvent) GetChanges() Object

type YMapIter

type YMapIter struct {
	Key  string
	Item *Item
}

type YString

type YString struct {
	AbstractType
	Str string
}

func NewDefaultYString

func NewDefaultYString() *YString

func NewYString

func NewYString(str string) *YString

func (*YString) CallObserver

func (str *YString) CallObserver(trans *Transaction, parentSubs Set)

func (*YString) Clone

func (str *YString) Clone() IAbstractType

func (*YString) Copy

func (str *YString) Copy() IAbstractType

func (*YString) First

func (str *YString) First() *Item

func (*YString) GetDoc

func (str *YString) GetDoc() *Doc

func (*YString) GetItem

func (str *YString) GetItem() *Item

func (*YString) GetLength

func (str *YString) GetLength() Number

func (*YString) GetMap

func (str *YString) GetMap() map[string]*Item

func (*YString) Integrate

func (str *YString) Integrate(doc *Doc, item *Item)

func (*YString) Observe

func (str *YString) Observe(f func(interface{}, interface{}))

func (*YString) ObserveDeep

func (str *YString) ObserveDeep(f func(interface{}, interface{}))

func (*YString) Parent

func (str *YString) Parent() IAbstractType

func (*YString) SetSearchMarker

func (str *YString) SetSearchMarker(mark []*ArraySearchMarker)

func (*YString) SetStartItem

func (str *YString) SetStartItem(item *Item)

func (*YString) StartItem

func (str *YString) StartItem() *Item

func (*YString) ToJson

func (str *YString) ToJson() interface{}

func (*YString) Unobserve

func (str *YString) Unobserve(f func(interface{}, interface{}))

func (*YString) UnobserveDeep

func (str *YString) UnobserveDeep(f func(interface{}, interface{}))

func (*YString) UpdateLength

func (str *YString) UpdateLength(n Number)

func (*YString) Write

func (str *YString) Write(encoder *UpdateEncoderV1)

type YText

type YText struct {
	AbstractType
	Pending      []func()
	SearchMarker []ArraySearchMarker
}

Type that represents text with formatting information.

This type replaces y-richtext as this implementation is able to handle block formats (format information on a paragraph), embeds (complex elements like pictures and videos), and text formats (**bold**, *italic*).

func NewDefaultYText

func NewDefaultYText() *YText

func NewYText

func NewYText(text string) *YText

func (*YText) ApplyDelta

func (y *YText) ApplyDelta(delta []EventOperator, sanitize bool)

Apply a {@link delta} on this shared YText type. sanitize = true

func (*YText) CallObserver

func (y *YText) CallObserver(trans *Transaction, parentSubs Set)

Creates YTextEvent and calls observers.

func (*YText) Clone

func (y *YText) Clone() IAbstractType

func (*YText) Copy

func (y *YText) Copy() IAbstractType

func (*YText) Delete

func (y *YText) Delete(index Number, length Number)

Deletes text starting from an index.

func (*YText) Format

func (y *YText) Format(index Number, length Number, attributes Object)

Assigns properties to a range of text.

func (*YText) GetAttribute

func (y *YText) GetAttribute(attributeName string) interface{}

Returns an attribute value that belongs to the attribute name.

func (*YText) GetAttributes

func (y *YText) GetAttributes(snapshot *Snapshot) Object

Returns all attribute name/value pairs in a JSON Object.

func (*YText) Insert

func (y *YText) Insert(index Number, text string, attributes Object)

Insert text at a given index.

func (*YText) InsertEmbed

func (y *YText) InsertEmbed(index Number, embed Object, attributes Object)

Inserts an embed at a index.

func (*YText) Integrate

func (y *YText) Integrate(doc *Doc, item *Item)

func (*YText) Length

func (y *YText) Length() Number

func (*YText) RemoveAttribute

func (y *YText) RemoveAttribute(attributeName string)

Removes an attribute.

func (*YText) SetAttribute

func (y *YText) SetAttribute(attributeName string, attributeValue interface{})

Sets or updates an attribute.

func (*YText) ToDelta

func (y *YText) ToDelta(snapshot *Snapshot, prevSnapshot *Snapshot, computeYChange func(string, *ID) Object) []EventOperator

Returns the delta representation of this YText type.

func (*YText) ToJson

func (y *YText) ToJson() interface{}

Returns the unformatted string representation of this YText type.

func (*YText) ToString

func (y *YText) ToString() string

Returns the unformatted string representation of this YText type.

func (*YText) Write

func (y *YText) Write(encoder *UpdateEncoderV1)

type YTextEvent

type YTextEvent struct {
	YEvent
	ChildListChanged bool // Whether the children changed.
	KeysChanged      Set  // Set of all changed attributes.
}

Event that describes the changes on a YText type.

func NewYTextEvent

func NewYTextEvent(ytext *YText, trans *Transaction, subs Set) *YTextEvent

func (*YTextEvent) GetDelta

func (y *YTextEvent) GetDelta() []EventOperator

Compute the changes in the delta format. A {@link https://quilljs.com/docs/delta/|Quill delta}) that represents the changes on the document.

type YXmlElement

type YXmlElement struct {
	YXmlFragment

	PrelimAttrs map[string]interface{}
	NodeName    string
}

func NewYXmlElement

func NewYXmlElement(nodeName string) *YXmlElement

func (*YXmlElement) Clone

func (y *YXmlElement) Clone() IAbstractType

func (*YXmlElement) Copy

func (y *YXmlElement) Copy() IAbstractType

Copy Creates an Item with the same effect as this Item (without position effect)

func (*YXmlElement) GetAttribute

func (y *YXmlElement) GetAttribute(attributeName string) interface{}

GetAttribute Returns an attribute value that belongs to the attribute name.

func (*YXmlElement) GetAttributes

func (y *YXmlElement) GetAttributes() Object

GetAttributes Returns an attribute value that belongs to the attribute name.

func (*YXmlElement) GetNextSibling

func (y *YXmlElement) GetNextSibling() IAbstractType

GetNextSibling return {YXmlElement|YXmlText|nil}

func (*YXmlElement) GetPrevSibling

func (y *YXmlElement) GetPrevSibling() IAbstractType

GetPrevSibling return {YXmlElement|YXmlText|nil}

func (*YXmlElement) HasAttribute

func (y *YXmlElement) HasAttribute(attributeName string) bool

HasAttribute Returns whether an attribute exists

func (*YXmlElement) Integrate

func (y *YXmlElement) Integrate(doc *Doc, item *Item)

Integrate this type into the Yjs instance.

Save this struct in the os
This type is sent to other client
Observer functions are fired

func (*YXmlElement) RemoveAttribute

func (y *YXmlElement) RemoveAttribute(attributeName string)

RemoveAttribute Removes an attribute from this YXmlElement.

func (*YXmlElement) SetAttribute

func (y *YXmlElement) SetAttribute(attributeName string, attributeValue interface{})

SetAttribute Sets or updates an attribute.

func (*YXmlElement) ToDOM

func (y *YXmlElement) ToDOM()

ToDOM Creates a Dom Element that mirrors this YXmlElement.

func (*YXmlElement) ToString

func (y *YXmlElement) ToString() string

Returns the XML serialization of this YXmlElement. The attributes are ordered by attribute-name, so you can easily use this method to compare YXmlElements

@return {string} The string representation of this type.

func (*YXmlElement) Write

func (y *YXmlElement) Write(encoder *UpdateEncoderV1)

type YXmlEvent

type YXmlEvent struct {
	YEvent
	ChildListChanged  bool // Whether the children changed.
	AttributesChanged Set  // Set of all changed attributes.
}

YXmlEvent An Event that describes changes on a YXml Element or Yxml Fragment

func NewYXmlEvent

func NewYXmlEvent(target IAbstractType, subs Set, trans *Transaction) *YXmlEvent

type YXmlFragment

type YXmlFragment struct {
	AbstractType
	PrelimContent ArrayAny
}

func NewYXmlFragment

func NewYXmlFragment() *YXmlFragment

func (*YXmlFragment) CallObserver

func (y *YXmlFragment) CallObserver(trans *Transaction, parentSubs Set)

Creates YXmlEvent and calls observers.

func (*YXmlFragment) Clone

func (y *YXmlFragment) Clone() IAbstractType

func (*YXmlFragment) Copy

func (y *YXmlFragment) Copy() IAbstractType

func (*YXmlFragment) CreateTreeWalker

func (y *YXmlFragment) CreateTreeWalker(filter func(abstractType IAbstractType) bool) *YXmlTreeWalker

func (*YXmlFragment) Delete

func (y *YXmlFragment) Delete(index, length Number)

Deletes elements starting from an index. Default: length = 1

func (*YXmlFragment) Get

func (y *YXmlFragment) Get(index Number) interface{}

Returns the i-th element from a YArray.

func (*YXmlFragment) GetFirstChild

func (y *YXmlFragment) GetFirstChild() interface{}

func (*YXmlFragment) GetLength

func (y *YXmlFragment) GetLength() Number

func (*YXmlFragment) Insert

func (y *YXmlFragment) Insert(index Number, content ArrayAny)

Insert Inserts new content at an index.

@example

// Insert character 'a' at position 0

xml.insert(0, [new Y.XmlText('text')])

func (*YXmlFragment) InsertAfter

func (y *YXmlFragment) InsertAfter(ref interface{}, content ArrayAny)

Inserts new content at an index.

@example

// Insert character 'a' at position 0
xml.insert(0, [new Y.XmlText('text')])

func (*YXmlFragment) Integrate

func (y *YXmlFragment) Integrate(doc *Doc, item *Item)

Integrate this type into the Yjs instance.

Save this struct in the os This type is sent to other client Observer functions are fired

func (*YXmlFragment) Push

func (y *YXmlFragment) Push(content ArrayAny)

Appends content to this YArray.

func (*YXmlFragment) QuerySelector

func (y *YXmlFragment) QuerySelector(query interface{})

not supported yet.

func (*YXmlFragment) QuerySelectorAll

func (y *YXmlFragment) QuerySelectorAll(query interface{})

not supported yet.

func (*YXmlFragment) Slice

func (y *YXmlFragment) Slice(start, end Number) ArrayAny

Transforms this YArray to a JavaScript Array. Default: start = 0

func (*YXmlFragment) ToArray

func (y *YXmlFragment) ToArray() ArrayAny

Transforms this YArray to a JavaScript Array.

func (*YXmlFragment) ToDOM

func (y *YXmlFragment) ToDOM()

not supported yet.

func (*YXmlFragment) ToJson

func (y *YXmlFragment) ToJson() interface{}

func (*YXmlFragment) ToString

func (y *YXmlFragment) ToString() string

Get the string representation of all the children of this YXmlFragment.

func (*YXmlFragment) Unshift

func (y *YXmlFragment) Unshift(content ArrayAny)

Preppends content to this YArray.

func (*YXmlFragment) Write

func (y *YXmlFragment) Write(encoder *UpdateEncoderV1)

Transform the properties of this type to binary and write it to an BinaryEncoder.

This is called when this Item is sent to a remote peer.

@param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.

type YXmlHook

type YXmlHook struct {
	YMap
	HookName string
}

You can manage binding to a custom type with YXmlHook.

func NewYXmlHook

func NewYXmlHook(hookName string) *YXmlHook

func (*YXmlHook) Clone

func (y *YXmlHook) Clone() IAbstractType

Clone

func (*YXmlHook) Copy

func (y *YXmlHook) Copy() IAbstractType

Copy Creates an Item with the same effect as this Item (without position effect)

func (*YXmlHook) ToDOM

func (y *YXmlHook) ToDOM()

func (*YXmlHook) Write

func (y *YXmlHook) Write(encoder *UpdateEncoderV1)

Transform the properties of this type to binary and write it to an BinaryEncoder.

This is called when this Item is sent to a remote peer.

type YXmlText

type YXmlText struct {
	YText
}

YXmlText Represents text in a Dom Element. In the future this type will also handle simple formatting information like bold and italic.

func NewYXmlText

func NewYXmlText() *YXmlText

func (*YXmlText) Clone

func (y *YXmlText) Clone() IAbstractType

func (*YXmlText) Copy

func (y *YXmlText) Copy() IAbstractType

func (*YXmlText) GetNextSibling

func (y *YXmlText) GetNextSibling() IAbstractType

func (*YXmlText) GetPreSibling

func (y *YXmlText) GetPreSibling() IAbstractType

func (*YXmlText) ToDOM

func (y *YXmlText) ToDOM()

not supported yet.

func (*YXmlText) ToJSON

func (y *YXmlText) ToJSON() string

func (*YXmlText) ToString

func (y *YXmlText) ToString() string

func (*YXmlText) Write

func (y *YXmlText) Write(encoder *UpdateEncoderV1)

type YXmlTreeWalker

type YXmlTreeWalker struct {
	Filter      func() bool
	Root        interface{}
	CurrentNode *Item
	FirstCall   bool
}

func NewYXmlTreeWalker

func NewYXmlTreeWalker(root interface{}, f func(abstractType IAbstractType) bool) *YXmlTreeWalker

not supported yet.

Jump to

Keyboard shortcuts

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