The editor instance
The runtime Edytor object behind every view, its members, the Block, Text and InlineBlock handles, and how to read state reactively.
Each <Edytor> view creates one runtime object, the editor instance. It holds the document the view renders, the selection, the plugins and the command dispatcher. You need it to read or change content from code, or to build UI around the editor (toolbars, menus, status bars).
Getting the instance
From the parent, bind it:
<script lang="ts">
import { Edytor, type EdytorInstance } from 'edytor';
let edytor = $state<EdytorInstance>();
</script>
<Edytor bind:edytor />
<button onclick={() => edytor?.historyUndo()}>Undo</button>
From a component rendered inside the editor (a block snippet, an inline block, a plugin’s UI), call useEdytor(). It reads the instance from Svelte context and throws No Edytor found outside an editor:
<script lang="ts">
import { useEdytor } from 'edytor';
const edytor = useEdytor();
</script>
The instance exists as soon as the component is created, but edytor.root stays undefined until the document is ready (edytor.synced is then true). With a sync provider that can take a moment.
Members
| Member | Type | What it is |
|---|---|---|
value |
JSONDoc |
The whole document as JSON, { data?, children } (data: the document’s properties, when it has some; the object also carries type: 'root'), the type the value prop takes. Reactive. |
data |
EdytorDocData |
The document’s properties as plain state: reactive at any depth and writable (edytor.data.title = 'Notes', each write a dispatched patchData). edytor.root.data is the same object. |
root |
Block | undefined |
The handle of the root block. root.children are the top-level blocks. |
synced |
boolean |
The view is bound to a ready document. |
document |
EdytorDocument |
The document this view renders: shared by every view of it, and usable without a view. Its own operations and reads are the raw document API (see below). |
insertBlocks, splitBlock, insertText, patchData, moveBlocks, … |
DocumentWrites |
The document’s operations, dispatched through this view: the same names and arguments as edytor.document’s, with hooks, undo, normalization, the caret they decide and the readonly check. Each answers an OpResult. See Editing programmatically and Operations. |
selection |
EdytorSelection |
The selection value and its setters. See Selection. |
transact(fn) |
<T>(fn: () => T) => T |
Run several changes as one transaction and one update. A throw from fn does not undo the changes made before it; normalization still runs on them, and fn’s error is the one thrown (a normalizer that fails then is logged). |
dispatcher |
Dispatcher |
Runs every command. dispatcher.last is the last command’s result; a command of several steps (a Tab over several sibling groups, Turn into over several blocks) reads applied when any step applied. dispatcher.lead(plan, body), dispatcher.plan(operation, payload, prepare, block?) and dispatcher.caret(caret, ops?) let a plugin issue one refusable command of its own. See Triggers: one plan. |
idToBlock |
Handles |
Handle lookup: get(id) (live blocks only), block(id), has(id). |
canMove(req), move(req) |
Block moves relative to a target or one step in a direction, resolved to the document’s move and announced. See Commands. | |
historyUndo(), historyRedo() |
() => void |
Undo and redo, restoring this view’s selection. Each call sets dispatcher.last: applied, noop when the stack is empty, or refused in a readonly view or a read-only document. See History. |
readonly |
boolean |
Whether the view refuses edits. Follows the readonly prop. |
node |
HTMLElement | undefined |
The editable root element, once mounted. |
overlay |
Overlay |
The chrome layer beside the root, overlay.layer once mounted. overlay.add(measure) runs measure(origin) once per invalidated frame: it reads layout (origin is the layer’s rect) and returns its DOM writes, which run after every measure has read. overlay.mount(component, props, name, zIndex, measure) mounts a component in a fixed host placed by measure(host, origin); overlay.invalidate() asks for a frame. add and mount answer their teardown. See Styling. |
blocks, marks, inlineBlocks |
Map<string, Definition> |
The registered definitions, by type. |
kinds |
KindRow[] |
The kind catalogue. See Blocks. |
commands, runCommand(id) |
Registered commands (block.heading2, …) and an async runner that resolves to false when the command is missing or disabled. |
|
defaultChild(parent) |
(parent: Block) => string |
The type a new child of parent takes. |
awareness |
Awareness |
The document’s presence channel. See Collaboration. |
cells |
Cells |
The reactive render state, one cell per visible block (below). |
focus() |
() => void |
Focus the editor without scrolling, as a click in it would: the selection it has stays, and with none the caret goes to the start of the first text. For a menu button or a shortcut outside the editor. |
clear() |
() => boolean |
Replace the whole document with one empty block and put the caret in it, as one undo step (the document’s properties, edytor.data, stay). It is a command: a readonly view or a read-only document refuses it (it answers false, and dispatcher.last reads refused), so a viewer never wipes the shared document. Plugin hooks do not see it. |
edytor.document and its operations
edytor.document is the EdytorDocument: it owns the CRDT document, the shared history, awareness, and the document’s operations and reads. Several views can render one document; see Collaboration.
edytor.document is also the raw path: it has every document operation (insertText, formatRange, insertBlocks, moveBlocks, …) and read (toJSON, childrenIds, blockTypeOf, anchorAt, …). Its operations are raw document writes: they skip plugin hooks, normalization, the undo policy and the view’s readonly. The view has the same operations under the same names (edytor.insertText(…)), dispatched: they do all of these. Commands compares them. edytor.document.history is the raw path for undo in the same way: its undo() and redo() replay the document’s shared history without the view’s readonly and without restoring a selection; a view undoes with historyUndo()/historyRedo() (History).
While the document has no block, the view shows a local empty paragraph (its handle is edytor.root.children[0]); the first command in it creates the block. The document’s own reads do not see it, and the JSON (edytor.value) never contains it.
Handles
Block, Text and InlineBlock are handles: small read-only objects that name a piece of the document by id and read the current state from the document each time you access a getter. To change what they name, pass their ids to the view’s operations.
const block = edytor.idToBlock.get('page-title'); // undefined if not live
if (block) {
block.type; // 'heading'
block.data; // { level: 'h1' }
block.children; // Block[]
block.firstText?.stringContent; // 'A calmer place to think'
block.value; // this block's JSONBlock
}
Handle getters are reactive. Read in a template, a $derived or an $effect, a getter depends on the cells its answer comes from, so {block.type} updates when the block is retyped, here or by a peer, and block.children, block.content, text.stringContent or block.isInTree follow their commits too. Read anywhere else (an event handler, a command), a getter is a plain read of the document. block.data, atom.data and edytor.data are reactive at any depth too, and writable like state: block.data.title = 'Plan' is a dispatched patchData (see Properties).
<script lang="ts">
import type { Block } from 'edytor';
let { block }: { block: Block } = $props();
// Re-runs when the block is retyped or its children change, by anyone.
const label = $derived(`${block.type} · ${block.children.length} children`);
</script>
{#if block.isInTree}<span>{label}</span>{/if}
What a getter depends on: type, children, content and isInTree the block’s own cell; parent and index that cell and its parent’s (a move patches the parent’s child list); a Text’s and an InlineBlock’s getters their block’s cell; value (the block’s JSON, its subtree included) every commit. Getters that derive from these (isEmpty, firstText, depth, definition, …) follow them.
| Handle | Identity | Useful members |
|---|---|---|
Block |
One per block id: the same object for as long as the block exists. | id, type, data, parent, children, content, index, depth, firstText, lastText, value, isInTree, isEmpty (no content and no children; an inline atom is content, so a block holding only a mention is not empty), hasContent, movable, convertible (false for a void block, an island and a list container; true for an emptied document’s virtual paragraph, which a Turn into creates with its kind; a divider, from Turn into or insertDividerAtSelection, is created with a paragraph after it), isContainer (it renders only its children, like a list), isListItem, list (the list an item shows in, also after it was outdented out of a nested list into the item holding it), node, textAtOffset(offset) (the text segment that shows a block offset). It only reads: write with the view’s operations and its id (edytor.splitBlock(block.id, …)). |
Text |
A text segment of a block: the ordinal-th segment between inline blocks. It has no identity beyond that position. |
parent, ordinal, segStart (its first block offset: its offset o is the block’s segStart + o), stringContent, length, value (runs), getMarksAtRange(start, end), isInDocument, node. |
InlineBlock |
One per inline block id. | id, type, data, parent, value, selected, isInDocument. Its data is writable like state (atom.data.name = 'Ada'). |
Because a Text is a position, don’t keep one across edits to find “the same text” later. Keep the block id and an offset, or a selection anchor.
A handle can outlive what it names. Check block.isInTree, text.isInDocument or atom.isInDocument before acting on one you stored; idToBlock.get(id) returns undefined for a block that is gone.
Inside a command, handle getters see the command’s own earlier writes, so a normalizer or a plugin can read the state its operation produced.
Reading state reactively
Use these in templates, $derived and $effect:
-
Block snippets receive a view object,
block, whosetype,data,selectedandfocusedare reactive.block.handleis the block’s handle, for its id and its reads (undefinedin a suggestion’s preview); its getters are reactive too.{#snippet callout({ block, content })} <span>{block.data.icon}</span> {@render content()} {#if block.selected}<small>selected</small>{/if} {/snippet} -
edytor.cellsis the render state:cells.rootIds(the top-level ids) andcells.get(id), a frozen{ id, type, data, childIds, runs }that is replaced whenever the block changes. Both are reactive:<script lang="ts"> import type { EdytorInstance } from 'edytor'; // The editor a page bound with `bind:edytor`, passed down. let { edytor }: { edytor: EdytorInstance | undefined } = $props(); const outline = $derived( (edytor?.cells?.rootIds ?? []) .map((id) => edytor!.cells!.get(id)) .filter((cell) => cell?.type === 'heading') ); </script> -
edytor.data(the document’s properties) and thedataof a block or inline block are reactive proxies:{edytor.data.title}updates when anyone changes it. -
edytor.valueis reactive and recomputes the whole JSON after each change. Fine for a word count or a save button; usecellsor the handles for anything per block. -
onDocChange(an<Edytor>prop and a plugin hook) receives each commit’s change report, aDocChange: the blocks added, removed and moved, those whose type or data (meta) or content changed, and the new child order of each parent that changed. UnlikeonChange, it exports nothing, so it costs nothing on a large document. The report is the document’s own, shared with every other consumer and view, so it is read-only; a consumer that throws is logged and the others still run. Readedytor.valuefrom it only when you need the JSON (a debounced save):import type { DocChange, EdytorInstance } from 'edytor'; // `<Edytor onDocChange={autosave(edytor, save)}>`: one export a second at most. export const autosave = (edytor: EdytorInstance, save: (json: unknown) => void, delay = 1000) => { let timer: ReturnType<typeof setTimeout> | undefined; return (_change: DocChange) => { clearTimeout(timer); timer = setTimeout(() => save(edytor.value), delay); }; }; -
edytor.selection.valueandselection.projectionare reactive, as areselection.selectedBlocksandselection.focusedBlocks.
Everything else, including the document’s reads and definitions, is imperative: read it when you need it.