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

Suggestions

Propose changes for review. An AI draft shown only in your view until you accept it, or shared suggestions in the document, which every collaborator sees and a writer accepts or rejects, as in Google Docs.

A suggestion is a change proposed for review. edytor.suggestions holds two kinds in one list, told apart by suggestion.shared:

  • View-local (the default): content a view proposes at a position, such as an AI draft, a completion or a rewrite. It shows only in the view that made it, rendered with the document’s own kinds inside a tinted, non-editable preview, until it is accepted or discarded. Before accept() nothing reaches the document: no other tab or collaborator sees it, presence does not carry it, onChange does not fire, and it adds no undo step. accept() writes it as one command and one undo step, which then syncs like any edit.
  • Shared, with the shared suggestions plugin: a change written into the document as a proposal. Every collaborator sees it with its author, a reload keeps it, and a writer accepts or rejects it. A view in suggesting mode writes each of its edits this way, and an AI answer streams into the document as it arrives.
<script lang="ts">
	import { Edytor, type EdytorInstance } from 'edytor';

	let edytor = $state<EdytorInstance>();

	const propose = () => {
		const block = edytor?.selection.caret?.block;
		if (!edytor || !block) return;
		edytor.suggestions.add({ after: block.id }, [
			{ type: 'heading', data: { level: 'h2' }, content: [{ text: 'Next steps' }] },
			{ type: 'todo-item', data: { checked: false }, content: [{ text: 'Book the review' }] }
		]);
	};
</script>

<button onmousedown={(event) => event.preventDefault()} onclick={propose}>Suggest</button>
<Edytor bind:edytor />

Add createSuggestionsPlugin() to bind Mod+Enter, Escape, and Tab to it, and createSuggestionBarPlugin({ bar }) to render a bar under the preview (Accept, Discard): see Keyboard shortcuts and bar.

Positions

edytor.suggestions.add(at, content?, options?) takes one of these positions:

at Shown Accepting it
{ after: id } As the next siblings of block id (after its children) Places the blocks there
{ before: id } As the previous siblings of block id Places the blocks there
{ inside: id } As the last children of block id Places the blocks there. A block that holds no children (a void, a code line) throws at add
{ end: id } As ghost text after block id’s text: the first block’s content (more blocks show after the block) Inserts that content at the end of the text, as typing would; more blocks follow
{ replace: [ids] } The blocks are marked as removed (data-edytor-suggestion-replaced) and the content shows after the last of them. Blocks that hold nothing (an empty line, as when the user asks AI on one) fold away (data-edytor-suggestion-replaced="empty") and the content shows in their place; typing in the folded line unfolds it Deletes the blocks and places the content in the first one’s slot, in one plan. Their children that are not replaced stay, after the content
{ replace: 'selection' } Resolved when added (below)

replace: 'selection' reads the selection once, at add:

  • a block selection becomes { replace: ids }, its members (a selected list or code block with its items or lines);
  • a text range becomes { replace: { anchor, focus } }, the range’s anchors, marked in the overlay; the content shows after the range’s last block, and accepting deletes the range and pastes the content at its caret (the first block’s text joins the line, as a paste does), as one undo step;
  • a caret becomes { after: block };
  • no selection throws.

suggestion.at is the position as resolved (null for a shared suggestion another view made: its changes say where it is). A position names blocks by id (a range, by anchors), so it follows them through edits elsewhere, a collaborator’s included. add throws when the position names no shown block.

The content goes in as a paste of those blocks would: in a list, a plain paragraph becomes the list’s item; in a code block, lines become code lines; the other kinds keep their kind and data.

Content and streaming

content is JSONBlock[] (the document’s JSON) or a string. A string becomes paragraphs split on blank lines (at an end, one text run, newlines kept). The paragraph kind is the default child of the position’s parent, so a string inside a code block gives code lines. To read markdown, pass textToBlocks(text).

A suggestion added without content starts streaming; with content it starts ready (options.status overrides both). Then:

  • suggestion.update(content) replaces the content. Call it on every chunk with everything received so far;
  • suggestion.append(text) adds text to the last block’s text (a new paragraph when there is none). Away from an end, a blank line in the text starts a new paragraph, even when it arrives split across two chunks;
  • suggestion.done() sets status to ready.

The preview updates as the content does, and following blocks move down. The user can type, select and edit elsewhere meanwhile: the suggestion stays where it is.

Streaming from an AI

Read the response body as text and append each chunk, then mark the suggestion done:

import type { EdytorInstance, Suggestion } from 'edytor';

/** Stream the model's answer into `suggestion`; Try again streams a new one. */
const stream = async (suggestion: Suggestion, prompt: string) => {
	const response = await fetch('/api/draft', { method: 'POST', body: JSON.stringify({ prompt }) });
	if (!response.body) return suggestion.discard();
	const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
	for (;;) {
		const { done, value } = await reader.read();
		// Accepted or discarded meanwhile: stop reading.
		if (done || !suggestion.live) break;
		suggestion.append(value);
	}
	suggestion.done();
};

/** Ask for a draft after the caret's block. */
export const draft = (edytor: EdytorInstance, prompt: string) => {
	const block = edytor.selection.caret?.block;
	if (!block) return;
	const suggestion = edytor.suggestions.add({ after: block.id }, undefined, {
		label: 'AI',
		onRetry: (again) => void stream(again, prompt)
	});
	void stream(suggestion, prompt);
};

/api/draft is your endpoint, which calls the model and streams its text back. For a model that answers in markdown, keep the text received so far and replace the content with its blocks on each chunk, read with edytor/export’s textToBlocks and streaming: true: a line still arriving shows only what the next chunk cannot turn into another kind or mark (no **bol or | A | B flashing as raw text). Once the stream ends, read the whole text once more without it:

import type { Suggestion } from 'edytor';
import { textToBlocks } from 'edytor/export';

/** Stream the model's markdown answer into `suggestion`, its kinds and marks as they arrive. */
export const streamMarkdown = async (suggestion: Suggestion, response: Response) => {
	const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader();
	let markdown = '';
	while (true) {
		const { done, value } = await reader.read();
		if (done || !suggestion.live) break;
		markdown += value;
		suggestion.update(textToBlocks(markdown, { streaming: true }));
	}
	suggestion.update(textToBlocks(markdown));
	suggestion.done();
};

Accept and discard

suggestion.accept() writes the content and answers an OpResult ({ status, ids }):

  • One command. It runs through the dispatcher as acceptSuggestion, with the payload { suggestion: { id, at, content } }. onBeforeOperation sees the command, then each step it plans (insertBlocks, deleteBlock, insertText…; for a text range, the range’s deletion), and can refuse it with prevent(). dispatcher.last records the result.
  • One undo step. The content and anything it replaces go and come back together. Typing right after it is a step of its own.
  • Fresh ids. The blocks and atoms get new ids; the ids in content are ignored.
  • The caret ends the content: the end of the last block’s last line.
  • Refused (status: 'refused'): a readonly view, a read-only document, a veto, or a position the document no longer accepts. The suggestion stays, so the user can discard it.

Once accepted, the suggestion is gone from the list. Accepting while it streams writes what it holds at that moment.

suggestion.discard() drops it and writes nothing. A suggestion is also dropped when its block is deleted, by this view or a collaborator: a block of replace, or a block holding an end of its range. It survives everything else, the selection leaving its block included.

suggestion.retry() empties it, sets it streaming and calls options.onRetry(suggestion), where you stream another answer into it. Without onRetry it does nothing, and suggestion.retryable is false.

Shared suggestions

Shared suggestions are a plugin, createSharedSuggestionsPlugin(): list it and the view reads and writes them; without it, the bare <Edytor /> ships none of their code. It requires a collaborative CRDT document — render <CollaborativeEdytor> or pass document={createDocument()} (mounting it on a local <Edytor> logs a warning in development and is a no-op). Its controller, sharedSuggestionsController(edytor), holds suggesting mode, the pending changes and the decisions:

<script lang="ts">
	import {
		CollaborativeEdytor,
		createSharedSuggestionsPlugin,
		sharedSuggestionsController,
		type EdytorInstance
	} from 'edytor';

	const plugins = [createSharedSuggestionsPlugin()];
	let edytor = $state<EdytorInstance>();
	const shared = $derived(edytor && sharedSuggestionsController(edytor));
	const suggesting = $derived(shared?.suggesting ?? false);
	// Writers decide; a suggest-only user's view can accept nothing.
	const pending = $derived(edytor?.suggestions.list.some((s) => s.shared && s.canDecide) ?? false);
</script>

<button
	aria-pressed={suggesting}
	onmousedown={(event) => event.preventDefault()}
	onclick={() => shared && (shared.suggesting = !suggesting)}
>
	{suggesting ? 'Suggesting' : 'Editing'}
</button>
{#if pending}
	<button onclick={() => shared?.acceptAll()}>Accept all</button>
	<button onclick={() => shared?.rejectAll()}>Reject all</button>
{/if}
<CollaborativeEdytor
	bind:edytor
	{plugins}
	server="wss://rooms.example.com/rooms"
	room="doc-1"
	actor={{ id: 'ada' }}
/>

With it, edytor.suggestions.list holds the shared suggestions after the view-local ones (suggestion.shared is true: a SharedSuggestion), and the document’s toJSON() leaves the pending ones out (who sees what). List it in every view of a document under review: a view without it shows their text as plain content.

Suggesting mode

Set suggesting on the controller and the view’s edits become a shared suggestion of its user’s, as in Google Docs. Every write of the view goes through it while it suggests, whatever made it: typing, Backspace and Delete, an input method, a paste, a drop, Turn into, the toolbar’s marks, a find and replace, a plugin’s command.

What the user does What is written Shown as Accepted Rejected
Types, pastes text The text, as the suggestion’s An inserted run, in the author’s colour The text stays The text goes
Deletes someone’s text A proposal naming the text: nothing is deleted yet A struck run; the caret moves past it as if it were gone The text goes The text stays
Deletes text of their own pending suggestion The deletion itself: nobody else’s content changes — — —
Presses Enter, pastes blocks The new blocks The block marked inserted (a split’s new line: split) The blocks stay The blocks go (a split joins the line it came from)
Deletes blocks (a block selection’s Delete) A proposal naming the blocks: nothing is deleted yet The block marked removed The blocks go (their children take their place) The blocks stay
Merges lines (Backspace at a line’s start), retypes a block, changes its data, formats text, moves, nests or outdents blocks (a drag, a move key, a handle move, a beside drop, Tab) Nothing: refused, and the view says so (on the user’s own pending blocks, written directly) — — —
  • One suggestion per contiguous edit. Edits continue the suggestion the view is writing while they touch the block it last wrote in or the block before or after it; an edit anywhere else starts another. Switching suggesting ends both the undo step and the suggestion.
  • The suggester’s own undo withdraws what it suggested, and its redo suggests it again.
  • Only text and blocks are suggested. A merge, a retype, a data change, a format and a move are refused while the view suggests (canMove is false), announced to assistive technology with the suggestions.notSuggested label; on the user’s own pending blocks (a line they just added) they are written directly. Accept or reject the pending suggestions first, or switch to editing.
  • A user who may only suggest (the room’s suggest access, document.access) always suggests: suggesting reads true from the moment the room tells the view, and the room refuses any other write from them. Until the room’s word arrives, the view writes as it would, and the room strips those writes: set suggesting yourself, from your own permission model, before the view connects (the same one your authorize reads).

Reviewing

A shared suggestion’s changes are what it proposes, in document order (reactive), and the controller’s changes() is every pending change of the document. Each SuggestedChange is one run or block:

PropType
suggestion?string

The suggestion it belongs to (its id).

Typestring
kind?'insert' | 'delete' | 'block' | 'split' | 'remove'

Inserted text, text proposed for deletion, an inserted block, the line a split made, or a block proposed for deletion.

Type'insert' | 'delete' | 'block' | 'split' | 'remove'
block?string

The block it is in or about.

Typestring
offset?number

Its run's start, in the block's offsets (an atom counts 1).

Typenumber
length?number

Its run's length (a block's: the whole block).

Typenumber
text?string

Its text.

Typestring
  • suggestion.accept() and suggestion.reject() decide all its changes: one command each, acceptSuggestion and rejectSuggestion with the payload { changes }, one undo step, which hooks see and can refuse like any command. The controller’s decide(changes, accept) decides some of them (one change, the changes of a block), and acceptAll() and rejectAll() every pending one.
  • A decision writes only what changes. The text that goes is deleted by the reviewer (their own delete, which their undo takes back), a block that goes is the reviewer’s block delete (its children take its place), a rejected line split joins the line it came from. The text and blocks that stay are marked settled, so they read as ordinary content from then on.
  • The reviewer’s undo makes the changes pending again.
  • Who decides. A view that may write and whose user may write (document.access is 'write') accepts and rejects (suggestion.canDecide). A read-only view and a suggest-only user’s view list the pending suggestions and decide nothing: their accept() answers refused.
  • The author takes it back by rejecting it. suggestion.discard() on a shared suggestion rejects it, the same command as a reviewer’s reject(); its author (suggestion.mine) may, even from a view that may not decide (a suggest-only user’s). Nothing of it stays pending and the text is as it was.
  • Two reviewers at once. Decisions compose: when one accepts and the other rejects the same change at the same time, the text that one of them takes away goes on every replica.
  • suggestion.by is its author’s actor id and suggestion.via the agent that wrote it for them ('ai'); edytor.document.attribution.actors.get(by) has their name and colour.

AI answers shared live

Add a suggestion with the controller’s add and what you stream into it is written into the document as it arrives: every collaborator watches the answer being written, then a writer accepts or rejects it, as one suggestion. It is attributed to the user who asked, with via: 'ai' (the bar shows “Ada (AI)”; pass via to name another agent):

import { sharedSuggestionsController, type EdytorInstance } from 'edytor';
import { textToBlocks } from 'edytor/export';

/** Stream the model's markdown answer after the caret's block, shared with everyone as it arrives. */
export const askShared = async (edytor: EdytorInstance, response: Response) => {
	const block = edytor.selection.caret?.block;
	const shared = sharedSuggestionsController(edytor);
	if (!block || !shared || !response.body) return;
	const suggestion = shared.add({ after: block.id }, undefined, { label: 'AI' });
	const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
	let markdown = '';
	for (;;) {
		const { done, value } = await reader.read();
		if (done) break;
		markdown += value;
		suggestion.update(textToBlocks(markdown, { streaming: true }));
	}
	suggestion.update(textToBlocks(markdown));
	suggestion.done();
};
  • Only what changed is written. Each update keeps the blocks that are the same, extends the last block’s text when the new one extends it, and replaces the rest. A markdown answer of 257 characters streamed word by word (60 chunks) syncs about 3.5 KB in all, 58 bytes a chunk, and stores 2.1 KB, against 1.8 KB for the same blocks written at once.
  • Positions. after, before, inside and a replace of blocks or of a text range (proposed for deletion, the answer after it). An end suggestion is a completion of this view’s line, never shared: add makes a view-local one there.
  • The answer is its own suggestion: the user’s edits meanwhile, suggested or not, are not part of it. It is written outside the user’s undo history; discard() rejects it.

Who sees what

  • Every view of the document shows the pending shared suggestions, read-only views and readonly users included: the inserted runs and blocks, the struck runs, the marked blocks, and their bars (Suggested, without Accept).
  • toJSON() is the document without its pending suggestions once the plugin is listed (or the document built for them): the document as shown, on a copy with every pending suggestion rejected (the inserted text and blocks left out, a split’s line joined back to the line it came from, the proposed deletions not applied). While any suggestion is pending, each read costs that copy, a whole-document cost of about a document load (on a laptop, some 70 ms more per 1,000 blocks): onChange reads it at every change, so read edytor.value only when you need it on a large document under review. With no pending suggestion it costs nothing extra. toJSON({ suggestions: true }) is the document as shown. edytor.value, the room’s onSave value, a version in the history and the blocks a move exports are the document without them; the room’s update, the browser’s copy and a reload keep them. Copying in the editor takes the text as shown.
  • A version restore drops the pending suggestions: the restored document has none, and the restore’s undo brings them back.
  • The decision trail (what was accepted and rejected, by whom) stays in the document until the room’s purge removes a suggestion decided before its horizon, as it removes other deleted content.

A view without the plugin

A view that does not list createSharedSuggestionsPlugin() reads a document’s shared suggestions as plain content:

  • It shows a pending insertion’s text and blocks as ordinary text and blocks, unmarked, and text or blocks proposed for deletion as they are, not struck: a proposal holds nothing until a writer accepts it. Its edytor.suggestions.list has only its view-local suggestions.
  • Its exports include them: its toJSON(), edytor.value and onChange are the document as shown (toJSON({ suggestions: true }) of a view with the plugin), unless another view of the same document object lists the plugin, which builds them for the document.
  • Its edits are direct: typing inside a pending insertion adds text of its own (not the suggestion’s), deleting it deletes it for real, and so does deleting text proposed for deletion. It can neither list, accept nor reject them.
  • A suggest-only user’s view without it writes as a writer’s would, and the room strips each of its writes (refused suggest-only; the socket stays): its edits are never stored.

In development, such a view warns once in the console when the document it opens holds shared suggestions. Nothing else guards it: a production guard (refusing the view’s writes while the document holds suggestion records) would also refuse writes on documents whose suggestions were all decided, until the purge removes them.

A document without a view

A document read on a server or in a worker leaves its pending suggestions out of toJSON() once they are built over it:

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

/** The stored document, without its pending suggestions. */
export const saved = (bytes: Uint8Array) => {
	const document = loadDocument(bytes);
	adoptSharedSuggestions(document);
	return document.toJSON();
};

The room does this for its own document: its onSave value, its versions and the blocks a move exports leave them out. edytor/export holds no document, so it ships none of their code.

What it costs

Measured on the stored document (document.encode()), against the same edit made directly:

Suggested Direct
A typed character (1,000 typed one by one) 1.01 bytes 1.08 bytes
A deleted character (1,000 Backspaces) 0.02 bytes (proposed) 0.10 bytes
A suggestion’s fixed cost 89 bytes (another by the same view: 36) —
Accepting an insertion, or rejecting a deletion 13–14 bytes —
Rejecting an insertion, or accepting a deletion 37 bytes —

A document with no suggestion reads nothing for them, and a keystroke in a suggestion costs the same work at 5,000 blocks as at 1,000.

API

edytor.suggestions is the view’s list:

PropType
add(at, content?, options?)?Suggestion

Propose content at a position, view-local. options: { id?, status?, label?, onRetry? }. An id already listed replaces that suggestion.

TypeSuggestion
list?readonly (Suggestion | SharedSuggestion)[]

Every suggestion: the view-local ones, then (with the plugin) the shared ones, this view's first. Reactive.

Typereadonly (Suggestion | SharedSuggestion)[]
latest?Suggestion | undefined

The newest view-local one, which the keys act on.

TypeSuggestion | undefined
get(id)?Suggestion | SharedSuggestion | undefined

One by id.

TypeSuggestion | SharedSuggestion | undefined
clear()?void

Discard every view-local suggestion.

Typevoid
at(blockId)?SuggestionsAt

What shows at a block: { before, after, inside, end, replaced, inPlace }. inPlace: the replace removes only blocks that hold nothing, so its content shows in their place. Reactive.

TypeSuggestionsAt

sharedSuggestionsController(edytor) is the shared suggestions plugin’s controller (undefined without the plugin):

PropType
suggesting?boolean

Suggesting mode: the view's writes are a shared suggestion. Always true for a suggest-only user.

Typeboolean
add(at, content?, options?)?Suggestion | SharedSuggestion

Propose content at a position, written live into the document as it streams (at an end: a view-local one). options: { id?, status?, label?, onRetry?, via? }.

TypeSuggestion | SharedSuggestion
changes()?readonly SuggestedChange[]

Every pending change of a shared suggestion, in document order. Reactive.

Typereadonly SuggestedChange[]
decide(changes, accept)?OpResult

Accept or reject some changes: one command, one undo step.

TypeOpResult
acceptAll()?OpResult

Accept every pending shared suggestion.

TypeOpResult
rejectAll()?OpResult

Reject every pending shared suggestion.

TypeOpResult

A Suggestion (view-local; shared is false):

PropType
id?string

Its id (options.id, or minted).

Typestring
at?ResolvedAt

The position, resolved.

TypeResolvedAt
shared?false

View-local.

Typefalse
content?readonly JSONBlock[]

The proposed blocks. Reactive.

Typereadonly JSONBlock[]
status?'streaming' | 'ready'

Reactive.

Type'streaming' | 'ready'
label?string | undefined

options.label; the bar shows it.

Typestring | undefined
live?boolean

Still listed: not accepted, discarded or dropped.

Typeboolean
retryable?boolean

An onRetry was given.

Typeboolean
update(content)?void

Replace the content. Does nothing once not live.

Typevoid
append(text)?void

Add streamed text to the last block.

Typevoid
done()?void

status becomes 'ready'.

Typevoid
accept()?OpResult

Write it: one command, one undo step.

TypeOpResult
discard()?void

Drop it, writing nothing.

Typevoid
retry()?void

Empty it and call onRetry.

Typevoid

A SharedSuggestion (shared is true) has the same members, and:

PropType
at?ResolvedAt | null

The position this view added it at; null for one another view made (its changes say where it is).

TypeResolvedAt | null
by?string | undefined

Its author (an actor id).

Typestring | undefined
via?string | undefined

The agent that wrote it for its author ('ai').

Typestring | undefined
changes?readonly SuggestedChange[]

Its pending changes. Reactive.

Typereadonly SuggestedChange[]
canDecide?boolean

This view may accept or reject it.

Typeboolean
mine?boolean

Its author is this view's user.

Typeboolean
accept()?OpResult

Accept its changes: one command, one undo step.

TypeOpResult
reject()?OpResult

Reject its changes: one command, one undo step.

TypeOpResult
discard()?void

Reject it (by its author too, even without the right to decide).

Typevoid

The default UI

createSuggestionsPlugin() is opt-in (Plugins): list it in plugins to bind the suggestion keyboard shortcuts. Its bar under each block suggestion, in the overlay, is your bar snippet via createSuggestionBarPlugin({ bar }) (below; the demo’s shows the label, AI is writing… while it streams, Accept, Discard, and Try again when the suggestion has an onRetry, Discard only in a readonly view). An end suggestion has no bar: the keys accept it.

Keys Action Where
Mod + Enter Accept the latest suggestion Focus in the editor
Escape Discard the latest suggestion Focus in the editor
Tab Accept the end suggestion of the caret’s block A caret in that block, except a list-like block (bulleted, numbered, to-do, toggle, a list’s item), where Tab keeps indenting: use Mod + Enter there

The keys claim nothing while there is no suggestion, so Mod + Enter still checks to-dos and opens toggles. Plugins listed before it in plugins get the keys first (Plugin order); in a code line, the code plugin’s Tab accepts an end suggestion too.

Render the bar with createSuggestionBarPlugin({ bar }) (without it, no bar shows). Its placement is the plugin’s, the keys the default suggestions plugin’s: under a block suggestion’s preview, and under the last block a shared suggestion changes. The bar receives a SuggestionBarPayload: the suggestion, accept, discard, reject, retry (with an onRetry), readonly, canDecide (this view may accept or reject it), author (a shared one’s: { id, name?, color? }, from its profile) and mac (Mod is ⌘); its words are your markup’s. The keys act on view-local suggestions only: a shared one is decided from its bar or your review controls.

<script lang="ts">
	import { Edytor, createSuggestionBarPlugin, type SuggestionBarPayload } from 'edytor';
</script>

{#snippet bar({ suggestion, accept, discard, retry, readonly }: SuggestionBarPayload)}
	<div class="ai-bar">
		<span>{suggestion.status === 'streaming' ? 'Writing…' : 'Done'}</span>
		{#if !readonly}<button onmousedown={(e) => e.preventDefault()} onclick={accept}>Keep</button>{/if}
		<button onmousedown={(e) => e.preventDefault()} onclick={discard}>Remove</button>
		{#if retry}<button onmousedown={(e) => e.preventDefault()} onclick={retry}>Again</button>{/if}
	</div>
{/snippet}

<Edytor plugins={[createSuggestionBarPlugin({ bar })]} />

Under a shared suggestion, show its author and Accept and Reject when canDecide, Withdraw for its author (suggestion.mine: discard rejects it), and a plain “Suggested” otherwise:

<script lang="ts">
	import { Edytor, createSuggestionBarPlugin, type SuggestionBarPayload } from 'edytor';
</script>

{#snippet bar({ suggestion, author, accept, reject, discard, canDecide }: SuggestionBarPayload)}
	<div class="review-bar" style:color={author?.color}>
		{#if suggestion.shared}
			<span>{author?.name ?? author?.id}{suggestion.via ? ` (${suggestion.via.toUpperCase()})` : ''}</span>
			{#if canDecide && !suggestion.mine}
				<button onmousedown={(e) => e.preventDefault()} onclick={accept}>Accept</button>
				<button onmousedown={(e) => e.preventDefault()} onclick={reject}>Reject</button>
			{:else if suggestion.mine}
				<button onmousedown={(e) => e.preventDefault()} onclick={discard}>Withdraw</button>
			{:else}
				<span>Suggested</span>
			{/if}
		{:else}
			<button onmousedown={(e) => e.preventDefault()} onclick={accept}>Keep</button>
			<button onmousedown={(e) => e.preventDefault()} onclick={discard}>Remove</button>
		{/if}
	</div>
{/snippet}

<Edytor plugins={[createSuggestionBarPlugin({ bar })]} />

The ready-made chrome draws this bar, and the starter’s review controls the Editing and Suggesting switch with Accept all and Reject all.

Prevent the buttons’ mousedown so the editor keeps its focus and selection. <Edytor labels> (its editor.suggestion) translates a preview’s accessible name when the suggestion has no label (see Localization). Without createSuggestionsPlugin() or createSuggestionBarPlugin({ bar }), suggestions still render and can be accepted or discarded programmatically, without keyboard shortcuts or a bar.

Rendering and styling

A block suggestion renders inside the editor, in the document’s flow, as one group:

<div data-edytor-suggestion="s_…" data-status="streaming" contenteditable="false" role="group">
	<!-- each block, rendered by its kind: the same element, snippet and attributes -->
</div>

The kinds render their blocks as in the document, images included, with data-edytor-block and data-edytor-type (no data-edytor-id, no text elements). A snippet receives a BlockView whose handle is undefined, selected and focused false: guard commands on block.handle in a kind’s own controls. Nothing inside answers the pointer, and a press on the group is cancelled, so it never takes the caret. The group gives no caret stop, no selection, no copied content and no drag image; the editor’s DOM check ignores it.

Selector What
[data-edytor-suggestion], [data-status] A block suggestion’s group, by id, and its status
[data-edytor-suggestion-replaced] A block a replace removes (="empty": one that holds nothing, folded by the core so the content takes its place)
[data-edytor-suggestion-range] A rectangle over the text a range replace removes (overlay)
[data-edytor-text-suggestion] An end suggestion’s ghost text
[data-edytor-suggestion-bar] Where your bar renders, under its preview (overlay)

The Notion theme gives the group a tinted background, pulses it while it streams (not with reduced motion), strikes through replaced blocks and greys the ghost text. Its custom properties: --edytor-suggestion-background, --edytor-suggestion-removed (replaced blocks), --edytor-suggestion-removed-line (a range’s underline), --edytor-suggestion-bar-space (the room under a group for the bar, 40px).

A shared suggestion is the document’s own text and blocks: it renders in place, with nothing of its own inside the host. Its runs are rectangles in the overlay, in its author’s colour (--edytor-range-color on each), and the blocks it makes or proposes to delete carry an attribute:

Selector What
[data-edytor-suggestion-inserted] A rectangle over inserted text (overlay)
[data-edytor-suggestion-deleted] A rectangle over text proposed for deletion (overlay)
[data-edytor-suggested] A block a shared suggestion made (inserted, split) or proposes to delete (removed)

The Notion theme underlines inserted text and strikes deleted text in the author’s colour, and marks the blocks with a bar at their start (an inserted block also tinted, a removed one tinted and struck). Its custom properties: --edytor-suggestion-inserted and --edytor-suggestion-inserted-background (inserted blocks), --edytor-suggestion-removed and --edytor-suggestion-removed-line (removed blocks).

Live example

The editor on the home page has an Ask AI button and two slash commands. They need no API key: the answers are canned and streamed word by word. Until you accept one, the shared room never sees it; once accepted, everyone does. Its plugin, trimmed:

import type { EdytorInstance, JSONBlock, Plugin, Suggestion } from 'edytor';

const ANSWERS: JSONBlock[][] = [
	[
		{ type: 'heading', data: { level: 'h2' }, content: [{ text: 'Launch plan' }] },
		{ type: 'bulleted-list-item', content: [{ text: 'Write the announcement post' }] },
		{ type: 'todo-item', data: { checked: false }, content: [{ text: 'Book the launch review' }] }
	],
	[{ type: 'paragraph', content: [{ text: 'Another answer, for Try again.' }] }]
];
let next = 0;

/** Show `blocks` one block more every 300 ms, then mark the suggestion ready. */
const stream = (suggestion: Suggestion, blocks: JSONBlock[]) => {
	let shown = 0;
	const timer = setInterval(() => {
		if (!suggestion.live) return clearInterval(timer);
		suggestion.update(blocks.slice(0, ++shown));
		if (shown === blocks.length) {
			clearInterval(timer);
			suggestion.done();
		}
	}, 300);
};

export const askAI = (edytor: EdytorInstance) => {
	const block = edytor.selection.caret?.block;
	if (!block) return;
	// An empty line is replaced, as in Notion; else the answer goes after the block.
	const at = block.isEmpty && block.convertible ? { replace: [block.id] } : { after: block.id };
	const suggestion = edytor.suggestions.add(at, undefined, {
		label: 'AI',
		onRetry: (again) => stream(again, ANSWERS[next++ % ANSWERS.length]!)
	});
	stream(suggestion, ANSWERS[next++ % ANSWERS.length]!);
};

/** `/ai` in the slash menu: it runs once the `/ai` text is removed. */
export const aiPlugin: Plugin = () => ({
	commands: [
		{
			id: 'ai.ask',
			label: 'Ask AI',
			icon: '✦',
			group: 'AI',
			keywords: ['ai', 'write', 'generate'],
			run: async (edytor) => {
				await Promise.resolve();
				askAI(edytor);
			}
		}
	]
});

The full demo (site/islands/ai-demo.ts in the repository) streams word by word, adds an image to the answer and a Continue writing command (/continue), an end suggestion that Tab accepts.

Text to blocks

There are two readers of markdown:

  • textToBlocks from edytor, the editor’s own: what a markdown paste and a string suggestion read. It reads # to ### headings (deeper ones read as ###), -, * or + bullets, 1. numbers, [ ] and [x] to-dos (also after a bullet), > quotes, --- dividers, fenced code blocks (an unclosed fence keeps its lines), list items nested by indentation (two spaces a level), and **bold**, *italic* or _italic_, `code` and [text](url) links (marks do not nest). Consecutive plain lines make one paragraph, joined by a space.
  • textToBlocks from edytor/export, the full reader, for a model’s answer or a markdown file. It parses with TanStack Markdown and reads, beyond the small one: GFM tables as a table (the first row a header), a fence’s language in data.language, nested marks (**[a bold link](url)**, ***both***), ~~strike~~, <https://…> and reference links, backslash escapes, a quote’s later paragraphs as its children, > [!NOTE] as a callout, <details> as a toggle, $$ equations, a line holding only an image as an image, line breaks (a line ending in \ or two spaces), and streaming: true: a text still arriving shows only what the next chunk cannot turn into another kind or mark (streaming).

Both are pure (use them in a server or a Worker), take markdown: false (every character as text: blank lines split paragraphs) and type, the paragraph kind (default paragraph). The other kinds and marks are the bundled plugins’. Only the full one is in edytor/export, so <Edytor> ships the small one.

Streaming works in two steps: before parsing, the last line (the one with no newline yet) is cut back, to nothing while it is only a block marker (#, -, 1., >, a table row, a fence’s first backticks, a tag being typed) and to just before an inline marker it has not closed (**bol, [the do, `npm), and a table’s header row is held until its separator row arrives; inside an open fence, every line shows as code. After parsing, TanStack’s streaming profile drops a trailing heading or list item that is still empty. A link’s href goes through the link sanitizer, so a javascript: link is its text.

import { textToBlocks } from 'edytor/export';

textToBlocks('## Plan\n- [ ] Ship it\nSee **[the notes](https://example.com)**');
// [{ type: 'heading', data: { level: 'h2' }, content: [{ text: 'Plan' }] },
//  { type: 'todo-item', data: { checked: false }, content: [{ text: 'Ship it' }] },
//  { type: 'paragraph', content: [{ text: 'See ' },
//    { text: 'the notes', marks: { bold: true, link: { href: 'https://example.com' } } }] }]

The block API, before edytor.suggestions

block.suggestText({ value }), block.suggestions and block.acceptSuggestedText() are gone: add an { end: block.id } suggestion with edytor.suggestions.add, read the block’s with edytor.suggestions.at(block.id).end, and accept one with suggestion.accept() (migration).

Limitations

  • A view-local suggestion lives in one view. Another tab or a collaborator cannot review it, and a reload loses it: add a shared one (the plugin’s add) when it must be reviewed by others or survive a reload.
  • Shared suggestions need the plugin in every view of a document under review: a view without it shows their text as plain content, exports it and edits it directly (a view without the plugin).
  • Only text and blocks are suggested: a merge, a retype, a data change, a format, a move, a nest or an outdent is refused while the view suggests (a beside drop and a table’s row and column moves with them), except on the user’s own pending blocks.
  • A re-proposed deletion needs a new suggestion: once a reviewer rejected deleting some text or a block, deleting it again in the same suggestion proposes nothing (what the reviewer settled stays settled in that suggestion); the next suggestion proposes it.
  • Writes a plugin makes on its own (a bookmark’s fetched title and image, a page link’s title) are direct writes, not suggestions: for a suggest-only user the room refuses them, so the card or the title stays as it was until a writer’s view fetches it.
  • No headless review. A document without a view (a server, a bot, the room’s transact) leaves its pending suggestions out of toJSON() only once they are built over it (adoptSharedSuggestions, a document without a view), and reads them only through toJSON({ suggestions: true }): listing, accepting and rejecting them needs a view with the plugin.
  • Exports leave pending suggestions out: edytor.value, onChange’s value, the room’s onSave value and a cross-document move are the document without them; a block moved to another document arrives without its pending changes.
  • A text-range replace is two writes in one command and one undo step: the range’s deletion, then the paste at its caret. Hooks see the deletion’s steps only.
  • The preview applies no transformText (a code block’s preview is not highlighted) and renders the kinds this view registers; an unknown kind shows as a plain block.
  • Markdown pasted into the editor reads with the editor’s small reader: a pasted table, a fence’s language or nested marks need the full one (edytor/export), applied by your app (a plugin’s onPaste). The full reader keeps no table column alignment (:---:), and HTML in markdown stays text.

Was this page helpful?