### Example: Initialize and Create Doc Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Example demonstrating how to initialize a utils.YDoc and use it to create a content.Doc wrapper. ```go subdoc := utils.NewDoc(&utils.YDocOptions{GUID: "sub-1"}) c := content.NewDoc(subdoc) ``` -------------------------------- ### Example Usage of DSEncoderV2 Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-encoding.md Demonstrates how to use DSEncoderV2 to encode a delete set and get the resulting data. ```go encoder := utils.NewDsEncoderV2() deleteSet := utils.NewDeleteSet(doc.Store) deleteSet.Write(encoder) data := encoder.ToArray() ``` -------------------------------- ### Create a New Yjs Document Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/README.md Initializes a new Yjs document with optional configuration like garbage collection and a unique GUID. Use this to start a new collaborative session. ```go import ( "YJS-GO/utils" "YJS-GO/types" ) doc := utils.NewDoc(&utils.YDocOptions{ GC: true, GUID: "my-doc", }) ``` -------------------------------- ### Configure Yjs Document Options Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/configuration.md Initialize a new Yjs document with specific options for garbage collection, GUID, and auto-loading. Always use stable and unique GUIDs for logical documents. ```go doc := utils.NewDoc(&utils.YDocOptions{ GC: true, // Enable cleanup GUID: appID, // Use stable ID AutoLoad: false, // Manual control }) // Always use unique GUIDs per logical document // GUIDs should be stable across sessions ``` -------------------------------- ### Example Usage of UpdateDecoderV2 Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-encoding.md Demonstrates initializing UpdateDecoderV2 and using it to read structs and apply delete sets within a transaction. ```go reader := bytes.NewReader(updateData) decoder := utils.NewUpdateDecoderV2(reader) doc.Transact(func(tx *utils.Transaction) { utils.ReadStructs(decoder, tx, doc.Store) utils.ReadAndApplyDeleteSet(decoder, tx) }, "sync") ``` -------------------------------- ### Initialize YDoc with Options Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/configuration.md Configure YDoc with garbage collection, a custom GUID, metadata, and auto-load settings. ```go options := &utils.YDocOptions{ GC: true, GUID: "my-document-123", Meta: map[string]string{ "title": "Collaborative Document", "created": "2024-01-01", "author": "Alice", }, AutoLoad: false, } doc := utils.NewDoc(options) ``` -------------------------------- ### Create Yjs Items with String Content Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-structs.md Demonstrates how to create and integrate new Yjs items with string content into a YArray within a Yjs document. This example shows the setup for a new document, transaction handling, and item creation with unique IDs and content. ```go import ( "YJS-GO/structs" "YJS-GO/structs/content" "YJS-GO/types" "YJS-GO/utils" ) doc := utils.NewDoc(nil) doc.Transact(func(tx *utils.Transaction) { yarray := doc.Get("items").(*types.YArray) // Create an item with string content item1 := structs.NewItem( &utils.ID{Client: doc.ClientId, Clock: doc.Store.GetState(doc.ClientId)}, nil, // No left neighbor yet nil, nil, // No right neighbor yet nil, yarray, "", // Array, not map content.NewString("Hello"), ) item1.Integrate(tx, 0) // Create another item item2 := structs.NewItem( &utils.ID{Client: doc.ClientId, Clock: doc.Store.GetState(doc.ClientId)}, item1, item1.LastId, nil, nil, yarray, "", content.NewString(" World"), ) item2.Integrate(tx, 0) }, "init") // Query state stateVector := doc.Store.GetStateVector() for clientId, clock := range stateVector { fmt.Printf("Client %d has %d operations\n", clientId, clock) } ``` -------------------------------- ### NewItem Constructor Example Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-structs.md Demonstrates how to create a new Item instance with initial values for ID, neighbors, parent, and content. Use this to insert new data into a document. ```go item := structs.NewItem( &utils.ID{Client: 1, Clock: 0}, nil, nil, nil, nil, yarray, "", content.NewString("hello"), ) ``` -------------------------------- ### Basic Undo/Redo Example Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-undo-redo.md Demonstrates the fundamental usage of the UndoManager for tracking and reverting user edits. Ensure the UndoManager is initialized with the types to track and a maximum history size. ```go import ( "YJS-GO/types" "YJS-GO/utils" ) doc := utils.NewDoc(nil) ytext := doc.Get("text").(*types.YText) // Create undo manager undoMgr := utils.NewUndoManager( []*types.AbstractType{ytext}, 500, nil, // Track all origins ) // User edits doc.Transact(func(tx *utils.Transaction) { // Insert "Hello" // This creates a StackItem in undoMgr.UndoStack }, "user-input") // User edits again (batched if within 500ms) doc.Transact(func(tx *utils.Transaction) { // Insert " World" }, "user-input") // User clicks Undo if undoMgr.CanUndo() { undoMgr.Undo() // " World" is removed } // User clicks Undo again if undoMgr.CanUndo() { undoMgr.Undo() // "Hello" is removed } // User clicks Redo if undoMgr.CanRedo() { undoMgr.Redo() // "Hello" is restored } // Clean up undoMgr.Destroy() ``` -------------------------------- ### Example: Creating Items Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-structs.md Demonstrates how to create and integrate new items with string content into a Yjs document using the Yjs-Go library. ```APIDOC ## Example: Creating Items ### Description This example shows the process of creating a Yjs document, initiating a transaction, and then creating and integrating two new items with string content into a YArray. ### Code ```go import ( "YJS-GO/structs" "YJS-GO/structs/content" "YJS-GO/types" "YJS-GO/utils" ) doc := utils.NewDoc(nil) doc.Transact(func(tx *utils.Transaction) { yarray := doc.Get("items").(*types.YArray) // Create an item with string content item1 := structs.NewItem( &utils.ID{Client: doc.ClientId, Clock: doc.Store.GetState(doc.ClientId)}, nil, // No left neighbor yet nil, nil, // No right neighbor yet nil, yarray, "", // Array, not map content.NewString("Hello"), ) item1.Integrate(tx, 0) // Create another item item2 := structs.NewItem( &utils.ID{Client: doc.ClientId, Clock: doc.Store.GetState(doc.ClientId)}, item1, item1.LastId, nil, nil, yarray, "", content.NewString(" World"), ) item2.Integrate(tx, 0) }, "init") // Query state stateVector := doc.Store.GetStateVector() for clientId, clock := range stateVector { fmt.Printf("Client %d has %d operations\n", clientId, clock) } ``` ``` -------------------------------- ### Nested Transactions Example Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-transaction.md Demonstrates how to nest transactions. Only the outermost transaction triggers cleanup, simplifying resource management. ```go doc.Transact(func(tx *utils.Transaction) { // Outer transaction doc.Transact(func(tx2 *utils.Transaction) { // Inner transaction (same tx, no cleanup yet) }, "inner") // Cleanup happens here after outer transaction exits }, "outer") ``` -------------------------------- ### Create a new YDoc with options Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-ydoc.md Use NewDoc to create a new YDoc instance with optional configuration. Specify GC, GUID, and AutoLoad settings. ```go doc := utils.NewDoc(&utils.YDocOptions{ GC: true, GUID: "my-doc-id", AutoLoad: false, }) ``` -------------------------------- ### Encode Document State with UpdateEncoderV2 Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-encoding.md Example demonstrating how to create a V2 encoder, encode the document's state, and retrieve the binary update data. ```go encoder := utils.NewUpdateEncoderV2() // Encode document state doc.WriteStateAsUpdate(encoder, nil) // Get binary result updateData := encoder.ToArray() ``` -------------------------------- ### Full Sync Cycle Example Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-encoding.md Demonstrates a complete synchronization cycle between two clients (A and B) using Yjs update encoding and decoding. This involves exchanging state vectors and applying updates bidirectionally. ```go // Client A: Prepare update for Client B stateVectorB := decodeStateVector(clientBData) encoder := utils.NewUpdateEncoderV2() docA.WriteStateAsUpdate(encoder, stateVectorB) updateData := encoder.ToArray() // Send updateData to Client B // Client B: Apply update from A decoder := utils.NewUpdateDecoderV2(bytes.NewReader(updateData)) docB.Transact(func(tx *utils.Transaction) { utils.ReadStructs(decoder, tx, docB.Store) utils.ReadAndApplyDeleteSet(decoder, tx) }, "sync-from-a", false) // false = remote change // Client B: Send its changes to A stateVectorA := decodeStateVector(clientAData) encoder2 := utils.NewUpdateEncoderV2() docB.WriteStateAsUpdate(encoder2, stateVectorA) updateData2 := encoder2.ToArray() // Send updateData2 back to Client A docA.ApplyUpdateV2(updateData2, "sync-from-b", false) ``` -------------------------------- ### StructStore.GetItemCleanStart Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-structs.md Gets or splits an item at a specific ID within the transaction context. ```APIDOC #### GetItemCleanStart Get or split item at specific ID. ```go func (ss *StructStore) GetItemCleanStart(tx *Transaction, id *utils.ID) IAbstractStruct ``` **Parameters:** | Parameter | Type | Description | |-----------|------|-------------| | tx | *Transaction | Transaction context | | id | *utils.ID | Target ID | **Returns:** `IAbstractStruct` — Item at or after ID (may be split) **Behavior:** - If ID is in middle of item, splits it - Returns item at exact ID ``` -------------------------------- ### Integrate yjs-go with Database for State Persistence Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/README.md Provides an example of integrating yjs-go with a database to save document state after each transaction and load it on startup. Uses `AfterTransaction` and `ApplyUpdateV2`. ```go // Save state after each transaction doc.AfterTransaction = func(tx *utils.Transaction) { go func() { state := doc.EncodeStateAsUpdateV2(nil) saveToDatabase("document-id", state) }() } // Load on startup data := loadFromDatabase("document-id") if len(data) > 0 { doc.ApplyUpdateV2(data, "load", true) } ``` -------------------------------- ### Read and Apply DeleteSet Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-delete-set.md Example of decoding a DeleteSet from an update and applying the deletions within a transaction. Ensure the decoder is properly initialized. ```go decoder := utils.NewUpdateDecoderV2(reader) ds := utils.ReadDeleteSet(decoder) // Apply deletions doc.Transact(func(tx *utils.Transaction) { // Use ds to remove items }, "remote-deletion") ``` -------------------------------- ### StructStore GetItemCleanStart Method Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-structs.md Gets or splits an item at a specific ID within the StructStore. If the ID is in the middle of an item, it splits the item. Returns the item at or after the specified ID. ```go func (ss *StructStore) GetItemCleanStart(tx *Transaction, id *utils.ID) IAbstractStruct ``` -------------------------------- ### Get Format Key Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Retrieves the attribute key from a Format object. ```go func (f *Format) GetKey() string ``` -------------------------------- ### Garbage Collection Example Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-delete-set.md Demonstrates how to enable and utilize garbage collection for deleted items in a Yjs document. Ensure GC is enabled and a filter is provided to specify which deleted items should be garbage collected. ```go doc := &utils.YDoc{ GC: true, GCFilter: utils.DefaultPredicate, // GC all deleted items Store: &utils.StructStore{}, } // After operations and deletions doc.Transact(func(tx *utils.Transaction) { // Deletions happen here }, "changes") // During cleanup (automatic): // 1. DeleteSet is created from tx.DeleteSet // 2. ds.SortAndMergeDeleteSet() // 3. ds.TryGcDeleteSet(store, gcFilter) // Memory freed // 4. ds.TryMergeDeleteSet(store) ``` -------------------------------- ### Clone Document Options with New GUID Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-ydoc.md Creates a deep copy of the YDoc options, ensuring that the new copy has a unique GUID. This is useful for creating independent document configurations. ```go func (d *YDoc) CloneOptionsWithNewGuid() *YDocOptions ``` -------------------------------- ### Creating YDoc with Configurable Options Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/configuration.md This Go code illustrates how to create a Yjs document with custom options, such as garbage collection and GUID settings, by loading configuration from a map. This approach allows externalizing configuration from environment variables. ```go func createDoc(configMap map[string]interface{}) *utils.YDoc { options := &utils.YDocOptions{} if gc, ok := configMap["gc"].(bool); ok { options.GC = gc } if guid, ok := configMap["guid"].(string); ok { options.GUID = guid } return utils.NewDoc(options) } // Load from JSON, YAML, or env vars configMap := loadConfigFromFile("config.json") doc := createDoc(configMap) ``` -------------------------------- ### Send Encoded Update Data Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-encoding.md Example showing how to obtain the binary update data using ToArray() and prepare it for network transmission. ```go data := encoder.ToArray() // Send over network networkSend(data) ``` -------------------------------- ### Get or create a shared type by name Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-ydoc.md Use the Get method to retrieve an existing shared type (like YArray or YMap) by its key, or create it if it doesn't exist. ```go // Get or create an array type items := doc.Get("items").(*types.YArray) // Get or create a map type data := doc.Get("data").(*types.YMap) ``` -------------------------------- ### Execute a Transaction Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-transaction.md Example of performing operations within a transaction. Ensure operations are within the callback function provided to `YDoc.Transact()`. ```go doc.Transact(func(tx *utils.Transaction) { // Perform operations here yarray := doc.Get("items").(*types.YArray) // ... }, "source") ``` -------------------------------- ### Get Content from Any Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md The GetContent method retrieves the original, unwrapped value stored within the Any content type. ```go func (a *Any) GetContent() any ``` -------------------------------- ### Get Format Value Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Retrieves the attribute value from a Format object. ```go func (f *Format) GetValue() any ``` -------------------------------- ### IContentExt Interface Definition Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Defines the interface for all content types, specifying methods for getting content, copying, merging, and writing. ```go type IContentExt interface { GetContent() any Copy() IContentExt GetLength() uint64 MergeWith(other IContentExt) bool Write(encoder utils.IUpdateEncoder) GetRef() uint } ``` -------------------------------- ### YDocOptions Struct Definition Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-ydoc.md Defines configuration options for YDoc initialization. These options control aspects like garbage collection, document GUID, metadata, and auto-loading behavior. ```go type YDocOptions struct { GC bool GUID string Meta map[string]string AutoLoad bool } ``` -------------------------------- ### Create New Format Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Use this constructor to create format content. Specify the attribute key and its value. ```go func NewFormat(key string, value any) *Format ``` ```go c1 := content.NewFormat("bold", true) c2 := content.NewFormat("color", "#ff0000") c3 := content.NewFormat("size", 16) ``` -------------------------------- ### Cloning Yjs Document with New GUID Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/quick-reference.md Create a clone of a Yjs document that has a new, unique GUID. This ensures the cloned document is independent. ```go opts := doc.CloneOptionsWithNewGuid() // opts.GUID is now different from doc.GUID ``` -------------------------------- ### Slice YArrayBase Content Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-types.md Extracts a slice of values from the YArrayBase between the specified start and end indices. Negative start indices wrap around. ```go func (b *YArrayBase) InternalSlice(start, end uint64) []any ``` ```go values := yarray.InternalSlice(0, 10) ``` -------------------------------- ### YArrayBase Method: InternalSlice Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-types.md Extracts a slice of values from the YArrayBase within a specified start and end index. Negative start indices wrap around. ```APIDOC ## InternalSlice Extract values from start to end index. ```go func (b *YArrayBase) InternalSlice(start, end uint64) []any ``` ### Parameters: | Parameter | Type | Description | |-----------|------|-------------| | start | uint64 | Start index (negative wraps) | | end | uint64 | End index (exclusive) | **Returns:** `[]any` — Values in range **Example:** ```go values := yarray.InternalSlice(0, 10) ``` ``` -------------------------------- ### Set Custom GUID for YDoc Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/configuration.md Assign a custom globally unique identifier to a YDoc. Use unique GUIDs for each logical document to prevent conflicts during synchronization. ```go doc2 := utils.NewDoc(&utils.YDocOptions{ GUID: "my-custom-id", }) ``` -------------------------------- ### Create New Doc Instance Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Constructor for creating a new Doc instance. Requires an initialized utils.YDoc. ```go func NewDoc(doc *utils.YDoc) *Doc ``` -------------------------------- ### Create New Binary Content Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Use this constructor to create a new Binary content wrapper with a byte slice. ```go func NewBinary(content []byte) *Binary ``` ```go c := content.NewBinary([]byte{0x01, 0x02, 0x03}) ``` -------------------------------- ### Create New String Content Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Use this constructor to create a new String content wrapper with a given string value. ```go func NewString(value string) *String ``` ```go c := content.NewString("Hello, World!") ``` -------------------------------- ### Get Subdocument from Doc Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Method to retrieve the underlying utils.YDoc from a Doc wrapper. ```go func (d *Doc) GetDoc() *utils.YDoc ``` -------------------------------- ### GetLength() Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-structs.md Gets the logical length of an Item, representing its character count or array length. ```APIDOC ## GetLength() ### Description Get item's logical length. ### Returns `uint64` — Character count, array length, etc. ``` -------------------------------- ### Get String Value Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Retrieves the stored string value from a String content object. ```go func (s *String) GetString() string ``` -------------------------------- ### Any Method: GetLength Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Gets the item count of the Any content, which is 1 for scalars, or the length/size for arrays/maps. ```APIDOC ## GetLength Get item count (1 for scalar, array length, map size). ### Signature ```go func (a *Any) GetLength() uint64 ``` ``` -------------------------------- ### Create a new YDoc with explicit options Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-ydoc.md Use NewDocWithOption to create a YDoc, requiring a configuration object. ```go func NewDocWithOption(options *YDocOptions) *YDoc ``` -------------------------------- ### Get Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-ydoc.md Retrieves a shared type from the Yjs document by its key. If the type does not exist, it will be created. ```APIDOC ## Get ### Description Retrieve or create a shared type by name. ### Method ```go func (d *YDoc) Get(key string) *types.AbstractType ``` ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters - **key** (string) - Description: Name of the shared type (e.g., "items", "text") ### Request Example ```go // Get or create an array type items := doc.Get("items").(*types.YArray) // Get or create a map type data := doc.Get("data").(*types.YMap) ``` ### Response #### Success Response - **Return Value**: *types.AbstractType - Shared type, creating if needed ### Response Example N/A ``` -------------------------------- ### Get Operation Identifier Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-structs.md Retrieves the unique identifier for an operation, represented as a (Client, Clock) pair. ```go func (i *Item) ID() *utils.ID ``` -------------------------------- ### Get Item Logical Length Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-structs.md Retrieves the logical length of an item, such as character count or array length. ```go func (i *Item) GetLength() uint64 ``` -------------------------------- ### Get Length of Any Content Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md GetLength returns the item count, which is 1 for scalars, or the array/map size for collections. ```go func (a *Any) GetLength() uint64 ``` -------------------------------- ### Enable and Configure Garbage Collection Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/quick-reference.md Set doc.GC to true to enable garbage collection. Customize GC behavior using doc.GCFilter. GC occurs automatically during transaction cleanup. ```go doc.GC = true // Enable doc.GCFilter = func(item *structs.Item) bool { return !item.Keep // GC unless marked Keep } // GC happens during transaction cleanup automatically ``` -------------------------------- ### Listen to Document Changes Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/quick-reference.md Register callbacks to be executed before or after transactions to observe changes and their origins. ```go doc.BeforeTransaction = func(tx *utils.Transaction) { log.Println("Change coming:", tx.Origin) } doc.AfterTransaction = func(tx *utils.Transaction) { log.Println("Change applied") } ``` -------------------------------- ### Configure AutoLoad for YDoc Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/configuration.md Control document initialization behavior. Set AutoLoad to true for automatic loading on access, or false for manual loading. ```go // AutoLoad: false (default) doc := utils.NewDoc(&utils.YDocOptions{ AutoLoad: false, // Manual loading required }) // doc.ShouldLoad = false // AutoLoad: true doc := utils.NewDoc(&utils.YDocOptions{ AutoLoad: true, // Auto-load on access }) // doc.ShouldLoad = true ``` -------------------------------- ### Configure YDoc Options in Go Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/quick-reference.md Set up YDoc options for garbage collection, unique IDs, metadata, and auto-loading behavior before creating a new document. ```go options := &utils.YDocOptions{ GC: true, // Garbage collect GUID: "doc-id", // Unique ID Meta: map[string]string{}, // Metadata AutoLoad: false, // Auto-load } doc := utils.NewDoc(options) ``` -------------------------------- ### Create and Integrate a New Item Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/quick-reference.md Use structs.NewItem to create a new item with specified ID, neighbors, parent, and content. Integrate the item into the document using item.Integrate. ```go item := structs.NewItem( &utils.ID{Client: id, Clock: clock}, nil, // left neighbor nil, // left origin nil, // right neighbor nil, // right origin parent, // AbstractType "", // parentSub (map key or "") content, // IContentExt ) item.Integrate(transaction, 0) ``` -------------------------------- ### Get Shared Types from Document Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/quick-reference.md Retrieve shared types like YArray, YMap, or YText from a Yjs document by their key. ```go yarray := doc.Get("items").(*types.YArray) ymap := doc.Get("data").(*types.YMap) ytext := doc.Get("text").(*types.YText) ``` -------------------------------- ### NewStackItem Constructor Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-transaction.md Creates a new StackItem for use in undo management. Requires delete set, before state, and after state. ```go func NewStackItem(ds *DeleteSet, BeforeState map[uint64]uint64, AfterState map[uint64]uint64, ...) *StackItem ``` -------------------------------- ### Create a Yjs Document Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/quick-reference.md Instantiate a new Yjs document with optional configuration for garbage collection and a unique identifier. ```go doc := utils.NewDoc(&utils.YDocOptions{ GC: true, GUID: "unique-id", }) ``` -------------------------------- ### Create NewJson Instance Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Creates a new Json content wrapper with the provided array of values. Use this to initialize JSON data. ```go func NewJson(data []any) *Json ``` ```go c := content.NewJson([]any{1, "hello", 3.14, true}) ``` -------------------------------- ### Create New Embed Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Use this constructor to create embedded content. It accepts any type of object to be embedded. ```go func NewEmbed(embed any) *Embed ``` ```go c := content.NewEmbed(map[string]any{"type": "image", "src": "url"}) ``` -------------------------------- ### Add Deletion to DeleteSet Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-delete-set.md Registers a deletion with client ID, starting clock, and length. Does not merge or sort; call SortAndMergeDeleteSet after bulk additions. ```go func (ds *DeleteSet) Add(client, clock, length uint64) ``` ```go ds := &utils.DeleteSet{ Clients: make(map[uint64][]*utils.DeleteItem), } ds.Add(clientA, 10, 5) // Delete ops 10-14 from clientA ds.Add(clientA, 20, 3) // Delete ops 20-22 from clientA ``` -------------------------------- ### Create Items with Different Content Types Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Demonstrates creating Yjs items with various content types such as strings, integers, binary data, and formatting. Ensure you have the necessary imports for structs, types, and utils. ```go // Creating items with different content types import ( "YJS-GO/structs/content" "YJS-GO/types" "YJS-GO/utils" ) doc := utils.NewDoc(nil) doc.Transact(func(tx *utils.Transaction) { array := doc.Get("items").(*types.YArray) // Insert different content types c1 := content.NewString("Hello") c2 := content.NewAny(42) c3 := content.NewBinary([]byte{1, 2, 3}) c4 := content.NewFormat("bold", true) // Items would be created with these contents // (wrapped in structs.Item) }, "init") ``` -------------------------------- ### UndoManager Constructor Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/configuration.md Initialize the UndoManager by specifying the types to track, the capture timeout in milliseconds, and an array of origins to track. ```go undoMgr := utils.NewUndoManager( []*types.AbstractType{ytext, yarray}, // Types to track 500, // Capture timeout (ms) []any{"user-input"}, // Tracked origins ) ``` -------------------------------- ### Create New DSEncoderV2 Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-encoding.md Creates a new instance of the DSEncoderV2. ```go func NewDsEncoderV2() *DSEncoderV2 ``` -------------------------------- ### Default WebSocket Upgrader Configuration Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/configuration.md This Go code shows the default configuration for a WebSocket upgrader, including buffer sizes and a permissive origin check. It's suitable for development but requires customization for production. ```go // Default configuration in server.go var upgrade = websocket.Upgrader{ ReadBufferSize: 4096, // Read buffer size WriteBufferSize: 1024, // Write buffer size CheckOrigin: func(r *http.Request) bool { return true // Allow all origins (customize as needed) }, } // Server starts on port 9001 // Address: "9001" (implicitly localhost) ``` -------------------------------- ### Create New YArrayBase Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-types.md Creates and initializes a new YArrayBase instance with search markers. This is the constructor for YArrayBase. ```go func NewYArrayBase() *YArrayBase ``` -------------------------------- ### Get Delta Representation of YText Changes Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-types.md Retrieves the delta representation of changes made to the YText. Computes delta lazily on first call and includes formatting changes. ```go func (yte YTextEvent) GetDelta() []*utils.Delta ``` ```go deltas := textEvent.GetDelta() for _, op := range deltas { if op.Insert != "" { // Handle insert } else if op.Delete > 0 { // Handle delete } } ``` -------------------------------- ### String Constructor: NewString Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Creates a new String content wrapper with the provided string value. ```APIDOC ## NewString ### Description Create string content. ### Signature ```go func NewString(value string) *String ``` ### Parameters #### Parameters - **value** (string) - String value ### Returns - `*String` — Content wrapper ### Example ```go c := content.NewString("Hello, World!") ``` ``` -------------------------------- ### Any Method: Copy Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Creates a shallow copy of the Any content type. ```APIDOC ## Copy Create a shallow copy. ### Signature ```go func (a *Any) Copy() IContentExt ``` ### Returns - **`IContentExt`** - New Any with copied value ``` -------------------------------- ### DeleteSet and DeleteItem Structs Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-delete-set.md Defines the structure for DeleteSet, which maps client IDs to deleted item ranges, and DeleteItem, representing a specific deleted range with a starting clock and length. ```go type DeleteSet struct { Clients map[uint64][]*DeleteItem } type DeleteItem struct { Clock uint64 Length uint64 } ``` -------------------------------- ### Good: Fast operations in BeforeTransaction Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/configuration.md Implement fast operations within the `BeforeTransaction` hook. Avoid blocking operations like network I/O or database queries to maintain performance. ```go // ✓ Good: Fast operations only doc.BeforeTransaction = func(tx *utils.Transaction) { startTime := time.Now() tx.Meta["startTime"] = startTime } ``` -------------------------------- ### Add Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-delete-set.md Registers a deletion with the DeleteSet. This method adds a deletion range specified by client ID, starting clock, and length. It does not perform merging or sorting, which should be handled by calling `SortAndMergeDeleteSet` afterwards. ```APIDOC ## Add ### Description Registers a deletion with the DeleteSet. This method adds a deletion range specified by client ID, starting clock, and length. It does not perform merging or sorting, which should be handled by calling `SortAndMergeDeleteSet` afterwards. ### Method `func (ds *DeleteSet) Add(client, clock, length uint64)` ### Parameters #### Path Parameters - **client** (uint64) - Required - Client ID of deleted operations - **clock** (uint64) - Required - Starting clock value - **length** (uint64) - Required - Number of operations deleted ### Request Example ```go ds := &utils.DeleteSet{ Clients: make(map[uint64][]*utils.DeleteItem), } ds.Add(clientA, 10, 5) // Delete ops 10-14 from clientA ds.Add(clientA, 20, 3) // Delete ops 20-22 from clientA ``` ``` -------------------------------- ### Create NewType Instance Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Creates a new Type content wrapper for a shared type reference. Use this to associate a shared type with content. ```go func NewType(v any) *Type ``` ```go yarray := &types.YArray{} c := content.NewType(yarray) ymap := &types.YMap{} c2 := content.NewType(ymap) ``` -------------------------------- ### Encode the document's state vector Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-ydoc.md Use EncodeStateVectorV2 to get a binary representation of the document's state vector, which tracks logical clocks per client for efficient syncing. ```go sv := doc.EncodeStateVectorV2() // Send to another client for diff calculation ``` -------------------------------- ### Set and Access Transaction Origin Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-transaction.md Demonstrates how to set a custom origin string when initiating a transaction and how to access it within the transaction or in observer hooks. This is useful for distinguishing between local user input and network changes. ```go doc.Transact(func(tx *utils.Transaction) { fmt.Printf("Origin: %v\n", tx.Origin) // "user-input" }, "user-input") // In observer hook: doc.BeforeTransaction = func(tx *utils.Transaction) { if tx.Origin == "user-input" { // Local user change } else if tx.Origin == "network" { // Remote change } } ``` -------------------------------- ### Define DeleteSet and DeleteItem Structs Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/types.md Tracks deleted operation ranges. DeleteSet contains a map of client IDs to slices of DeleteItems, where each DeleteItem specifies a start clock and the number of deleted operations. ```go type DeleteSet struct { Clients map[uint64][]*DeleteItem } ``` ```go type DeleteItem struct { Clock uint64 // Start clock Length uint64 // Number of deleted ops } ``` ```go // Client 1: deleted ops 10-14 and 20-24 ds.Clients[1] = []*DeleteItem{ {Clock: 10, Length: 5}, {Clock: 20, Length: 5}, } ``` -------------------------------- ### Binary Constructor: NewBinary Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Creates a new Binary content wrapper with the provided byte slice. ```APIDOC ## NewBinary ### Description Create binary content. ### Signature ```go func NewBinary(content []byte) *Binary ``` ### Parameters #### Parameters - **content** ([]byte) - Binary data ### Returns - `*Binary` — Content wrapper ### Example ```go c := content.NewBinary([]byte{0x01, 0x02, 0x03}) ``` ``` -------------------------------- ### Constructor for StackItem Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-undo-redo.md Creates a new StackItem to be used in the undo/redo stack. It requires the delete set and the state vectors before and after the operation. ```go func NewStackItem( ds *DeleteSet, beforeState map[uint64]uint64, afterState map[uint64]uint64, ) *StackItem ``` -------------------------------- ### Create Any Content Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Use NewAny to create an Any content wrapper for JSON-serializable data. Supports maps, slices, and primitive types. ```go c := content.NewAny(map[string]any{"name": "Alice", "age": 30}) c2 := content.NewAny([]any{1, 2, 3}) c3 := content.NewAny("hello") ``` -------------------------------- ### Create New DsDecoderV2WithEmpty Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-encoding.md Creates a new, empty delete-set decoder. ```go func NewDsDecoderV2WithEmpty() *DSDecoderV2 ``` -------------------------------- ### Any Constructor: ReadAny Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Decodes an Any content type from an update decoder. ```APIDOC ## ReadAny Decode Any from update decoder. ### Signature ```go func ReadAny(decoder utils.IUpdateDecoder) (*Any, error) ``` ### Returns - **`*Any`** - Decoded content - **`error`** - Error during decoding ``` -------------------------------- ### Create DeleteSet from StructStore Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-delete-set.md Populates the DeleteSet by scanning a StructStore and extracting all deleted item ranges across all clients. ```go func (ds *DeleteSet) CreateDeleteSetFromStructStore(ss *StructStore) ``` ```go ds.CreateDeleteSetFromStructStore(ss) ``` -------------------------------- ### Implement Yjs Sync Pattern in Go Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/quick-reference.md A four-step process for synchronizing Yjs documents between clients: exchanging state vectors, encoding missing operations, transferring updates, and applying remote changes. ```go // 1. Exchange state vectors localSV := doc.EncodeStateVectorV2() remoteSV := receiveFromNetwork() // 2. Encode missing operations missingOps := doc.EncodeStateAsUpdateV2(remoteSV) // 3. Send and receive sendToNetwork(missingOps) theirOps := receiveFromNetwork() // 4. Apply remote changes doc.ApplyUpdateV2(theirOps, "sync", false) ``` -------------------------------- ### Create Yjs Types with Content Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/quick-reference.md Demonstrates creating various content types within a Yjs document, including strings, binary data, JSON, embedded objects, formats, type references, and subdocuments. ```go yarray := doc.Get("items").(*types.YArray) doc.Transact(func(tx *utils.Transaction) { // String c1 := content.NewString("hello") // Binary c2 := content.NewBinary([]byte{1, 2, 3}) // JSON c3 := content.NewAny(map[string]any{"x": 1}) // Embed c4 := content.NewEmbed(obj) // Format c5 := content.NewFormat("bold", true) // Type reference c6 := content.NewType(&types.YArray{}) // Subdocument c7 := content.NewDoc(subdoc) }, "init") ``` -------------------------------- ### Configure UndoManager to Include/Exclude Own Changes Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-undo-redo.md Set the `IncludeOwnChanges` property to `true` to track all changes, including those made by the current user. Set it to `false` to only track remote changes. ```go undoMgr := utils.NewUndoManager([]*types.AbstractType{ytext}, 500, nil) // Track all changes including own undoMgr.IncludeOwnChanges = true doc.Transact(func(tx *utils.Transaction) { // ... }, "user-input") // This can be undone // Don't track own changes (only remote) undoMgr.IncludeOwnChanges = false doc.Transact(func(tx *utils.Transaction) { // ... }, "user-input") // This cannot be undone // Only remote changes are tracked ``` -------------------------------- ### Any Constructor: NewAny Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md Creates a new Any content type, which can hold any JSON-serializable value. ```APIDOC ## NewAny Create an Any content. ### Signature ```go func NewAny(content any) *Any ``` ### Parameters - **content** (any) - Required - JSON-serializable value ### Returns - **`*Any`** - Content wrapper ### Example ```go c := content.NewAny(map[string]any{"name": "Alice", "age": 30}) c2 := content.NewAny([]any{1, 2, 3}) c3 := content.NewAny("hello") ``` ``` -------------------------------- ### NewStackItem Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-undo-redo.md Constructor for creating a new StackItem, which represents a single undo/redo operation. ```APIDOC ## NewStackItem Create a stack item. ### Parameters #### Path Parameters - **ds** (*DeleteSet) - Required - Deletions in this step - **beforeState** (map[uint64]uint64) - Required - Clocks before - **afterState** (map[uint64]uint64) - Required - Clocks after ### Returns - ***StackItem** — Entry for undo/redo stack ``` -------------------------------- ### Copy Any Content Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-content.md The Copy method creates a shallow copy of the Any content, returning a new IContentExt interface. ```go func (a *Any) Copy() IContentExt ``` -------------------------------- ### Enable Garbage Collection in YDoc Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/README.md Demonstrates how to enable garbage collection for deleted items in a YDoc. You can also provide a custom filter function to control which deleted items are eligible for garbage collection. ```go doc := utils.NewDoc(&utils.YDocOptions{ GC: true, // Enable GC }) doc.GCFilter = func(item *structs.Item) bool { return true // GC all deleted items } ``` -------------------------------- ### Real-time Collaboration Synchronization Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/README.md Demonstrates synchronizing Yjs documents between two peers. First, Peer 1 sends its entire state to Peer 2. Then, Peer 1 modifies its document and sends only the subsequent updates to Peer 2. ```go // Peer 1 doc1 := utils.NewDoc(nil) ytext1 := doc1.Get("text").(*types.YText) // Peer 2 doc2 := utils.NewDoc(nil) ytext2 := doc2.Get("text").(*types.YText) // Sync: Peer 1 → Peer 2 update := doc1.EncodeStateAsUpdateV2(nil) doc2.ApplyUpdateV2(update, "sync-from-1", false) // Peer 1 modifies doc1.Transact(func(tx *utils.Transaction) { // ... insert text ... }, "user-input") // Sync: Peer 1 → Peer 2 update := doc1.EncodeStateAsUpdateV2(doc2.EncodeStateVectorV2()) doc2.ApplyUpdateV2(update, "sync", false) // Now both peers have same content, fully synchronized ``` -------------------------------- ### YArrayBase Constructor: NewYArrayBase Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-types.md Creates a new YArrayBase instance, initializing its internal structures including search markers. ```APIDOC ## NewYArrayBase Create a new array base with search markers. ```go func NewYArrayBase() *YArrayBase ``` **Returns:** `*YArrayBase` — Initialized array ``` -------------------------------- ### Create New UpdateDecoderV2 Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-encoding.md Creates a new V2 update decoder that reads from the provided io.Reader. ```go func NewUpdateDecoderV2(reader io.Reader) *UpdateDecoderV2 ``` -------------------------------- ### Enable Garbage Collection in yjs-go Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/README.md Shows how to enable garbage collection for memory efficiency in yjs-go. This process removes deleted items during cleanup, with a potential performance trade-off. ```go doc.GC = true // Removes deleted items during cleanup ``` -------------------------------- ### Configure Yjs Undo Manager Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/configuration.md Set up the undo manager with reasonable defaults for debounce time and filtering user actions. For collaborative editing, configure it to include own changes. ```go // Reasonable defaults undoMgr := utils.NewUndoManager( []*types.AbstractType{ytext}, 300, // 300ms debounce []any{"user-input"}, // Only user actions ) // For collaborative editing undoMgr.IncludeOwnChanges = true // Undo all changes ``` -------------------------------- ### NewDoc Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-ydoc.md Creates a new Yjs document instance with optional configuration. This is a convenient constructor for initializing a document with default or custom settings. ```APIDOC ## NewDoc ### Description Create a new YDoc with optional configuration. ### Method ```go func NewDoc(options *YDocOptions) *YDoc ``` ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters - **options** (*YDocOptions) - Optional - Configuration for the document ### Request Example ```go doc := utils.NewDoc(&utils.YDocOptions{ GC: true, GUID: "my-doc-id", AutoLoad: false, }) ``` ### Response #### Success Response - **Return Value**: *YDoc - Initialized document instance ### Response Example N/A ``` -------------------------------- ### Create YMapEvent Constructor Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-types.md Constructor for creating a YMapEvent, used to signal map changes. ```go func NewYMapEvent(ymap *YMap, t *utils.Transaction, subs map[string]struct{}) *YMapEvent ``` -------------------------------- ### Create New DsDecoderV2 Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-encoding.md Creates a new delete-set decoder using a provided io.Reader as the source. ```go func NewDsDecoderV2(reader io.Reader) *DSDecoderV2 ``` -------------------------------- ### Implement Undo/Redo Functionality Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/README.md Sets up an UndoManager to track changes for undo and redo operations on specified shared types. It allows controlling the debounce time and associating origins with actions. ```go undoMgr := utils.NewUndoManager( []*types.AbstractType{ytext, yarray}, 500, // 500ms debounce []any{"user-input"}, ) // User clicks Undo if undoMgr.CanUndo() { undoMgr.Undo() } // User clicks Redo if undoMgr.CanRedo() { undoMgr.Redo() } ``` -------------------------------- ### Check Redo Availability Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-undo-redo.md Determines if there are any actions available to redo. Use this before calling Redo() to prevent errors. ```go func (um *UndoManager) CanRedo() bool ``` -------------------------------- ### NewDocWithOption Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-ydoc.md Creates a new Yjs document instance with explicitly provided options. Use this when you need to ensure specific configurations are applied. ```APIDOC ## NewDocWithOption ### Description Create a new YDoc with explicit options. ### Method ```go func NewDocWithOption(options *YDocOptions) *YDoc ``` ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters - **options** (*YDocOptions) - Required - Configuration object ### Request Example N/A ### Response #### Success Response - **Return Value**: *YDoc - Initialized document ### Response Example N/A ``` -------------------------------- ### Synchronize with a Remote Client Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/README.md A step-by-step process for synchronizing Yjs documents between clients over a network. It involves exchanging state vectors and applying updates to ensure consistency. ```go // Step 1: Get remote state vector remoteStateVectorData := receiveFromNetwork() // Step 2: Encode only missing operations updateData := doc.EncodeStateAsUpdateV2(remoteStateVectorData) // Step 3: Send to remote sendToNetwork(updateData) // Step 4: Receive remote changes theirUpdateData := receiveFromNetwork() // Step 5: Apply remote changes doc.ApplyUpdateV2(theirUpdateData, "network-sync", false) ``` -------------------------------- ### NewUpdateEncoderV2 Constructor Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/api-reference-encoding.md Creates a new instance of the V2 update encoder. Use this to begin encoding document state or updates. ```go func NewUpdateEncoderV2() *UpdateEncoderV2 ``` -------------------------------- ### Persistence: Save and Load Yjs Document Source: https://github.com/averyyan/yjs-go/blob/main/_autodocs/README.md Shows how to save the current state of a Yjs document to disk and load it back. The document state is encoded as an update and written to a file, then read and applied to a new document. ```go // Save to disk doc := utils.NewDoc(nil) // ... make changes ... state := doc.EncodeStateAsUpdateV2(nil) os.WriteFile("doc.yjs", state, 0644) // Load from disk data, _ := os.ReadFile("doc.yjs") doc2 := utils.NewDoc(nil) doc2.ApplyUpdateV2(data, "load", true) ```