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

YjsProvider

A React component that initializes the SuperVizYjsProvider, enabling its use to manage collaborative state and synchronization across connected clients.

Props:

  • doc: The Yjs document instance to be used for collaboration.
  • awareness: (Optional) Boolean to enable or disable awareness features.
  • children: (Optional) Child components of the YjsProvider. Wrapping components with YjsProvider does not serve any function, but it can be useful for organizing the component tree.

Example:

<YjsProvider doc={doc}>
<CollaborativeEditor />
<UserList />
</YjsProvider>

useYjsProvider()

A custom React hook that provides access to YJS methods and properties within a functional component. This hook must be used within a component that is a child of SuperVizRoomProvider.

Returns: An object containing various YJS-related methods and the provider instance.

Example:

const {
setLocalState,
setLocalStateField,
getStates,
getLocalState,
provider,
} = useYjsProvider();

// Use these methods to interact with YJS

Types

YjsProviderProps

Props for the YjsProvider component, defining its configuration and behavior.

PropTypeDescription
docY.DocThe Yjs document instance to be used for collaboration. This document will be synchronized across all connected clients.
awarenessbooleanOptional prop to enable or disable awareness features. When true, allows tracking of user presence and custom state. Default is true.
childrenReact.ReactNodeChild components that will be wrapped by the YjsProvider component.

UseYjsProviderResult

The return type of the useYjsProvider hook, providing access to YJS functionality within React components.

FieldTypeDescription
setLocalState(state: Record<string, any> | null) => voidFunction to set the entire local participant's state. Useful for updating multiple fields at once.
setLocalStateField(field: string, value: any) => voidFunction to update a single field in the local participant's state. Useful for granular updates.
getStates() => Map<number, Record<string, any>>Function to retrieve the current states of all participants in the collaborative session.
getLocalState() => Record<string, any> | nullFunction to get the current state of the local participant.
providerY.DocThe Yjs document instance being used by the provider. Allows direct access to Yjs functionality if needed.

Events

The YjsProvider component accepts several event handler props for reacting to YJS events:

  • onMount: () => void

    • Called when the YjsProvider component is mounted. Use this for any initialization logic.
  • onUnmount: () => void

    • Called when the YjsProvider component is about to unmount. Use this for cleanup tasks.
  • onConnect: () => void

    • Called when a connection to the collaborative room is established.
  • onDisconnect: () => void

    • Called when the connection to the collaborative room is lost.
  • onSync: () => void

    • Called when the document is synced with other participants.
  • onAwarenessChange: (changes: { added: number[], updated: number[], removed: number[] }) => void

    • Called when there's a change in awareness states. The changes object provides information about which clients were added, updated, or removed.

Usage Example

Here's a detailed example demonstrating the usage of the YJS API in a React application:

import React, { useEffect, useState } from "react";
import {
YjsProvider,
useYjsProvider,
SuperVizRoomProvider,
} from "@superviz/react-sdk";
import * as Y from "yjs";

// Initialize Yjs document
const doc = new Y.Doc();
const DEVELOPER_KEY = import.meta.env.VITE_SUPERVIZ_DEVELOPER_KEY;

function CollaborativeComponent() {
const { setLocalState, getStates, setLocalStateField, provider } =
useYjsProvider();
const [allStates, setAllStates] = useState(new Map());

useEffect(() => {
// Set initial local state
setLocalState({
cursor: { x: 0, y: 0 },
name: "Alice",
status: "active",
});

// Update cursor position on mouse move
const handleMouseMove = (e) => {
setLocalStateField("cursor", { x: e.clientX, y: e.clientY });
};
window.addEventListener("mousemove", handleMouseMove);

return () => window.removeEventListener("mousemove", handleMouseMove);
}, [setLocalState, setLocalStateField]);

// Periodically update all states
useEffect(() => {
provider?.awareness.on("change", ({ added, updated, removed }) => {
console.log("Awareness changed", { added, updated, removed });

setAllStates(getStates());
});

return () => {
provider?.awareness.off("change");
};
}, [provider]);

return (
<div>
<h2>Collaborative Component</h2>
<div>
{Array.from(allStates).map(([clientId, state]) => (
<div key={clientId}>
User {state.name}: {state.status}
<div
style={{
position: "absolute",
left: state.cursor.x,
top: state.cursor.y,
width: 10,
height: 10,
borderRadius: "50%",
backgroundColor: "red",
}}
/>
</div>
))}
</div>
</div>
);
}

function App() {
return (
<SuperVizRoomProvider
developerKey={DEVELOPER_KEY}
group={{
id: "group-id",
name: "group-name",
}}
participant={{
id: "participant-id",
name: "participant",
}}
roomId="room-id"
>
<YjsProvider doc={doc} onSync={() => console.log("Document synced")}>
<CollaborativeComponent />
</YjsProvider>
</SuperVizRoomProvider>
);
}

export default App;