Skip to content
D
Documentation

Sync collaborators

how-to
6 min readUpdated

Use collaboration when several views edit the same document. Join peers through a shipped transport: concurrent edits to different properties survive, reconnect delivers missed operations, and Undo takes back only its author's edits.

The diagram owns the live models; collaboration captures changes to those models rather than synchronizing your framework's component state. Your product supplies document identity, authorization and storage.

1. Join two live views

Start in the project from your JavaScript, React, Vue, Angular or Qwik quick start. Those projects already install the packages used below; no additional install is needed. Add the shared data file, then use the matching framework tab in place of the quick start's editor content. Keep the starter's entry, styles and configuration wiring.

Type the seed data with NodeSpec and EdgeSpec. Give every peer the same starting document and stable entity ids, but a different actor id.

ts
import type { NodeSpec, EdgeSpec } from '@grafloria/renderer';

export function seedNodes(): NodeSpec[] {
  return [
    { id: 'a', label: 'Ingest', position: { x: 60, y: 80 },
      size: { width: 150, height: 66 } },
    { id: 'b', label: 'Publish', position: { x: 300, y: 80 },
      size: { width: 150, height: 66 } },
  ];
}

export function seedEdges(): EdgeSpec[] {
  return [{ id: 'e1', source: 'a', target: 'b' }];
}

BroadcastChannelTransport connects views in the same browser origin without a server. Its name identifies the document's channel; keep it the same across tabs and namespace it by document id. The examples use guide:document:ingest so opening the page twice joins the same document. Each mounted peer gets a fresh actor id.

For JavaScript, render() returns the mounted DiagramInstance. Pass its model to createSyncSession(), then call join(). Framework bindings expose the same session through their collab prop and join and leave it with the canvas lifecycle.

React's GrafloriaFlow, Vue's GrafloriaFlow, Qwik's GrafloriaFlow and Angular's DiagramCanvasComponent render two connected nodes in each pane. Vue, Angular and Qwik export the wrapper contract as GrafloriaCollabOptions, GrafloriaCollabOptions and GrafloriaCollabOptions, respectively. The wrapper's presence option adds live cursors and remote selection outlines; the JavaScript tab below synchronizes document edits only.

ts
// src/main.ts — retain the quick start's stylesheet import.
import './style.css';
import { render } from '@grafloria/element';
import { BroadcastChannelTransport, createSyncSession } from '@grafloria/engine';
import { seedNodes, seedEdges } from './collab-data';

const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
if (!BroadcastChannelTransport.isSupported()) {
  throw new Error('This browser needs a socket transport for collaboration.');
}
app.innerHTML = `
  <p>Drag a node in either pane; the other pane follows.</p>
  <div style="display:flex;gap:12px">
    <div id="peer-a" style="flex:1;height:400px"></div>
    <div id="peer-b" style="flex:1;height:400px"></div>
  </div>
  <button id="close-editor">Close editor</button>`;

function peer(target: string) {
  const actor = Array.from(crypto.getRandomValues(new Uint32Array(4)), n => n.toString(16)).join('-');
  const transport = new BroadcastChannelTransport({
    name: 'guide:document:ingest', actor,
  });
  const instance = render({ nodes: seedNodes(), edges: seedEdges() }, target);
  const session = createSyncSession(instance.getModel(), transport, { actor });
  session.join();
  return { instance, session, transport };
}

const peers = [peer('#peer-a'), peer('#peer-b')];
document.querySelector<HTMLButtonElement>('#close-editor')!
  .addEventListener('click', () => {
    for (const p of peers) {
      p.session.dispose();
      p.transport.close();
      p.instance.dispose();
    }
    app.replaceChildren();
  });

Vue uses :collab; Angular uses [collab]. Qwik takes an options object marked with noSerialize(): create transports in useVisibleTask$, not during server rendering. See Qwik resumable integration for the lifecycle pattern.

React's onCollabReady and Qwik's onCollabReady$ receive the joined session. These samples use it to publish the actor id as the peer's presence name with setAwareness().

The React sample starts with Ingest connected to Publish in each of two panes.

Run your development server. Drag Ingest in either pane: its position changes in the other pane too. Open the same URL in a second tab to join two more views. Cameras remain local; document edits synchronize. Compare the Two tabs, live demo.

2. Conflict resolution

Stage a move on peer A and a rename on peer B before exchanging operations. Position and metadata.label are separate registers, so both edits appear on both peers after exchange. If peers write the same register, its total-order last writer wins rather than combining the values.

Use MemoryHub for this same-page exercise. It returns a shipped MemoryTransport for each actor and delivers synchronously to the other connected peers.

Normally use createSyncSession(). The exercise below explicitly owns the capture-to-publish connection to show how Replica and SyncAdapter fit together: the replica's onLocalOp callback forwards each Op to publish(). Attach them to the mounted instance's model, not a separate document.

Add this browser module to any of the quick-start projects. It returns cleanup for your component's unmount hook; the JavaScript entry below mounts it directly. Its two replicas use a deliberately long batch interval so Exchange controls when queued edits cross the wire.

ts
import { render } from '@grafloria/element';
import { MemoryHub, Replica, SyncAdapter } from '@grafloria/engine';
import type { Op } from '@grafloria/engine';
import type { NodeSpec } from '@grafloria/renderer';

export function mountConflictEditor(host: HTMLElement): () => void {
  const hub = new MemoryHub();
  const makePeer = (actor: string) => {
    const pane = document.createElement('div');
    pane.style.cssText = 'height:400px;flex:1';
    panes.append(pane);
    const nodes: NodeSpec[] = [
      { id: 'n1', label: 'Draft', position: { x: 60, y: 80 },
        size: { width: 160, height: 70 } },
    ];
    const instance = render({ nodes, edges: [] }, pane);
    const transport = hub.connect(actor);
    let session: SyncAdapter | undefined;
    const replica = new Replica(instance.getModel(), {
      actor, onLocalOp: (op: Op) => session?.publish(op),
    });
    session = new SyncAdapter(replica, transport, {
      batch: { intervalMs: 1_000_000 },
      now: () => performance.timeOrigin + performance.now(),
      awarenessThrottleMs: 100,
    });
    session.join();
    return { instance, transport, replica, session };
  };

  const controls = document.createElement('div');
  const panes = document.createElement('div');
  panes.style.cssText = 'display:flex;gap:12px';
  host.append(controls, panes);
  // Mount each peer in its final pane while keeping controls outside it.
  const a = makePeer('ana');
  const b = makePeer('bo');
  const readout = document.createElement('pre');
  controls.append(readout);

  function button(label: string, action: () => void) {
    const element = document.createElement('button');
    element.textContent = label;
    element.addEventListener('click', () => { action(); queueMicrotask(update); });
    controls.append(element);
    return element;
  }
  const move = () => a.replica.transact(() => {
    a.instance.getModel().getNode('n1')?.setPosition(240, 200);
  });
  const rename = () => b.replica.transact(() => {
    b.instance.getModel().getNode('n1')?.setMetadata('label', 'Final');
  });
  button('Move A', move);
  button('Rename B', rename);
  button('Exchange', () => { a.session.flush(); b.session.flush(); });
  button('Disconnect B', () => b.transport.disconnect());
  button('Reconnect B', () => b.transport.connect());
  button('Undo A', () => { a.replica.undo(); a.session.flush(); });
  button('Redo A', () => { a.replica.redo(); a.session.flush(); });

  function update() {
    readout.textContent = [a, b].map(p => {
      const node = p.instance.getModel().getNode('n1');
      const label = node?.getMetadata('label');
      return `${p.replica.actor}: ${String(label)}, x=${node?.position.x}, ` +
        `ops=${p.replica.history().length}, ${p.transport.status}`;
    }).join('\n');
  }
  const unsubs = [a, b].flatMap(p => [
    p.instance.getModel().on('node:changed', () => queueMicrotask(update)),
    p.instance.on('nodes:change', () => queueMicrotask(update)),
    p.transport.onStatus(() => queueMicrotask(update)),
  ]);
  update();

  return () => {
    for (const unsubscribe of unsubs) unsubscribe();
    for (const p of [a, b]) {
      p.session.dispose();
      p.transport.close();
      p.instance.dispose();
    }
    host.replaceChildren();
  };
}

For the JavaScript project, use this entry instead of step 1's entry. Keep src/style.css from the quick start.

ts
import './style.css';
import { mountConflictEditor } from './conflict-editor';

const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
const host = document.createElement('section');
const close = document.createElement('button');
close.textContent = 'Close editor';
app.replaceChildren(host, close);
const unmount = mountConflictEditor(host);
close.addEventListener('click', () => { unmount(); close.remove(); });
  1. Choose Move A. Only A moves Draft.
  2. Choose Rename B. Only B displays Final.
  3. Choose Exchange. Both panes display Final at the moved position.

The readout uses history() for each replica's complete, ordered log. For network catch-up, let the session use its sharedHistory() and frontier(); batching excludes superseded intermediate operations from the shared history. See the Conflict resolution demo.

3. Recover missed operations after reconnect

Continue with the mounted conflict editor:

  1. Choose Disconnect B before making edits.
  2. Choose Move A and Rename B, then Exchange while B remains disconnected.
  3. Choose Reconnect B. Both panes converge with the move and rename intact.

disconnect() keeps the transport reopenable. connect() reports a connected status, and the session automatically announces its frontier and starts an anti-entropy round. Offline edits stay in each replica's local log; the session delivers the missing operations rather than replacing the document with a peer's snapshot. sync() requests an additional round when your application needs one; reconnect does not require a manual call.

Use this sequence in a fresh editor, or make new edits with a drag if the buttons already produced their target values. Repeating a setter with the current value does not demonstrate a new edit. The Offline & reconnect demo shows the same disconnected-edit sequence.

For peers on different machines, use the shipped WebSocketTransport with new WebSocketTransport({ url: 'wss://api.example.com/diagrams/ingest' }) in place of the broadcast transport. Supply your own endpoint: its relay broadcasts each incoming frame verbatim to every other socket in the room, excluding the sender. The transport supplies reconnect backoff; the session supplies catch-up. Room authorization and durable storage remain application responsibilities.

4. Keep undo local to its author

After exchanging the move and rename, choose Undo A. Both panes return to the original position but retain B's Final label. Choose Redo A to reapply A's move. Undo and Redo emit ordinary operations, so the result reaches peers too; the history being navigated belongs only to A.

The replica implements HistoryOwner and installs itself on the diagram. Engine and canvas undo paths then delegate to it. undo() and redo() return emitted operations; they can return an empty array when an edit has already been superseded. Do not publish those arrays again: capture already sends the inverse operations.

The sample's transact() groups each programmatic edit into one undo step. Canvas gestures and engine commands already frame their steps. The Undo and Redo buttons remain available; calling either with an empty stack emits no operations. The readout updates from the model's node:changed event and the instance's nodes:change event.

UndoStack is the per-actor, supersession-aware stack inside the replica, not a second stack to create for your UI. replay() applies an ordered log to a document and returns the number applied; use replica.receive(history) instead when seeding a peer that continues editing, so it retains quarantine and deduplication state. For saving a document and reopening it, use Save and restore, not repeated log replay.

Compare the Collaboration-aware undo demo.

Session options

SyncSessionOptions extends SyncAdapterOptions. Pass these to createSyncSession() when you own session setup, or include them alongside transport, actor and presence in wrapper collab options; the wrappers forward session tuning options to createSyncSession().

OptionTypeDefaultWhat it does
actorstringRequiredIdentifies this peer; keep it unique among peers.
startClocknumber0Resumes the Lamport clock from a persisted tail.
batchBatcher options or falseBatching enabledCoalesces repeated register writes; false sends every operation immediately. The exercise uses intervalMs to stage edits until flush().
relaybooleanfalseForwards newly received operations in a point-to-point mesh. Shipped broadcast transports already deliver to all peers.
syncIntervalMsnumber0Positive values schedule anti-entropy rounds; 0 disables the periodic timer.
heartbeatMsnumberOne third of the presence timeoutRepublishes presence while idle; 0 disables heartbeat sends, not pruning.
awarenessThrottleMsnumber50Sets the minimum interval between presence sends.
awarenessTimeoutMsnumber15000Expires silent peers' presence; pruning runs on a timer.
now() => numberDate.nowSupplies the local clock used for presence timing. It does not determine CRDT operation order.

Awareness stores local and remote cursor, selection and name state. It is available as session.awareness; use setAwareness() to publish a patch and awareness.onChange() to subscribe to peer changes. Presence travels outside the operation log and does not create undo steps.

  • Keep transports and actors stable for a mounted peer. Remount the canvas to change rooms or actors; changing the supplied collaboration object does not replace a mounted session.
  • Call dispose() for an owned session during unmount, and close() when its transport is no longer needed. Closing a transport is permanent; use disconnect() for a temporary drop.
  • A broadcast channel holds neither history nor storage. A late peer needs another live peer to supply missed operations, or your application's persisted document.
  • For controlled React arrays, keep the state return path; collaboration does not make stale controlled inputs authoritative.
  • Add cursor styling and comment panels with Share presence and comments. Route programmatic editor actions through Commands and history.

Was this page helpful?

Sync collaborators — Grafloria