Skip to content
Edytor
Esc
↑↓navigate↵open⌘Jpreview
On this page

Documents

Create, load, share and destroy an EdytorDocument, and understand when it is ready to edit.

An EdytorDocument is the thing views render and providers sync. Create one yourself when you want to share it between views, edit it without a view, attach a provider from code, or control its lifetime.

Create a document

import { createDocument } from 'edytor';

const document = createDocument({
  value: { children: [{ type: 'paragraph', id: 'p1', content: [{ text: 'hello' }] }] },
  actor: { id: 'user-42', name: 'Ada', color: '#7559ee' }
});

document.readiness; // 'local'
document.transact(() => document.insertText('p1', 5, ' world'));
document.blockText('p1'); // 'hello world'
document.history.undo(); // 'hello' again; the seed itself is never an undo step
Option Type Description
value JSONDoc Initial content and document properties (data), seeded immediately: the document is ready at once. Without it, the document stays pending until a provider or sync() decides. To seed only when a room turns out empty, pass value to attachSync instead (see the warning below).
actor { id, name?, color? } The local author. id is stored in attribution; name and color are published as presence. Defaults to an anonymous anon-<uuid>.
awareness Awareness Use an existing awareness instance instead of creating one. The document does not destroy a borrowed instance.
history { captureTimeout?: number, limit?: number } captureTimeout: edits closer together than this many milliseconds merge into one undo step. Engine default: 500. 0 makes every commit its own step. limit: the undo steps kept, 200 by default (DEFAULT_HISTORY_LIMIT); an older step is dropped and the deleted content it kept is released. Infinity keeps every step.
semantics DocumentSemanticsConfig Block roles (void, island, lines, layout), kinds without content, default child types, the default block type and mark edges (marks: { link: { edge: 'side-dependent' } }: where text a collaborator types at a mark’s edge lands while it is being set). Views contribute these from their plugins. Defaults to defaultSemantics, the bundled rich-text, code, image, media and columns kinds (richTextSemantics, codeSemantics, imageSemantics, mediaSemantics, layoutSemantics each hold one plugin’s; mediaSemantics the embed, bookmark, file, video and audio plugins’), which the room holds too; {} checks no roles.

A document edited with no view attached obeys these roles: it refuses to merge text into a divider or to move a code line out of its code block, edits no view could render. If your plugins add kinds of their own, pass them too, merged with the bundled ones: semantics: mergeSemantics(defaultSemantics, semanticsOf(myKinds)) (see Block roles). A view whose plugins redefine a bundled kind (an image that is not void) throws SemanticConflictError on such a document: give it the view’s rules, or semantics: {}. With semantics: {} the document applies every edit the tree allows.

Load saved bytes

document.encode() returns the full replicated state as a Uint8Array. loadDocument restores it as a fresh replica with a new client id:

import { createDocument, loadDocument } from 'edytor';

const document = createDocument({ value: { children: [{ type: 'paragraph', content: [{ text: 'hello' }] }] } });
const bytes = document.encode(); // store or send it
const copy = loadDocument(bytes); // readiness 'hydrated'
copy.toJSON(); // same JSON as the source

loadDocument checks the bytes on a scratch copy first. Corrupt bytes (a v13 yjs document’s among them) throw UndecodableUpdateError, and a schema this build cannot own throws SchemaMismatchError. Your bytes are never modified.

The document object

Member Description
Operations and reads The document’s own: insertBlocks, insertText, toJSON, childrenIds, order queries, onChange… (DocumentOperations). See the document API reference.
history The shared undo manager (undo(), redo(), stopCapturing()). Throws DocumentNotReadyError while the document is pending.
clearHistory() Empty the undo and redo stacks. Otherwise they keep the newest history.limit steps (200 by default).
endHistory() End this session’s history (a view calls it when its page leaves for good): its steps are released, and what it deleted goes at the room’s next purge. See history.
attribution Per-block authorship: block(id) returns createdBy, contributors and lastChangedBy; actorOf(clientID) the actor of a client id that wrote (a replica’s binding goes with its first write, so a page that is only read writes nothing).
awareness The one presence instance for every view and provider. See Presence.
actor The local author identity.
transact(fn) Run several edits as one transaction and one undo step. A throw from fn does not undo the writes made before it: they are kept and synced.
encode() The full state as bytes, for loadDocument.
attachSync(sync, { value? }) Attach a provider to the document. Returns its cleanup.
ready, readiness, onReady(fn) Whether the content has been decided, and how. See below.
syncRefusal, onSyncRefused(fn) The SyncRefusedError a provider reported when the server refused this client (close 1008, or 4xxx other than 4401). It lasts until that provider is released or syncs again.
sync(value?) Decide a pending document now: seed value if it is empty, adopt its content otherwise.
writable, onWritableChange(fn) false while the document holds content from a schema this build cannot own. Every write is refused and providers stop persisting and sending until it heals.
clientID This replica’s CRDT client id (doc.clientID).
doc The underlying CRDT document, for providers and advanced code.
destroy() Release the document: providers, history, awareness and the CRDT document.

Readiness

A document created without a value might be about to receive content from a provider, so it does not seed anything until that question is settled.

readiness Meaning What works
pending Undecided: a provider may still bring content. Reads, attachSync, sync(), destroy(). history throws.
local This replica seeded the content. Everything.
hydrated The content came from a provider or from loadDocument. Everything.

With providers attached, the rule is settle or bound:

  • A document that already holds content becomes hydrated as soon as any provider settles, or is refused.
  • An empty document seeds its value only once every attached provider has settled, failed, been removed, or reached its bound.
  • IndexedDB always settles, so it has no bound. A WebSocket alone in a new room may never hear from anyone, so it gets DEFAULT_READINESS_BOUND (1000 ms), counted from the moment the socket opens or first fails to open: a room that is slow to accept the connection is waited for, up to the socket’s connectTimeout (10 s by default). Expired credentials (4401) before the first sync hold the bound: an empty document waits for a dial that gets in.
  • A server refusal (SyncRefusedError) never seeds: an empty document stays pending and reports it in syncRefusal and onSyncRefused. A document that already has content keeps it and becomes hydrated, so a view mounted on it shows that content. The refusal belongs to the provider that reported it: once that provider is released (its cleanup ran) or syncs again (connect() after a refreshed token), the rule above applies to the providers still attached, and an empty room seeds value. Released with no provider left, the document stays pending until the next attachSync or sync().
import { createDocument } from 'edytor';

const document = createDocument(); // no value, no provider yet: pending
if (!document.ready) {
  const off = document.onReady(() => console.log(document.readiness));
}

onReady fires once, at the transition; it is never called for a document that is already ready.

Require hydration

createDocument({ requireHydration: true }) (also attachDocument, and the <Edytor requireHydration> prop for the document a view owns) decides an empty document only when a provider synced: the room answered, or a local copy loaded. A provider’s bound or failure never seeds it, so a first visit made offline writes nothing, instead of a value that a different seed in the room would later meet as duplicate blocks. The document stays pending until it is fetched once, and a view keeps it read-only meanwhile (its commands are refused). A document that holds content is decided as before, and an explicit sync() still decides. An empty room that answers is seeded with value as usual. A reattach naming another requireHydration is a SemanticConflictError.

Attach a provider

attachSync takes the same factories as the <Edytor sync> prop. The document keeps one provider per target (one IndexedDB name, one server and room), so attaching the same target twice does nothing.

import { createDocument, createWebsocketSync } from 'edytor';

const document = createDocument({ actor: { id: 'user-42' } }); // pending
document.attachSync(
  createWebsocketSync({ server: 'wss://rooms.example.com/rooms', room: 'doc-42' }),
  { value: { children: [] } } // seeded only if the room turns out empty
);

document.destroy() runs every attached provider’s cleanup. Calling the returned cleanup yourself detaches that one provider.

One document, several views

Pass the same document to several <Edytor> views. They share one document API, one undo history and one awareness; undo restores the caret in the view that issued it.

<script lang="ts">
  import { onDestroy } from 'svelte';
  import { Edytor, createDocument, createIndexeddbSync } from 'edytor';

  const document = createDocument();
  document.attachSync(createIndexeddbSync('notes/today'));
  onDestroy(() => document.destroy());
</script>

<Edytor {document} />
<Edytor {document} readonly />

A view never destroys a document you passed in: you created it, you destroy it. Views contribute the structural rules of their plugins (void and island blocks, default children) to the document. Two views whose plugins disagree on a rule throw SemanticConflictError. See the Edytor component for the view’s props.

Headless use (Node and SSR)

Import from edytor/crdt/edytor in code that cannot load Svelte components. It exports the document API edytor does, with the document’s full vocabulary (toBlockSpec, BlockSpec, …), without the component:

import { loadDocument, toBlockSpec } from 'edytor/crdt/edytor';

export function appendLine(saved: Uint8Array, text: string): Uint8Array {
  const document = loadDocument(saved, { actor: { id: 'server-bot' } }); // the bundled kinds' roles
  const index = document.childrenIds(null).length; // append at the root
  document.insertBlocks({ parent: null, index }, [toBlockSpec({ type: 'paragraph', content: [{ text }] })]);
  const bytes = document.encode();
  document.destroy();
  return bytes;
}

Deterministic seeds

Seeding a value is deterministic: the seed is written under a writer id hashed from the value, and blocks without an id get ids derived from the same hash. Two replicas that seed the same template write the same data, so their seeds merge into one copy instead of two, and a late identical seed never erases an edit.

import { createDocument } from 'edytor';

const template = { children: [{ type: 'paragraph', content: [{ text: 'Agenda' }] }] };
const a = createDocument({ value: template });
const b = createDocument({ value: template });
// Merging a and b shows one "Agenda" paragraph, not two.

Seeds are not undo steps and carry no author (createdBy is absent on seeded blocks). Seeds of different values merge as a union: blocks with different ids all show, so give a template new block ids when its content changes.

When a seed shares a block id with content it meets, one version of that block wins, last-writer-wins by writer id:

The block was written by Result
A person editing (a live replica) The seed loses. Seed writer ids sit below 2^26 and live ones are random 53-bit ids, so the block and every edit in it stay.
The same seed Nothing changes: it is the same data.
A different seed The larger writer id wins, whichever arrived first. If the loser is the room’s copy, its edits since that seed are replaced, on every replica, and no undo brings them back.

So never pass a snapshot that changes (a copy of onChange output) as value beside a room: a client that seeds it late, because it could not reach the room before its readiness bound, puts that snapshot in the last row. Pass a fixed template, or no value at all.

Errors

Error When
DocumentNotReadyError history used while the document is pending.
DocumentDestroyedError The document is used after destroy(), or attachSync runs on a destroyed document.
SemanticConflictError A view or option declares a block rule that contradicts one the document already adopted.
UndecodableUpdateError loadDocument bytes cannot be decoded.
SchemaMismatchError The content claims a schema this build cannot own.

Was this page helpful?