Skip to main content

YJS API Reference

The YJS API provides a powerful set of tools for managing real-time collaboration using Yjs, a high-performance CRDT framework. This API enables seamless offline editing, instant real-time updates, and comprehensive awareness features for all participants within a shared collaborative space. This reference guide covers the extensive methods and types available for working with YJS, helping you to build robust, real-time collaborative applications.

Methods

SuperVizYjsProvider()

SuperVizYjsProvider(doc: Y.Doc, options?: YjsProviderOptions)

Initializes a new YJS provider instance, which serves as the core of your collaborative setup.

Parameters:

  • doc: A Yjs document instance that will be synchronized across clients.
  • options: (Optional) Configuration options for the provider.

Returns: A new SuperVizYjsProvider instance.

Example:

const doc = new Y.Doc();
const provider = new SuperVizYjsProvider(doc, { awareness: true });

on()

on(event: string, callback: (data: any) => void)

Registers a listener for a specific YJS provider event, allowing you to react to various collaboration-related occurrences.

Parameters:

  • event: The name of the event to listen for.
  • callback: A function to be called when the event occurs.

Example:

provider.on('sync', () => {
console.log("Document successfully synced with other participants");
});

off()

off(event: string, callback: (data: any) => void)

Removes a previously registered event listener, useful for cleaning up when a component unmounts or when you no longer need to listen for an event.

Parameters:

  • event: The name of the event to stop listening to.
  • callback: The function that was originally passed to on().

Example:

const syncCallback = () => console.log("Document synced");
provider.off('sync', syncCallback);

once()

once(event: string, callback: (data: any) => void)

Registers a one-time listener for a specific YJS provider event. The listener automatically removes itself after being called once.

Parameters:

  • event: The name of the event to listen for.
  • callback: A function to be called when the event occurs.

Example:

provider.once('sync', () => {
console.log("Document synced for the first time");
});

emit()

emit(event: string, data: any[])

Manually triggers an event on the YJS provider, useful for custom events or testing.

Parameters:

  • event: The name of the event to emit.
  • data: Any data to be passed to the event listeners.

Example:

provider.emit('custom-event', { message: "Hello, YJS!" });

setLocalState()

setLocalState(state: Record<string, any> | null)

Updates the entire state of the local participant in the awareness protocol. This is crucial for sharing information like cursor position or user status with other participants.

Parameters:

  • state: An object representing the new state, or null to clear the state.

Example:

provider.awareness.setLocalState({ cursor: { x: 10, y: 20 }, status: "active" });

setLocalStateField()

setLocalStateField(field: string, value: any)

Updates a specific field in the local participant's state without affecting other fields. This is useful for updating individual pieces of information.

Parameters:

  • field: The name of the field to update.
  • value: The new value for the field.

Example:

provider.awareness.setLocalStateField('cursor', { x: 10, y: 20 });

getStates()

getStates(): Map<number, Record<string, any>>

Retrieves the current states of all participants in the collaborative session. This is useful for understanding the overall state of the collaboration.

Returns: A Map where keys are client IDs and values are the states of each participant.

Example:

const allStates = provider.awareness.getStates();
allStates.forEach((state, clientId) => {
console.log(`Client ${clientId} state:`, state);
});

getLocalState()

getLocalState(): Record<string, any> | null

Retrieves the current state of the local participant. This can be used to check or display the local user's current status or information.

Returns: An object representing the local state, or null if no state has been set.

Example:

const localState = provider.awareness.getLocalState();
console.log("My current state:", localState);

Types

YjsProviderOptions

Configuration options for initializing the YJS provider.

FieldTypeDescription
awarenessbooleanDetermines whether to enable awareness features. When true, allows tracking of user presence and custom state. Default is true.

YjsAwareness

Represents the awareness object of the YJS provider, which handles user presence and custom state information.

FieldTypeDescription
clientIdnumberA unique identifier for the local participant within the collaborative session.
statesMap<number, any>A map containing the awareness states of all participants, where keys are client IDs and values are their respective states.

Events

YJS provider emits several events that you can listen to for managing the collaborative session:

EventDescription
connectEmitted when the local user successfully joins the collaborative room. Use this to initialize user-specific data or UI elements.
disconnectEmitted when the user leaves the room or loses connection. Useful for cleaning up or showing a reconnection UI.
syncEmitted when the document is successfully synced with other participants. This indicates that the local state is up-to-date with the shared state.
awareness.changeEmitted when there's a change in any participant's awareness state. This could be used to update UI elements showing user presence or status.

Usage Example

Here's a comprehensive example demonstrating the usage of the YJS API:

import { SuperVizYjsProvider } from "@superviz/yjs";
import * as Y from "yjs";

// Initialize Yjs document and provider
const doc = new Y.Doc();
const provider = new SuperVizYjsProvider(doc);

// Listen for sync events
provider.on('sync', () => {
console.log("Document synced with other participants");
});

// Set local participant's state
provider.awareness.setLocalState({
cursor: { x: 10, y: 20 },
name: "Alice",
status: "active"
});

// Listen for awareness changes
provider.awareness.on('change', ({ added, updated, removed }) => {
console.log("Awareness changed", { added, updated, removed });

// Get all current states
const allStates = provider.awareness.getStates();
console.log("All participants' states", allStates);
});

// Example of updating a specific field
provider.awareness.setLocalStateField('status', "away");

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