CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-yjs

Conflict-free Replicated Data Type (CRDT) framework for real-time collaborative applications

Overview
Eval results
Files

document-management.mddocs/

Document Management

Core document functionality for creating, managing, and synchronizing collaborative documents. The Doc class serves as the central container that manages shared types and handles synchronization state.

Capabilities

Doc Class

The main document class that serves as the root container for all shared types in a collaborative session.

/**
 * Main document class that manages shared types and synchronization
 */
class Doc {
  constructor(options?: DocOpts);
  
  /** Unique client identifier for this document instance */
  readonly clientID: number;
  
  /** Globally unique identifier for this document */
  readonly guid: string;
  
  /** Collection identifier for grouping related documents */
  readonly collectionid: string | null;
  
  /** Whether garbage collection is enabled */
  readonly gc: boolean;
  
  /** Map of shared types by name */
  readonly share: Map<string, AbstractType<YEvent<any>>>;
  
  /** Whether the document has been loaded */
  readonly isLoaded: boolean;
  
  /** Whether the document is synchronized with remote state */
  readonly isSynced: boolean;
  
  /** Whether the document has been destroyed */
  readonly isDestroyed: boolean;
  
  /** Promise that resolves when document is loaded */
  readonly whenLoaded: Promise<Doc>;
  
  /** Promise that resolves when document is synced */
  readonly whenSynced: Promise<void>;
}

interface DocOpts {
  /** Custom client ID (auto-generated if not provided) */
  clientID?: number;
  
  /** Custom document GUID (auto-generated if not provided) */
  guid?: string;
  
  /** Collection identifier for grouping documents */
  collectionid?: string | null;
  
  /** Enable/disable garbage collection (default: true) */
  gc?: boolean;
  
  /** Custom garbage collection filter function */
  gcFilter?: (item: Item) => boolean;
  
  /** Custom metadata for the document */
  meta?: any;
  
  /** Whether to automatically load the document */
  autoLoad?: boolean;
  
  /** Whether the document should be loaded */
  shouldLoad?: boolean;
}

Usage Examples:

import * as Y from "yjs";

// Create a basic document
const doc = new Y.Doc();

// Create document with options
const docWithOptions = new Y.Doc({
  clientID: 12345,
  guid: "my-document-id",
  gc: false, // Disable garbage collection
  meta: { author: "Alice", version: "1.0" }
});

Getting Shared Types

Retrieve or create shared types within the document.

/**
 * Get or create a shared type by name and constructor
 * @param name - Name of the shared type
 * @param TypeConstructor - Constructor function for the type
 * @returns Instance of the shared type
 */
get<Type>(name: string, TypeConstructor?: Type): InstanceType<Type>;

/**
 * Get or create a YArray with the given name
 * @param name - Name of the array (default: random)
 * @returns YArray instance
 */
getArray<T>(name?: string): YArray<T>;

/**
 * Get or create a YText with the given name
 * @param name - Name of the text (default: random)
 * @returns YText instance
 */
getText(name?: string): YText;

/**
 * Get or create a YMap with the given name
 * @param name - Name of the map (default: random)
 * @returns YMap instance
 */
getMap<T>(name?: string): YMap<T>;

/**
 * Get or create a YXmlElement with the given name
 * @param name - Name of the element (default: random)
 * @returns YXmlElement instance
 */
getXmlElement<KV = { [key: string]: any }>(name?: string): YXmlElement<KV>;

/**
 * Get or create a YXmlFragment with the given name
 * @param name - Name of the fragment (default: random)
 * @returns YXmlFragment instance
 */
getXmlFragment(name?: string): YXmlFragment;

Usage Examples:

import * as Y from "yjs";

const doc = new Y.Doc();

// Get shared types by name
const users = doc.getArray<User>("users");
const settings = doc.getMap<any>("settings");
const content = doc.getText("content");
const xmlDoc = doc.getXmlFragment("document");

// Using generic get method
const customArray = doc.get("custom", Y.Array);

Transaction Management

Execute multiple operations atomically within a single transaction.

/**
 * Execute a function within a transaction context
 * @param f - Function to execute within transaction
 * @param origin - Optional origin identifier for the transaction
 * @returns Result of the function execution
 */
transact<T>(f: (transaction: Transaction) => T, origin?: any): T;

Usage Examples:

import * as Y from "yjs";

const doc = new Y.Doc();
const yarray = doc.getArray("items");
const ymap = doc.getMap("metadata");

// Execute multiple operations in a single transaction
doc.transact((transaction) => {
  yarray.push(["item1", "item2"]);
  ymap.set("lastModified", new Date().toISOString());
  ymap.set("itemCount", yarray.length);
}, "batch-update");

// The origin can be used to identify the source of changes
doc.transact(() => {
  yarray.delete(0, 1);
}, { type: "user-action", userId: "alice" });

Document Lifecycle

Control document loading, synchronization, and cleanup.

/**
 * Request that the document be loaded
 */
load(): void;

/**
 * Get all subdocuments contained within this document
 * @returns Set of subdocuments
 */
getSubdocs(): Set<Doc>;

/**
 * Get GUIDs of all subdocuments
 * @returns Set of subdocument GUIDs
 */
getSubdocGuids(): Set<string>;

/**
 * Convert document to JSON (deprecated - use individual type toJSON methods)
 * @returns JSON representation of shared types
 */
toJSON(): { [key: string]: any };

/**
 * Destroy the document and clean up resources
 */
destroy(): void;

Usage Examples:

import * as Y from "yjs";

const doc = new Y.Doc();

// Load document
doc.load();

// Wait for document to be loaded
await doc.whenLoaded;

// Wait for synchronization
await doc.whenSynced;

// Check subdocuments
const subdocs = doc.getSubdocs();
console.log(`Found ${subdocs.size} subdocuments`);

// Clean up when done
doc.destroy();

Document Events

Observe document-level events for loading, synchronization, and subdocument changes.

/**
 * Document event types
 */
interface DocEvents {
  load: (doc: Doc) => void;
  sync: (doc: Doc, isSynced: boolean) => void;
  beforeTransaction: (transaction: Transaction, doc: Doc) => void;
  afterTransaction: (transaction: Transaction, doc: Doc) => void;
  beforeObserverCalls: (transaction: Transaction, doc: Doc) => void;
  afterObserverCalls: (transaction: Transaction, doc: Doc) => void;
  subdocs: (doc: Doc, changes: { loaded: Set<Doc>; added: Set<Doc>; removed: Set<Doc> }) => void;
  destroy: (doc: Doc) => void;
}

Usage Examples:

import * as Y from "yjs";

const doc = new Y.Doc();

// Listen for document events
doc.on("load", () => {
  console.log("Document loaded");
});

doc.on("sync", (isSynced) => {
  console.log("Sync status changed:", isSynced);
});

doc.on("subdocs", ({ loaded, added, removed }) => {
  console.log("Subdocuments changed:", { loaded, added, removed });
});

doc.on("destroy", () => {
  console.log("Document destroyed");
});

Advanced Document Features

Advanced functionality for specialized use cases.

/**
 * Get current state vector of the document
 * @param doc - Document to get state from
 * @returns State vector as Map
 */
function getState(doc: Doc): Map<number, number>;

/**
 * Attempt garbage collection on the document
 * @param ds - Delete set to garbage collect
 * @param store - Struct store
 * @param gcFilter - Filter function for garbage collection
 */
function tryGc(ds: DeleteSet, store: StructStore, gcFilter: (item: Item) => boolean): void;

Usage Examples:

import * as Y from "yjs";

const doc = new Y.Doc();

// Get current document state
const state = Y.getState(doc);
console.log("Document state:", state);

// Custom garbage collection (advanced usage)
const deleteSet = Y.createDeleteSet();
Y.tryGc(deleteSet, doc._store, (item) => {
  // Custom logic to determine if item should be garbage collected
  return item.deleted && Date.now() - item.timestamp > 3600000; // 1 hour
});

Install with Tessl CLI

npx tessl i tessl/npm-yjs

docs

document-management.md

event-system.md

index.md

position-tracking.md

shared-data-types.md

snapshot-system.md

synchronization.md

transaction-system.md

undo-redo-system.md

xml-types.md

tile.json