Skip to main content
Version: 4.3

Liveblocks

Liveblocks syncs data between the people in a room in real time. Connected to a JointJS graph, it lets several people edit one diagram together and see each other's cursors.

How it works​

A Liveblocks room holds two kinds of data:

  • Storage is the shared document. It is persisted and synced to everyone in the room. Here, it is a LiveMap of the elements, each a LiveObject with its position and label.
  • Presence is live, per-person state that is never stored, such as the cursor.

The storage is the one source of truth, and every diagram is drawn from it:

  1. Storage → graph. Draw the stored elements, then subscribe to the storage and apply every change to the graph.
  2. Graph → storage. Listen to the graph and write what the user changed into the storage. Liveblocks syncs it to everyone, and step 1 draws it.

Step 1 must not trigger step 2, or every change would bounce back to the storage. Pass an option such as { remote: true } when you apply a change from the storage, and ignore the changes with that option in the graph listeners.

Example​

The two diagrams below belong to two people, Alice and Bob, connected to the same room. Drag an element in one diagram and watch it move in the other. Double-click the blank area to add an element, and double-click an element to remove it.

important

The example needs the public key of your Liveblocks project. Get it from the Liveblocks dashboard (a free account is enough), and paste it into PUBLIC_API_KEY at the top of index.js. Until then, the example does not connect.

import { dia, shapes } from '@joint/core';
import { createClient, LiveMap, LiveObject } from '@liveblocks/client';
import './styles.css';

// The public key of your Liveblocks project (https://liveblocks.io/dashboard/apikeys).
const PUBLIC_API_KEY = 'pk_...';

// Both collaborators join the same room. The random id keeps your session private.
const ROOM_ID = 'jointjs-docs-' + Math.random().toString(36).slice(2);

// The storage of a new room: the shared document the diagrams are drawn from.
function initialStorage() {
    return {
        elements: new LiveMap([
            ['a', new LiveObject({ x: 40, y: 60, label: 'Drag me' })],
            ['b', new LiveObject({ x: 120, y: 200, label: 'Or me' })]
        ])
    };
}

function createElement(id, x, y, label) {
    return new shapes.standard.Rectangle({
        id,
        position: { x, y },
        size: { width: 120, height: 50 },
        attrs: {
            body: { fill: '#fff', stroke: '#e2e8f0', rx: 12, ry: 12 },
            label: { text: label, fill: '#0f172a', fontSize: 14 }
        }
    });
}

function collaborate(el, name, color) {
    if (PUBLIC_API_KEY === 'pk_...') {
        const message = document.createElement('div');
        message.className = 'message';
        message.textContent = 'Paste the public key of your Liveblocks project into PUBLIC_API_KEY in index.js.';
        el.appendChild(message);
        return;
    }

    const graph = new dia.Graph({}, { cellNamespace: shapes });
    const paper = new dia.Paper({
        el: el.querySelector('.paper'),
        model: graph,
        cellViewNamespace: shapes,
        width: '100%',
        height: '100%',
        gridSize: 10,
        background: { color: '#f8fafc' }
    });

    // In an app, every browser tab has one client. Here, each collaborator has its own.
    const client = createClient({ publicApiKey: PUBLIC_API_KEY, throttle: 16 });
    const { room } = client.enterRoom(ROOM_ID, {
        initialPresence: { name, color, cursor: null },
        initialStorage
    });

    room.getStorage().then(({ root }) => {
        const elements = root.get('elements');

        // Storage -> graph: draw the stored elements. The `remote` flag marks
        // the changes that come from the storage, so they are not sent back.
        const sync = () => {
            const data = elements.toJSON();
            Object.entries(data).forEach(([id, { x, y, label }]) => {
                const element = graph.getCell(id);
                if (element) {
                    element.position(x, y, { remote: true });
                } else {
                    graph.addCell(createElement(id, x, y, label), { remote: true });
                }
            });
            graph.getElements().forEach((element) => {
                if (!(element.id in data)) element.remove({ remote: true });
            });
        };
        sync();
        room.subscribe(elements, sync, { isDeep: true });

        // Graph -> storage: write what the user changed.
        graph.on('change:position', (element, position, opt) => {
            if (opt.remote) return;
            // The element may have been removed by someone else in the meantime.
            const item = elements.get(element.id);
            if (item) item.update(position);
        });

        // Double-click the blank area to add an element, an element to remove it.
        paper.on('blank:pointerdblclick', (evt, x, y) => {
            const id = Math.random().toString(36).slice(2);
            elements.set(id, new LiveObject({ x: x - 60, y: y - 25, label: name }));
        });
        paper.on('element:pointerdblclick', (elementView) => {
            elements.delete(elementView.model.id);
        });
    });

    // Presence: live, per-person state that is not stored, e.g. the cursor.
    // It is sent in graph coordinates, so it lands right at any zoom and scroll.
    paper.el.addEventListener('pointermove', (evt) => {
        room.updatePresence({
            cursor: paper.clientToLocalPoint(evt.clientX, evt.clientY).toJSON()
        });
    });
    paper.el.addEventListener('pointerleave', () => {
        room.updatePresence({ cursor: null });
    });

    // Draw the cursors of the others.
    const cursors = {};
    room.subscribe('others', (others) => {
        Object.values(cursors).forEach((cursorEl) => cursorEl.remove());
        others.forEach(({ connectionId, presence }) => {
            if (!presence.cursor) return;
            const { x, y } = paper.localToPaperPoint(presence.cursor);
            const cursorEl = cursors[connectionId] || document.createElement('div');
            cursorEl.className = 'cursor';
            cursorEl.textContent = presence.name;
            cursorEl.style.background = presence.color;
            cursorEl.style.transform = `translate(${x}px, ${y}px)`;
            el.appendChild(cursorEl);
            cursors[connectionId] = cursorEl;
        });
    });
}

collaborate(document.getElementById('alice'), 'Alice', '#6366f1');
collaborate(document.getElementById('bob'), 'Bob', '#f43f5e');


Connect to a room​

Create a client with the public key of your Liveblocks project and enter a room. initialStorage is applied only when the room has no storage yet:

import { createClient, LiveMap, LiveObject } from '@liveblocks/client';

const client = createClient({ publicApiKey: 'pk_...', throttle: 16 });

const { room } = client.enterRoom('my-diagram', {
initialPresence: { cursor: null },
initialStorage: () => ({
elements: new LiveMap([
['a', new LiveObject({ x: 40, y: 60, label: 'Drag me' })]
])
})
});

throttle: 16 sends the changes every 16 milliseconds (once per frame), so the others see your drags smoothly.

Storage → graph​

Load the storage with room.getStorage() and draw it. Then subscribe to it: with isDeep, the callback runs whenever an element is added or removed, or one of its fields changes:

const { root } = await room.getStorage();
const elements = root.get('elements');

const sync = () => {
const data = elements.toJSON();
Object.entries(data).forEach(([id, { x, y, label }]) => {
const element = graph.getCell(id);
if (element) {
element.position(x, y, { remote: true });
} else {
graph.addCell(createElement(id, x, y, label), { remote: true });
}
});
graph.getElements().forEach((element) => {
if (!(element.id in data)) element.remove({ remote: true });
});
};

sync();
room.subscribe(elements, sync, { isDeep: true });

sync() goes through all the elements on every change, which keeps the example short. In a large diagram, apply only the changes passed to the callback (updates) instead.

Graph → storage​

Write the changes made by the user, and skip the ones that came from the storage:

graph.on('change:position', (element, position, opt) => {
if (opt.remote) return;
// The element may have been removed by someone else in the meantime.
const item = elements.get(element.id);
if (item) item.update(position);
});

To add or remove an element, change the storage, not the graph. sync() then updates every graph, yours included:

elements.set(id, new LiveObject({ x, y, label: 'New' }));
elements.delete(id);

Presence​

Send the cursor in graph coordinates. Everyone may zoom and scroll differently, but the cursor still lands on the same spot of the diagram:

paper.el.addEventListener('pointermove', (evt) => {
room.updatePresence({
cursor: paper.clientToLocalPoint(evt.clientX, evt.clientY).toJSON()
});
});

Subscribe to the others, and draw their cursors at paper.localToPaperPoint(presence.cursor):

room.subscribe('others', (others) => {
others.forEach(({ connectionId, presence }) => {
// Draw the cursor of `connectionId` at `paper.localToPaperPoint(presence.cursor)`.
});
});

Real-world example​

Playbook is a multiplayer process designer built with @joint/react-plus and Liveblocks. On top of the basics above, it:

  • syncs links, resizing and text editing,
  • shows who is editing which card,
  • shows the links and cards the others are dragging,
  • keeps an activity feed.

Open it, and share the link of your board with someone to edit it together.

The source code is available on GitHub.