JS SDK
Through Yorkie JS SDK, you can efficiently build collaborative applications. On the client-side implementation, you can create Documents that are automatically synced with remote peers with minimal effort.
If you want to install the SDK, refer to the Getting Started with JS SDK.
Client
Client
is a normal client that can communicate with the server. It has documents and sends changes of the document from local to the server to synchronize with other replicas in remote.
Creating a Client
We can create a Client using new yorkie.Client()
. After the Client has been activated, it is connected to the server and ready to use.
1const client = new yorkie.Client('https://api.yorkie.dev', {2 apiKey: 'xxxxxxxxxxxxxxxxxxxx',3});4await client.activate();
The API key is used to identify the project in Yorkie. You can get the API key of the project you created in the Dashboard.
Subscribing to Client events
We can use client.subscribe
to subscribe to client-based events, such as status-changed
, stream-connection-status-changed
and peer-changed
.
1const unsubscribe = client.subscribe((event) => {2 if (event.type === 'status-changed') {3 console.log(event.value); // 'activated' or 'deactivated'4 } else if (event.type === 'stream-connection-status-changed') {5 console.log(event.value); // 'connected' or 'disconnected'6 }7});
By using the value of the stream-connection-status-changed
event, it is possible to determine whether the Client is connected to the network.
If you want to know about other client events, please refer to the ClientEvent, and ClientEventType.
Presence
Presence is a feature that allows you to display information about users who are currently using a collaborative application. Presence is often used in collaborative applications such as document editors, chat apps, and other real-time applications.
1const clientA = new yorkie.Client('https://api.yorkie.dev', {2 presence: {3 username: 'alice',4 color: 'blue',5 },6});7await clientA.activate();89const docA = new yorkie.Document('doc-1');10await clientA.attach(docA);
Then, another Client is created and attaches a Document with the same name as before.
1const clientB = new yorkie.Client('https://api.yorkie.dev', {2 presence: {3 username: 'bob',4 color: 'red',5 },6});7await clientB.activate();89const docB = new yorkie.Document('doc-1');10await clientB.attach(docB);
When a new peer registers or leaves, the peers-changed
event is fired, and the other peer's clientID and presence can be obtained from the event.
1const unsubscribe = clientA.subscribe((event) => {2 if (event.type === 'peers-changed') {3 const peers = event.value.peers[doc.getKey()];4 switch (event.value.type) {5 case 'initialized':6 displayPeers(peers);7 break;8 case 'watched':9 peers.forEach((peer) => addPeer(peer));10 // peer as follows:11 // {12 // clientID: 'xxxxxxxxxxxxxxxxxxxx',13 // presence: {username: 'bob', color: 'red'}14 // }15 break;16 case 'unwatched':17 peers.forEach((peer) => removePeer(peer));18 break;19 case 'presence-changed':20 peers.forEach((peer) => updatePeer(peer));21 break;22 default:23 break;24 }25 }26});
In the code above, clientA
receives a watched
event from clientB
because clientB
attached the Document with the key doc-1
.
Presence can include their names, colors, and other identifying details. Here is an example of how Presence might be used in a collaborative document editor:
Document
Document
is a primary data type in Yorkie, which provides a JSON-like updating experience that makes it easy to represent your application's model. A Document
can be updated without being attached to the client, and its changes are automatically propagated to other peers when the Document
is attached to the Client
or when the network is restored.
Creating a Document
We can create a Document using yorkie.Document()
. Let's create a Document with a key and attach it to the Client.
1const doc = new yorkie.Document('doc-1');2await client.attach(doc);
The document key is used to identify the Document in Yorkie. It is a string that can be freely defined by the user. However, it is allowed to use only a-z
, A-Z
, 0-9
, -
, .
, _
, ~
and must be less than 120 characters.
After attaching the Document to the Client, all changes to the Document are automatically synchronized with remote peers.
Changing Syncronization Setting
To change the synchronization setting for a document, you can use client.pause(doc)
and client.resume(doc)
.
When you pause a document, the synchronization process will no longer occur in realtime, and you will need to manually execute the synchronization to ensure that the changes are propagated to other clients.
To resume the realtime synchronization, you can call client.resume(doc)
.
1// Pause real-time sync2await client.pause(doc);34// Resume real-time sync5await client.resume(doc);
Changing Syncronization Mode
By default, Yorkie synchronizes a document in push-pull
mode, where local changes are pushed to the server, and remote changes are pulled from the server.
If you only want to send your changes and not receive remote changes, you can use push-only
mode.
For realtime synchronization, you can use client.pauseRemoteChanges(doc)
and client.resumeRemoteChanges(doc)
.
For manual synchronization, you can pass the desired sync mode to client.sync(doc, syncMode)
.
1// Pause remote changes for realtime sync2client.pauseRemoteChanges(doc);3// Resume remote changes for realtime sync4client.resumeRemoteChanges(doc);56// Manual sync in Push-Only mode7await client.sync(doc, SyncMode.PushOnly);8// Manual sync in Push-Pull mode9await client.sync(doc, SyncMode.PushPull);
Editing the Document
Document.update(changeFn, message)
enables you to modify a Document. The optional message
allows you to add a description to the change. If the Document is attached to the Client, all changes are automatically synchronized with other Clients.
1const message = 'update document for test';2doc.update((root) => {3 root.todos = [];4 root.todos.push('todo-1');5 root.obj = {6 name: 'yorkie',7 age: 14,8 };9 root.counter = new yorkie.Counter(yorkie.IntType, 0);10 root.counter.increase(1);11}, message);
Under the hood, root
in the update
function creates a change
, a set of operations, using a JavaScript proxy. Every element has its unique ID, created by the logical clock. This ID is used by Yorkie to track which object is which.
You can get the contents of the Document using document.getRoot()
.
1const root = doc.getRoot();2console.log(root.todos); // ["todo-1"]3console.log(root.obj); // {"name":"yorkie","age":14}4console.log(root.obj.name); // "yorkie"5console.log(root.counter.getValue()); // 1
Subscribing to Document events
A Document can be modified by changes generated remotely or locally in Yorkie.
Whenever the Document is modified, change events are triggered and we can subscribe to these events using the document.subscribe(callback)
.
The callback is called with an event object, and the event.type
property indicates the source of the change, which can be one of the following values: local-change
, remote-change
, or snapshot
.
When the event.type
is local-change
or remote-change
, the event.value
is a list of changeInfo.
Each changeInfo is an {operations, message}
object.
For more information about changeInfo for document events, please refer to the ChangeInfo.
1const unsubscribe = doc.subscribe((event) => {2 if (event.type === 'local-change') {3 console.log(event);4 } else if (event.type === 'remote-change') {5 for (const changeInfo of event.value) {6 // `message` delivered when calling document.update7 const { message, operations } = changeInfo;8 for (const op of operations) {9 // ex) { type: 'increase', value: 1, path: '$.counter' }10 switch (op.type) {11 case 'increase':12 // Do something...13 break;14 }15 }16 }17 }18});
Additionally, you can subscribe to changes for a specific path in the Document using doc.subscribe(path, callback)
with a path argument, such as $.todos
, where the $
sign indicates the root of the document.
The callback function is called when the target path and its nested values are changed.
1const unsubscribe = doc.subscribe('$.todos', (event) => {2 // The callback will be called when the root.todos or any of its nested values change.3 const target = doc.getValueByPath('$.todos') // you can get the value by path4 // Do something...5});
Detaching the Document
If the document is no longer used, it should be detached to increase the efficiency of GC removing CRDT tombstones. For more information about GC, please refer to Garbage Collection.
1await client.detach(doc);
Custom CRDT types
Custom CRDT types are data types that can be used for special applications such as text editors and counters, unlike general JSON data types such as Object
and Array
. Custom CRDT types can be created in the callback function of document.update
.
Text
Text
provides supports for collaborative text editing. Text
has selection information for sharing the cursor position. In addition, contents in Text
can have attributes; for example, characters can be bold, italic, or underlined.
1doc.update((root) => {2 root.text = new yorkie.Text(); // {"text":""}3 root.text.edit(0, 0, 'hello'); // {"text":"hello"}4 root.text.edit(0, 1, 'H'); // {"text":"Hello"}5 root.text.select(0, 1); // {"text":"^H^ello"}6 root.text.setStyle(0, 1, { bold: true }); // {"text":"<b>H</b>ello"}7});
An example of Text co-editing with CodeMirror: CodeMirror example
An example of Text co-editing with Quill: Quill example
Counter
Counter
supports integer types changing with addition and subtraction. If an integer data needs to be modified simultaneously, Counter
should be used instead of primitives.
1doc.update((root) => {2 root.counter = new yorkie.Counter(yorkie.IntType, 1); // {"counter":1}3 root.counter.increase(2); // {"counter":3}4 root.counter.increase(3); // {"counter":6}5 root.counter.increase(-4); // {"counter":2}6});
TypeScript Support
To use the Document more strictly, we can use type variable in TypeScript when creating a Document.
1type DocType = {2 list: Array<number>;3 text: yorkie.Text;4};56const doc = new yorkie.Document<DocType>('key');7doc.update((root) => {8 root.list = [1, 2, 3];9 root.text = new yorkie.Text();10});
Reference
For details on how to use the JS SDK, please refer to JS SDK Reference.