Birch UI v0.1
Pricing

CollaborationSpreadsheet

Several people editing one workbook: the operation stream, how concurrent edits are merged, presence cursors, the provider interface and what the model does not do.

Open .md

The spreadsheet can report every edit as a small JSON operation and apply operations that come from somewhere else. On top of that it ships the client side of a collaboration protocol, a server-side function that orders and merges operations, presence cursors, and an in-memory provider for tests, demos and several spreadsheets on one page.

It does not ship a server, a network transport, accounts or permissions. You bring those; the provider interface is where they plug in.

The model, stated plainly#

  • One authority orders the operations. Every edit is sent to a single place (your server) that puts all operations in one sequence and gives each a revision number. Every client ends up applying the same sequence.
  • It is operational transformation, not a CRDT. When two people edit at the same time, each operation was made without knowing about the other. The authority rewrites the later one so it still means the same thing after the earlier one (transform), and each client does the same for operations it has sent but not yet seen confirmed. Two clients cannot merge with each other without the authority.
  • Each client sends one operation at a time. Further local edits wait in a queue until the server confirms the one in flight. The spreadsheet shows local edits at once; only the sending is serial.
  • What is not modelled as a fine-grained operation is sent as a snapshot of the workbook. Snapshots are correct but coarse; the rules for them are below.
TypeScript
import { connectCollaboration, createSpreadsheet } from '@birchui/spreadsheet';

const sheet = createSpreadsheet(container, { data: workbook });
const session = connectCollaboration(sheet, provider, {
  clientId: account.id,
  user: { name: account.displayName, color: '#1f6feb' },
  revision: workbookRevision,
  rejected: ({ operation, reason }) => showToast(`Your ${operation.type} edit was not kept (${reason}).`),
});

provider is an object you write for your transport, or createLoopbackProvider(). revision is the server revision the loaded workbook corresponds to; leave it out when everyone starts from the same data at revision 0.

Operations#

sheet.onOperation(listener) calls the listener with { operation, origin: 'local' } for every local edit: typing, paste, fill, clear, API writes, row and column edits, sheet edits, and undo and redo, which are sent as the operations they perform. It returns a function that stops listening. sheet.applyRemoteOperation(operation) applies one operation from elsewhere. It does not call the onOperation listeners, does not add an undo step, and fires cellChange with source: 'remote'.

type Fields Meaning
cells sheet, cells: { address, value?, formula?, style?, richText? }[] Replace the content and style of each listed cell. An entry with neither value nor formula clears the cell; an entry without style removes the style.
insertRows, deleteRows sheet, row, count Insert or delete count rows at 1-based row.
insertColumns, deleteColumns sheet, column, count The same for columns; column is a 1-based number.
insertCells sheet, range, shift: 'right' | 'down' Insert blank cells at range and move the cells that were there, and the ones after them in the same rows or columns, right or down.
deleteCells sheet, range, shift: 'left' | 'up' Delete the cells of range and move the cells after them left or up.
addSheet name, order Add a sheet. order is the list of sheet names after the add.
moveSheet name, order Move a sheet. order is the list of sheet names after the move.
removeSheet name, order Remove a sheet. order is the list of sheet names before the removal.
renameSheet from, to Rename a sheet and rewrite the formulas that refer to it.
defineName, removeName name, formula?, sheet? Add, change or remove a defined name; sheet is the scope.
snapshot workbook Replace the workbook with this WorkbookJSON.

Operations are plain JSON and self-contained: replaying a spreadsheet's operations in order on another instance that started from the same workbook gives the same toJSON(), apart from per-user view state. The sheet operations carry the tab order so that concurrent adds, moves and removals can be merged without positions drifting.

The headless engine has applyOperation(operation) with the same meaning, which is what a server uses to keep the current workbook.

What converges#

Two operations made at the same time are merged by these rules. "Later" means ordered later by the authority.

Concurrent edits Result
Cells at different addresses Both are kept.
The same cell The later edit wins. The earlier author is not told; it is the same as being overwritten a moment later.
A cell edit and a row or column insert or delete The edit moves with its row or column, and its formula text is adjusted the way the engine adjusts existing formulas. An edit in a deleted row or column is dropped.
Two inserts Both are kept. At the same position the later one lands after the earlier one.
Two deletes Rows or columns deleted by both are deleted once.
An insert touching rows or columns that are deleted concurrently The insert is dropped, whichever came first.
A cell edit and an insert or delete of cells The edit moves with the cells it was typed into; an edit in deleted cells is dropped. Formula text is adjusted.
An insert or delete of cells shifting right or left, and a row insert or delete Both are kept. The shifted range moves, grows or shrinks with the rows. The same holds for a shift down or up and a column insert or delete.
An insert or delete of cells and a column change left of it (shift right or left), or a row change above it (shift down or up) Both are kept; the shifted range moves.
Two inserts or deletes of cells that cover exactly the same rows (shift right or left) or the same columns (shift down or up) Merged like two column or two row changes.
Any other pair of cell shifts on one sheet, or a cell shift and a row or column change that starts at or after the shifted range in the direction of the shift The later one is dropped. See below.
An edit on a sheet that is renamed concurrently It follows the sheet to its new name; formulas are rewritten.
An edit on a sheet that is removed concurrently It is dropped. References to the sheet become #REF!.
Two renames of one sheet, two moves of one sheet, two definitions of one name The later one wins.
Two sheets added or renamed to the same name A sheet added twice becomes one sheet at the later position. Otherwise the earlier one keeps the name and the later operation is dropped.
The last two sheets removed by two people Both are removed and one blank sheet named Sheet1 (or Sheet2, Sheet3 if taken) is left.

Whenever one of your own operations is dropped, or loses cells, because of someone else's row, column, sheet or snapshot edit, the session calls rejected({ operation, reason: 'conflict', by }) with your original operation and the operation that caused it, so you can tell the user.

A dropped insert or delete of cells cannot be taken back out of the workbook of the person who made it by another operation, because the cells behind it have already moved. The session therefore calls rejected for it and then asks the server for the current workbook (a reload, see Offline and reconnect), which also drops that client's other unsent operations. This needs a server that answers resync; the loopback provider does when it is given a workbook.

These rules are tested by applying random pairs and short sequences of concurrent operations to two engines in both orders and comparing the workbooks, and by running three clients against the loopback authority with random edits and pauses.

Snapshots#

Edits without an operation of their own are sent as a snapshot that carries the whole workbook: column widths and row heights, hiding, merging, freeze panes, conditional formats, validation, notes, comments, hyperlinks, charts, pictures, shapes, tables, sorting, filters, pivot table definitions, slicers, outline, protection, page setup, tab colours, hiding or duplicating a sheet, moving cells by cut and paste or by dragging, an insert or delete of cells that is undone or redone, typing next to a table so that it grows, editing a table header cell, inserting a column on a sheet that has tables, fromJSON() and the import methods, the sheet view toggles (gridlines, headings, direction, zero values), and undo or redo of any of these and of row, column, sheet and name edits.

A snapshot is a whole-workbook message. On a workbook with a hundred thousand cells, widening a column sends all of them. Measure this for your workbooks before relying on it.

Rules for a snapshot that races with something else:

  • Concurrent cell edits are kept. They are written into the snapshot at the same address. If the snapshot moved cells (a sort, or undoing a row insert), the edit stays at the address it was typed into, not with the row it was typed next to.
  • Concurrent row, column, sheet and name operations are dropped and reported to their author through rejected. This holds whichever came first, because a snapshot cannot be adjusted for them.
  • Of two concurrent snapshots the later one wins and the earlier change is lost without a rejected call. Two people changing a column width and a chart at the same moment end up with only one of the two changes.

What is not shared#

  • The active cell, selection, scroll position and zoom of each sheet, and the active sheet. They stay per user, and a snapshot from someone else does not change yours. Because toJSON() includes them, two users' JSON differs in activeSheet and in each sheet's view.activeCell, view.selection, view.topLeftCell and view.zoom.
  • The named sheet view a user is in, and the filter and hidden rows shown inside it. The list of views is shared; a snapshot from someone else updates the default view underneath and leaves the view on screen alone.
  • Pivot table output. Each spreadsheet recalculates its own pivot tables after every local or remote edit; the result cells are not sent.
  • Custom functions and locale settings. Register the same functions on every client.

Undo#

Undo and redo stay local: each user undoes their own steps.

  • A step that changed cells keeps working after remote edits. Its cells follow remote row and column inserts and deletes and sheet renames. A cell that someone else has written since is left out of the step, so undo never overwrites another user's newer value. A step that loses all its cells this way disappears.
  • A step for a row, column, sheet or name edit, and for anything sent as a snapshot, is stored as a before-and-after copy of the workbook. Undoing it after a remote edit would erase that edit, so the first remote operation that arrives removes these steps, and every step older than them. Steps kept as an undo and redo action (conditional formats, widths, notes and the like) survive remote cell, name, sheet add, move and rename operations, and are removed by remote row and column operations and by a remote sheet removal.
  • A remote snapshot clears the undo history.
  • When undo has nothing left because steps were removed, the next undo fires the error event once with code: 'collaboration', and the message is announced to screen readers.

In practice: in a busy session you can reliably undo your recent cell edits, and you can undo a structural edit only until the next remote operation arrives.

Presence#

A session sends your active cell and selection, at most once per presenceInterval (80 ms by default), and draws the other users' cursors in the grid: an outline around the active cell with the user's name, and a tinted outline for a multi-cell selection. Cursors follow scrolling, zoom, frozen panes and sheet switches, are shown only on the sheet they are on, and are removed when the user disconnects.

The cursors are decoration and are hidden from assistive technology. A screen reader hears "Ana Lima joined" and "Ana Lima left" through the polite live region, not every cursor move. Colours are checked as CSS colours and names are set as text; a missing or invalid colour is replaced from a fixed palette. After a remote row or column edit a cursor can be one position off until its owner moves.

TypeScript
session.getPeers(); // [{ clientId, user: { name, color }, presence: { sheet, active, ranges } }]
session.onPeersChange((peers) => renderAvatars(peers));

To draw cursors from your own presence system, without a session, call sheet.setPresence(cursors) with { id, name, color?, sheet, active, ranges? } entries, and sheet.getPresence() to read them back.

The session#

connectCollaboration(sheet, provider, options) returns:

Member Purpose
status 'connecting', 'connected', 'offline' or 'closed'.
revision The last server revision this client has applied. Store it with the workbook if you save from the client.
pending How many local operations are not yet confirmed.
getPeers(), onPeersChange(listener) The other users and their cursors.
onStatusChange(listener) Called when status changes.
disconnect() Stop sending and receiving, remove the listeners and timers, and clear the cursors.

Options: clientId (required, unique per connected client), user: { name, color? }, revision, presenceInterval and rejected.

rejected is called with { operation, reason, by?, message? } for each of your operations that was not kept:

reason Meaning
conflict A concurrent operation, given as by, dropped it or some of its cells.
reload The workbook was replaced by the server's copy before the operation was confirmed.
invalid The server refused it; message has the server's text. The session then asks for a reload, because the local workbook still has the edit.

Offline and reconnecting#

When the provider reports that the connection closed, the session goes 'offline'. The spreadsheet stays editable; operations queue up in memory. When the connection opens again the session sends its revision, receives the operations it missed, transforms its queue against them and sends the queue. Edits made offline are merged by the same rules as any other concurrent edits, so a long offline period makes dropped edits more likely.

The queue lives in memory. Closing the page while offline loses the unsent edits.

If the server no longer has the operations the client missed, it sends a reload with the current workbook. The client replaces its workbook, drops its unsent operations and reports each through rejected with reason: 'reload'. A client also asks for a reload on its own when a remote operation cannot be applied, which means its workbook no longer matches the server's.

The provider interface#

A provider opens a connection and passes messages. It does not need to understand them.

TypeScript
interface CollaborationProvider {
  connect(handlers: ConnectionHandlers): CollaborationConnection;
}
interface ConnectionHandlers {
  open(): void; // the transport is ready; called again after every reconnect
  message(message: ServerMessage): void;
  close(): void; // the transport dropped; the provider reconnects by itself
}
interface CollaborationConnection {
  send(message: ClientMessage): void;
  close(): void;
}

Messages must arrive in the order they were sent. Over a WebSocket:

TypeScript
import type { CollaborationProvider } from '@birchui/spreadsheet';

export function webSocketProvider(url: string): CollaborationProvider {
  return {
    connect(handlers) {
      let socket: WebSocket;
      let closed = false;
      const open = () => {
        socket = new WebSocket(url);
        socket.onopen = () => handlers.open();
        socket.onmessage = (event) => handlers.message(JSON.parse(event.data));
        socket.onclose = () => {
          handlers.close();
          if (!closed) setTimeout(open, 2000);
        };
      };
      open();
      return {
        send: (message) => {
          if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message));
        },
        close() {
          closed = true;
          socket.close();
        },
      };
    },
  };
}

Messages#

From the client Fields The server answers
join clientId, revision, user joined with the operations after revision, or reload. Tells the others with peer.
operation clientId, id, revision, operation ack to the sender, operation to everyone else, or rejected for a malformed operation.
presence clientId, presence peer to everyone else.
resync clientId reload.
From the server Fields
joined revision, operations, peers
reload revision, workbook, peers
operation revision, operation, clientId, id
ack id, revision
rejected id, message
peer peer: { clientId, user, presence? }
peerLeft clientId

The authority#

createCollaborationAuthority({ revision?, historyLimit? }) is the server-side half. It has no DOM dependency and runs in Node.

  • receive(clientId, baseRevision, operation, id?) validates the operation, transforms it against the operations committed after baseRevision by other clients, assigns revisions and returns the committed operations as { revision, operation, clientId, id }[]. The list is empty when the operation was dropped by a conflict and can hold more than one entry. It returns undefined when baseRevision is older than the kept history, and throws a TypeError for a malformed operation.
  • since(revision) returns the committed operations after revision, or undefined when they are no longer kept.
  • revision is the current revision.

A minimal server with the ws package. It keeps the workbook in a headless engine so it can save it and answer reload:

server.ts
import { WebSocketServer, type WebSocket } from 'ws';
import { createCollaborationAuthority, createFormulaEngine } from '@birchui/spreadsheet';

const authority = createCollaborationAuthority({ historyLimit: 5000 });
const workbook = createFormulaEngine();
workbook.fromJSON(await loadWorkbook());

const peers = new Map<WebSocket, { clientId: string; user: { name: string; color?: string }; presence?: object }>();
const send = (socket: WebSocket, message: object) => socket.send(JSON.stringify(message));
const others = (socket: WebSocket) => [...peers].filter(([peer]) => peer !== socket);
const reload = (socket: WebSocket) =>
  send(socket, {
    type: 'reload',
    revision: authority.revision,
    workbook: workbook.toJSON(),
    peers: others(socket).map(([, peer]) => peer),
  });

new WebSocketServer({ port: 8080 }).on('connection', (socket, request) => {
  const account = authenticate(request); // yours: reject the connection if this fails
  socket.on('message', (data) => {
    const message = JSON.parse(String(data));
    if (message.type === 'join') {
      const peer = { clientId: account.id, user: { name: account.name, color: message.user?.color } };
      peers.set(socket, peer);
      const missed = authority.since(message.revision);
      if (!missed) reload(socket);
      else {
        send(socket, {
          type: 'joined',
          revision: authority.revision,
          operations: missed,
          peers: others(socket).map(([, other]) => other),
        });
      }
      for (const [other] of others(socket)) send(other, { type: 'peer', peer });
      return;
    }
    const peer = peers.get(socket);
    if (!peer) return;
    if (message.type === 'presence') {
      peer.presence = message.presence ?? undefined;
      for (const [other] of others(socket)) send(other, { type: 'peer', peer });
    } else if (message.type === 'resync') reload(socket);
    else if (message.type === 'operation') {
      if (!mayEdit(account, message.operation)) {
        send(socket, { type: 'rejected', id: message.id, message: 'Not allowed' });
        return;
      }
      let committed;
      try {
        committed = authority.receive(peer.clientId, message.revision, message.operation, message.id);
      } catch (error) {
        send(socket, { type: 'rejected', id: message.id, message: String(error) });
        return;
      }
      if (!committed) return reload(socket);
      for (const entry of committed) {
        workbook.applyOperation(entry.operation);
        for (const [other] of others(socket)) send(other, { type: 'operation', ...entry });
      }
      send(socket, { type: 'ack', id: message.id, revision: authority.revision });
    }
  });
  socket.on('close', () => {
    const peer = peers.get(socket);
    peers.delete(socket);
    if (peer) for (const [other] of peers) send(other, { type: 'peerLeft', clientId: peer.clientId });
  });
});

The sketch handles one workbook, keeps everything in memory and processes each message to the end before the next, which the protocol requires. A real server needs one authority per workbook, persistence of the workbook together with its revision, and its own decision about when a rejected operation should be followed by a reload (the client asks for one itself).

The server's copy does not recalculate pivot tables or run your custom functions. Cached values in what it saves can be stale for those; every client recalculates them after loading.

The loopback provider#

createLoopbackProvider({ workbook?, historyLimit? }) is an authority and a transport in one object, in memory. Use it in tests, in demos and to keep several spreadsheets on one page in step.

TypeScript
import { connectCollaboration, createLoopbackProvider, createSpreadsheet } from '@birchui/spreadsheet';

const provider = createLoopbackProvider({ workbook: budget });
const left = createSpreadsheet(leftPane, { data: budget });
const right = createSpreadsheet(rightPane, { data: budget });
connectCollaboration(left, provider, { clientId: 'left', user: { name: 'Planning' } });
connectCollaboration(right, provider, { clientId: 'right', user: { name: 'Finance' } });

Messages are delivered synchronously and copied through JSON, as a network would. For tests, pause() holds all messages and resume() delivers them in order, which is how you make two edits concurrent; setOnline(clientId, false) drops one client's connection and setOnline(clientId, true) restores it. With the workbook option the provider keeps the current workbook (getWorkbook()) and can answer reloads; historyLimit only takes effect together with it.

Security#

  • Operations and presence are untrusted input. applyRemoteOperation() and the authority's receive() validate the shape, sheet names, addresses, numbers and limits of every operation. An invalid one is refused: the spreadsheet fires error with code: 'collaboration' and returns false, and nothing is thrown into the page. Cell styles and rich text go through the same sanitiser as loaded workbooks, a snapshot is loaded the way fromJSON() loads a file, and cell text is always rendered as text.
  • Authorisation is the server's job. The component applies whatever the provider delivers. Sheet protection, readOnly, enforceProtection and data validation are not checked for remote operations. A server that must stop a user from changing something has to refuse the operation before calling receive(); inspect operation.type, operation.sheet and the cell addresses there.
  • Do not trust the client's identity fields. Take clientId and the user name from your own session, as the server sketch does, not from the message.
  • A read-only viewer is a spreadsheet with readOnly: true whose operations the server refuses.

Limits#

  • No permissions model. There are no per-user, per-sheet or per-range rights in the component.
  • No history of who changed what. Operations are not attributed in the workbook, there is no version history and no change tracking. Keep the authority's log if you need an audit trail.
  • Scale. The protocol is tested with two and three clients and small workbooks. Nothing is known about sessions with dozens of editors. Each snapshot is a whole-workbook message, and the authority's history grows without bound unless you set historyLimit.
  • Throughput. One operation per client is in flight at a time, so a client's edits reach the others at the pace of its round trips.
  • 3-D references. The engine does not adjust Jan:Mar!B2 for row and column changes. A row or column change on a spanned sheet that races with removing Jan or Mar can leave two clients with different formula text.
  • Workbook-level names without a sheet. A defined name such as =$B$1, with no sheet name and workbook scope, that is defined while rows or columns of the first sheet change concurrently can end up different on two clients. Write names with a sheet: =Rates!$B$1.
  • Formulas that differ by nature. RAND(), NOW() and other volatile functions, custom functions and circular references under iterative calculation can show different values on different clients. The formula text is the same.
  • An edit in progress. A cell being typed in follows remote row and column changes. A remote snapshot that no longer has the sheet closes the editor without saving.
  • Cursors and selections are not transformed; see Presence.

Bridging to Yjs#

This is not a CRDT data model and it does not become one by being carried over Yjs. What you can do is use a Yjs document as the transport and the log, and keep one place that orders operations.

How. Keep one Y.Array in the document as the log of committed operations, appended to by exactly one writer, the authority. Clients apply log entries in order with applyRemoteOperation(); the index of an entry is its revision.

  • With a server in the room (a Yjs provider you run, or a headless peer), leave the authority there. A client puts each local operation, with the revision it has applied and an id, where the authority can read it: a message on your provider, or an entry in a per-client Y.Array used as an outbox. The authority calls receive() and appends the committed operations to the log. Awareness carries presence; pass it to setPresence().
  • Without a server, designate one connected client as the authority, for example the one with the lowest Yjs clientID in the awareness states. It runs createCollaborationAuthority() and is the only one that appends to the log; everyone else, including its own spreadsheet, writes to an outbox. When it leaves, the next client takes over: it rebuilds the authority's history by feeding the log through a fresh authority, receive(entry.clientId, index, entry.operation) for each index in order, and then continues. Two clients that both believe they are the authority for a moment will both append; detect that (an entry whose author is not the current authority) and have the clients reload from a replay of the log.

To write a provider for either setup, map the log and the outbox onto the messages: a new log entry by someone else becomes operation, your own entry becomes ack, and reconnecting becomes joined with the entries after the client's revision.

Why it works with this model. The model needs a total order of operations and, for each operation, the revision its author had applied. A single-writer Y.Array is such an order, Yjs delivers it to every replica and keeps it, and the transformation is unchanged.

Why the Yjs order of concurrent appends is not enough on its own. If every client appended to the log directly, Yjs would still give all replicas one order, but an entry's position would no longer say what its author had seen: entries from others can be placed before an entry that was written without knowing them, and a client's second entry depends on its first. Merging that correctly needs each entry to record exactly which entries its author had applied and a replay that transforms against the rest. createCollaborationAuthority() does not do that; it assumes revisions are a prefix of the log and that each client has one operation in flight. That is why the recipes above keep a single writer.

What you do not get.

  • No CRDT merge. Offline edits are operations that wait in the outbox and are transformed in the authority's order when the client reconnects. Conflicts are resolved by the rules above: later wins, edits in deleted rows are dropped, snapshots supersede structure edits. Nothing merges at a finer grain than a cell, and two offline clients cannot merge with each other until an authority is reachable.
  • No peer-to-peer symmetry. One client or server orders everything. If it is unreachable, edits queue.
  • A log that only grows. Compacting means agreeing on a snapshot entry and a new log.
  • Undo is the component's own, as described above, not Y.UndoManager.

If you need merging with no ordering point at all, this operation model is the wrong base; a native CRDT spreadsheet model is a different design.

↑ ↓ to move, Enter to open, Esc to close