# Collaborative documents with Yjs

> Sync a Yjs document and its cursors between the peers in a room with y-jsflow, and keep the document when the last peer leaves.

[Yjs](https://yjs.dev) is a library for documents that several people edit at once. **y-jsflow** is a Yjs provider: it syncs a `Y.Doc` and its awareness (cursors, names, selections) between the peers in a jsflow room, peer to peer, with no document server.

**jsflow keeps no room state.** A room holds peers, not data. When the last peer leaves, the document lives on only where your app saved it: in each browser with [`y-indexeddb`](https://github.com/yjs/y-indexeddb), or on your own backend. [Keeping the document](#keeping-the-document) shows both. Without one of them, an empty room is an empty document.

## Install

```sh
npm install y-jsflow yjs y-protocols jsflow-sdk
```

`yjs` and `y-protocols` are **peer dependencies of y-jsflow**: your app installs them, and y-jsflow shares your copy, which Yjs needs (two copies of Yjs in one page break it). The SDK itself depends on neither and stays at zero dependencies. y-jsflow has no dependencies of its own. Make sure your bundle holds one copy of `yjs`: with two, the provider's updates are not applied, and the page looks synced with an empty document. How the SDK's worker reaches a bundled page is in [bundlers and CSP](https://jsflow.com/docs/guides/bundlers-and-csp.md).

## Use it

Join the room yourself, then give the room and a `Y.Doc` to the provider:

```js
import * as Y from 'yjs';
import { join } from 'jsflow-sdk';
import { JsflowProvider } from 'y-jsflow';

const room = await join({ app: 'pk_…', room: 'doc-42' });
const doc = new Y.Doc();
const provider = new JsflowProvider(room, doc);

provider.awareness.setLocalStateField('user', {
  name: 'Ada',
  color: '#3366cc',
});
provider.on('synced', () => console.log('up to date'));

// when the page is done with the document:
provider.destroy();
room.leave();
```

You keep control of the join: your key, [join tickets](https://jsflow.com/docs/guides/join-tickets.md), region and `iceTransportPolicy` stay yours, and so does `room.leave()`. Use one provider per document. For two documents, use two rooms.

### Options

`new JsflowProvider(room, doc, options)`:

| option | default | |
|---|---|---|
| `channel` | `13` | The app channel (0 to 13) the provider uses for everything. Keep your own messages on other channels. |
| `awareness` | a new one | An existing y-protocols `Awareness` for this document. One the provider creates is destroyed with it. To reconnect (`destroy()`, `room.leave()`, a new `join()` and provider), give the new provider the same `Awareness`: a new one starts its clock at 0, and the others ignore it until it passes the old one. |
| `resyncMs` | `15000` | How often each peer compares state with one random peer (give or take 20 %), to repair updates lost on the way. |
| `leaveHoldMs` | `5000` | How long an unreachable peer's cursor stays before it is removed. A phone page that is briefly hidden keeps its cursor; a closed tab's cursor also stays this long. |
| `syncTimeoutMs` | `3000` | How long to wait for one peer's answer before asking the next. It is also how long a peer with nobody else in the room waits before `synced`. |

### `synced`, `awareness` and `destroy()`

- `provider.synced` is `true` once a peer's copy of the document has been applied. It is also `true` when the room had nobody else after `syncTimeoutMs`, or once every peer was asked and none answered. It never turns `false` again.
- `provider.on('synced', f)` calls `f` once, when `synced` turns true. Use it to hide a loading state. `provider.off('synced', f)` removes it.
- **`synced` is about the document, not the network.** The first peer in a room has no one to link to, so `room.state` stays `joining` while `synced` is already `true` after `syncTimeoutMs`: start editing on `synced`. When a second peer arrives the two exchange state, so what you typed alone reaches it. For a "waiting for others" indicator, use the room's `state` or its `peer` events (see [Joining](https://jsflow.com/docs/concepts/lifecycle.md#joining)).
- `provider.awareness` is the y-protocols `Awareness`. Hand it to your editor binding; set your own name and colour on it with `setLocalStateField`.
- `provider.destroy()` removes your cursor at the others at once while the page is live, stops syncing and detaches. **The room stays joined**: call `room.leave()` yourself. Called as the page unloads (a closed tab, a reload), its removal goes down with the page, and the others drop your cursor after `leaveHoldMs`.

## An editor with cursors

Any Yjs editor binding takes `provider.awareness`. With CodeMirror 6 and [`y-codemirror.next`](https://github.com/yjs/y-codemirror.next):

```js
import { EditorView } from '@codemirror/view';
import { EditorState } from '@codemirror/state';
import { yCollab } from 'y-codemirror.next';

const ytext = doc.getText('codemirror');
new EditorView({
  state: EditorState.create({
    doc: ytext.toString(),
    extensions: [yCollab(ytext, provider.awareness)],
  }),
  parent: document.querySelector('#editor'),
});
```

The [`yjs-editor` example](https://github.com/precisit/jsflow-community/tree/main/examples/yjs-editor) is this, complete: two tabs, one document, each with the other's cursor. [A shared whiteboard](https://jsflow.com/docs/guides/whiteboard.md) goes further: drawing, sticky notes, offline edits and a QR code to join.

## Keeping the document

When the last peer leaves, nothing in jsflow holds the document. Two ways to keep it, which you can combine.

**In each browser, with `y-indexeddb`.** A returning user opens their own copy at once, and edits made offline merge when they rejoin. Create the provider after the local copy has loaded:

```js
import { IndexeddbPersistence } from 'y-indexeddb';

const doc = new Y.Doc();
const local = new IndexeddbPersistence('doc-42', doc);
await local.whenSynced;         // the saved copy is in `doc`
const provider = new JsflowProvider(room, doc);
```

The provider exchanges state both ways with each peer it meets, so a joiner's offline edits reach the others, not only the other way round.

**On your backend.** Save the document's state from a client, and apply the saved state before you create the provider:

```js
const res = await fetch('/api/docs/doc-42');
if (res.ok) Y.applyUpdate(doc, new Uint8Array(await res.arrayBuffer()));
const provider = new JsflowProvider(room, doc);

const save = () => fetch('/api/docs/doc-42', {
  method: 'PUT',
  body: Y.encodeStateAsUpdate(doc),
});
let timer;
doc.on('update', () => {
  clearTimeout(timer);
  timer = setTimeout(save, 3000);   // a few seconds after a change
});
addEventListener('pagehide', save);
```

Yjs merges states, so it does not matter which client saved last, or whether two saved at once. To move or copy a document into another room, load its saved state into a new `Y.Doc` and join the other room with it.

## How it syncs

- **Edits.** An edit that fits a datagram (about 1 KB encoded, which covers most keystrokes) is broadcast. A larger one, a paste for example, goes by `sendReliable` to each peer, in parts above 64 KiB.
- **Joining.** A new peer asks one peer for the document, preferring a direct connection over a relayed one. The document crosses the network once per joiner.
- **Repair.** When an update arrives before one it depends on, the provider asks that peer for what is missing at once. The periodic exchange (`resyncMs`) covers what nothing else notices, such as a lost deletion.
- **Cursors.** Each peer sends only its own awareness state. A peer that calls `destroy()` in a live page disappears at once. One that becomes unreachable disappears after `leaveHoldMs`, and so does a page that closes or reloads: its last messages go down with it, so the others see it go quiet (about `leaveHoldMs` plus half a second).

A reload is a new peer with a new Yjs client id, and the old cursor goes after `leaveHoldMs`. See [lifecycle](https://jsflow.com/docs/concepts/lifecycle.md) for what a hidden page does.

## Limits

- **Room size** is your plan's peers per room. See [limits](https://jsflow.com/docs/guides/limits.md).
- **Document size.** A joiner receives the whole document from one peer over one reliable stream, so the size of the document is the size of every join. Measured with two peers, one joiner after a document built by the other:

  | document | path | time to `synced` |
  |---|---|---|
  | 5 MB | direct | 1.9 s |
  | 5 MB | relay only | 12.5 to 13.5 s |
  | 10 MB | relay only | 27 s |

  Keep documents to a few megabytes, or load a saved copy first (`y-indexeddb`, or your backend): a joiner that already has most of the document is sent only what it lacks.
- **Large documents through a relay need jsflow-sdk 1.1.1 or later.** With an earlier SDK a relayed link can drop and come back again and again under a transfer of several megabytes, and the document does not arrive.
- **If the one peer sending the document becomes unreachable partway**, stays away longer than `syncTimeoutMs` and nobody else is in the room, the joiner reports `synced` with what it has. The rest arrives when that peer is back.
- **Awareness.** Keep an awareness state under about 1 KB, so that it travels as one datagram. A name and a colour are tens of bytes; do not put a document in it.
- **Channel.** The provider uses one app channel, 13 unless you set `channel`.

## Next

[Choosing a state model](https://jsflow.com/docs/concepts/choosing-a-state-model.md) compares this with a chat, a game and a drawing. [Keeping state in sync](https://jsflow.com/docs/guides/keeping-state-in-sync.md) has the techniques to write yourself, for state that is not a document. [Presence](https://jsflow.com/docs/guides/presence.md) is the same idea without Yjs.

Source: https://jsflow.com/docs/guides/yjs/
