Skip to content

Collaboration with Loro CRDT

Loro offers CRDT data types for collaborative apps—compare with Yjs in the adjacent example. Conflict resolution is automatic; UI must still converge sensibly.

See Lesson 20 — Collaboration for architecture context.

Interactive demo

Use LoroDoc and BroadcastChannel mock collaboration, see Loro Excalidraw Example.

First, monitor changes to the local canvas and synchronize the list of shapes and their property objects to the local LoroDoc:

ts
api.onchange = (snapshot) => {
    const { appState, nodes } = snapshot;
    if (recordLocalOps(docNodes, nodes)) {
        doc.commit();
    }
};

Then listen for changes to LoroDoc, distinguishing between local and remote changes via e.by. If the change originates locally, send a synchronization message; if it comes from the remote, update the canvas content.

ts
doc.subscribe((e) => {
    if (e.by === 'local') {
        const bytes = doc.export({ mode: 'update', from: lastVersion });
        lastVersion = doc.version();
        channel.postMessage(bytes);
    }

    if (e.by !== 'local') {
        api.updateNodes(docNodes.toJSON());
    }
});

Released under the MIT License.