Skip to main content

Introduction

What is Yjs?

Yjs is a high-performance, modular framework for building collaborative applications. It provides a set of shared data types that can be used to build real-time, peer-to-peer applications.

What is YDoc?

YDoc is the main entry point for Yjs. It's a shared document that can contain multiple shared types, such as text, arrays, and maps. YDoc synchronizes automatically with other peers and provides conflict resolution.

Using YDoc

Creating a YDoc

import * as Y from "yjs";

const ydoc = new Y.Doc();

This creates a new YDoc instance that can be used to store and synchronize data.

Working with Text

Adding Text

const ytext = ydoc.getText("myText");
ytext.insert(0, "Hello, world!");

This creates a new shared text type named 'myText' and inserts 'Hello, world!' at the beginning.

Modifying Text

ytext.delete(0, 5); // Delete 'Hello'
ytext.insert(0, "Greetings"); // Insert 'Greetings' at the beginning

This deletes the first 5 characters and inserts 'Greetings' at the beginning.

Observing Changes

ytext.observe((event) => {
console.log("Text changed:", ytext.toString());
});

This sets up an observer that logs the text content whenever it changes.

Working with Maps

Adding to a Map

const ymap = ydoc.getMap("myMap");
ymap.set("key", "value");

This creates a shared map named 'myMap' and adds a key-value pair.

Modifying a Map

ymap.set("key", "new value");

This updates the value of an existing key.

Deleting from a Map

ymap.delete("key");

This removes a key-value pair from the map.

Synchronization sample code

import * as Y from "yjs";

// Yjs documents are collections of
// shared objects that sync automatically.
const ydoc = new Y.Doc();
// Define a shared Y.Map instance
const ymap = ydoc.getMap();
ymap.set("keyA", "valueA");

// Create another Yjs document (simulating a remote user)
// and create some conflicting changes
const ydocRemote = new Y.Doc();
const ymapRemote = ydocRemote.getMap();
ymapRemote.set("keyB", "valueB");

// Merge changes from remote
const update = Y.encodeStateAsUpdate(ydocRemote);
Y.applyUpdate(ydoc, update);

// Observe that the changes have merged
console.log(ymap.toJSON()); // => { keyA: 'valueA', keyB: 'valueB' }

Docs Reference: https://docs.yjs.dev/

Github Reference: https://github.com/yjs/yjs-demos