Skip to main content
Version: 4.3

Liveblocks

Liveblocks syncs data between the people in a room in real time. With @joint/react, the storage of the room is just another store for controlled mode. There are no graph listeners to write and no echo to filter out.

How it works​

Two hooks from @liveblocks/react connect the storage to GraphProvider:

  1. Read. useStorage returns the stored cells. Pass them as cells, and the graph follows every change, yours or anyone else's.
  2. Write. useMutation returns a function that changes the storage. Pass it as onIncrementalCellsChange, and the elements the user moves are written to the storage.

The cells you pass in through cells are not reported back through onIncrementalCellsChange, so a change from the storage never bounces back to it.

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 App.tsx. Until then, the example does not connect.

import { GraphProvider, HTMLBox, Paper, type IncrementalCellsChange } from '@joint/react';
import { LiveMap, shallow } from '@liveblocks/client';
import { ClientSideSuspense, LiveblocksProvider, RoomProvider, useMutation, useStorage } from '@liveblocks/react/suspense';
import '@joint/react/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-react-docs-' + Math.random().toString(36).slice(2);

type Cell = {
  id: string;
  type: 'element';
  position: { x: number; y: number };
  size: { width: number; height: number };
  data: { label: string };
};

const SIZE = { width: 120, height: 50 };

// The storage of the room: the cells, by id.
declare global {
  interface Liveblocks {
    Storage: { cells: LiveMap<string, Cell> };
  }
}

const initialStorage = () => ({
  cells: new LiveMap<string, Cell>([
    ['a', { id: 'a', type: 'element', position: { x: 40, y: 60 }, size: SIZE, data: { label: 'Drag me' } }],
    ['b', { id: 'b', type: 'element', position: { x: 160, y: 200 }, size: SIZE, data: { label: 'Or me' } }],
  ]),
});

function Diagram({ name }: { name: string }) {
  // The stored cells are the controlled state of the graph.
  const cells = useStorage((root) => Object.values(root.cells), shallow);

  // Write the elements the user moved back to the storage.
  const save = useMutation(({ storage }, { changed }: IncrementalCellsChange<Cell, never>) => {
    const stored = storage.get('cells');
    for (const cell of changed.values()) {
      // Skip the elements someone else has removed in the meantime.
      if (stored.has(cell.id)) stored.set(cell.id, cell);
    }
  }, []);

  const addCell = useMutation(({ storage }, x: number, y: number) => {
    const id = Math.random().toString(36).slice(2);
    storage.get('cells').set(id, { id, type: 'element', position: { x: x - SIZE.width / 2, y: y - SIZE.height / 2 }, size: SIZE, data: { label: name } });
  }, [name]);

  const removeCell = useMutation(({ storage }, id: string) => {
    storage.get('cells').delete(id);
  }, []);

  return (
    <GraphProvider cells={cells} onIncrementalCellsChange={save}>
      <Paper
        className="size-full"
        background={{ color: '#f8fafc' }}
        drawGrid={false}
        renderElement={({ label }) => (
          <HTMLBox useModelGeometry className="rounded-xl border border-slate-200 bg-white text-sm text-slate-900">
            {label}
          </HTMLBox>
        )}
        onBlankPointerDblClick={({ x, y }) => addCell(x, y)}
        onElementPointerDblClick={({ id }) => removeCell(String(id))}
      />
    </GraphProvider>
  );
}

function Collaborator({ name }: { name: string }) {
  // In an app, every browser tab has one provider. Here, each collaborator has its own.
  return (
    <LiveblocksProvider publicApiKey={PUBLIC_API_KEY} throttle={16}>
      <RoomProvider id={ROOM_ID} initialStorage={initialStorage}>
        <div className="relative flex-1 overflow-hidden rounded-xl border border-slate-200 bg-slate-50">
          <div className="absolute left-3 top-3 z-10 text-sm font-medium text-slate-900">{name}</div>
          <ClientSideSuspense fallback={null}>
            <Diagram name={name} />
          </ClientSideSuspense>
        </div>
      </RoomProvider>
    </LiveblocksProvider>
  );
}

export default function App() {
  if (PUBLIC_API_KEY === 'pk_...') {
    return (
      <div className="flex size-full items-center justify-center p-4 text-center text-sm text-slate-500">
        Paste the public key of your Liveblocks project into PUBLIC_API_KEY in App.tsx.
      </div>
    );
  }
  return (
    <div className="flex size-full gap-3 p-3">
      <Collaborator name="Alice" />
      <Collaborator name="Bob" />
    </div>
  );
}


Connect to a room​

Wrap the diagram in LiveblocksProvider and RoomProvider. initialStorage is applied only when the room has no storage yet. The hooks from @liveblocks/react/suspense wait for the storage to load, so ClientSideSuspense shows its fallback until then:

import { LiveMap } from '@liveblocks/client';
import { ClientSideSuspense, LiveblocksProvider, RoomProvider } from '@liveblocks/react/suspense';

<LiveblocksProvider publicApiKey="pk_...">
<RoomProvider id="my-diagram" initialStorage={{ cells: new LiveMap() }}>
<ClientSideSuspense fallback={null}>
<Diagram />
</ClientSideSuspense>
</RoomProvider>
</LiveblocksProvider>

Sync the storage and the graph​

The storage holds the cells in a LiveMap, by id. Read them as the controlled cells, and write the elements the user moved from onIncrementalCellsChange back:

function Diagram() {
const cells = useStorage((root) => Object.values(root.cells), shallow);

const save = useMutation(({ storage }, { changed }: IncrementalCellsChange<Cell, never>) => {
const stored = storage.get('cells');
for (const cell of changed.values()) {
// Skip the elements someone else has removed in the meantime.
if (stored.has(cell.id)) stored.set(cell.id, cell);
}
}, []);

return (
<GraphProvider cells={cells} onIncrementalCellsChange={save}>
<Paper renderElement={({ label }) => <HTMLBox useModelGeometry>{label}</HTMLBox>} />
</GraphProvider>
);
}

shallow keeps the same array while no cell has changed, so the graph is synced only when the storage changes. Only the cells that changed are written, so two people can move different elements at the same time. The size of each element is stored with it, and useModelGeometry draws the element at that size.

To add or remove an element, change the storage with another mutation. The graph of everyone in the room, yours included, follows:

const removeCell = useMutation(({ storage }, id: string) => {
storage.get('cells').delete(id);
}, []);

Presence​

Live, per-person state that is not stored, such as the cursor, is presence. Send yours with useUpdateMyPresence, and read the others with useOthers; see the Liveblocks React reference. The JointJS Liveblocks guide shows how to send the cursor in graph coordinates.

Stay in the know

Be where thousands of diagramming enthusiasts meet

Star us on GitHub