Plate
PlateEditorsCreateTemplates
GitHub16kGitHub
DiscordDiscord
    • Stream
    • Copilot
    • Prompt Editor
  • Comments
  • Discussion
  • Suggestions
    • Basic Blocks
      • Blockquote
      • Heading
      • Horizontal Rule
    • Board
    • Callout
    • Code Block
    • Column
    • Date
    • Equation
    • FieldExperimental
    • Link
    • Media
    • MentionElement
    • Table
    • Table of Contents
    • Footnote
    • Details
  • Marks
    • Bold
    • Italic
    • Underline
    • Code
    • Highlight
    • Keyboard Input
    • Strikethrough
    • Subscript
    • Superscript
      • Font
      • Line Height
      • Text Align
      • Clear Formatting
      • Format Painter
    • Indent
    • List
      • Exit Break
      • Single Block
      • Trailing Block
    • Autoformat
    • Block Menu
    • Block Placeholder
    • Combobox
      • Emoji
      • MentionElement
      • Slash Command
    • Drag & Drop
    • Navigation Feedback
    • Linting
    • Tabbable
    • Toolbar
    • Yjs
    • Multi SelectEditor
    • DOCX
    • HTML
    • Markdown

Suggestions

PreviousNext

Propose text, formatting, and block edits, then review them with copied Plate UI.

Authored ChangesDiscussionCommentsSuggestion Toolbar Button
Loading…
DiscussionBasic Blocks

On This Page

FeaturesKit UsageInstallationAdd the kitsSet the modeRead view stateExamplesFormatting and blocksAccepted, proposed, and markupSave proposals and repliesCreate and decide changesDecide every suggestionDecide a tableSave and reloadHeadless usageDiscussion reviewAPI ReferenceBaseSuggestionPluginSuggestionPluginReact hooksSuggestionKit
Build your editor
Production-ready AI template and reusable components.
Get all-access

The demo starts in Suggestion mode with a proposed insertion and deletion. Open a paragraph's discussion button to accept or reject its card, or choose Accept all suggestions or Reject all suggestions in the mode menu, then try undo and redo. Switch to Editing to keep the pending changes visible while ordinary edits apply directly, or type in Suggestion mode to propose an edit.

Typing or pasting inside struck text lands after the pending deletion, and a word confirmed with an input method splits the deletion around it. In Suggestion mode the new text is a proposed insertion of its own; in Editing mode it applies directly. Deleting struck text in Editing mode leaves it to its pending deletion.

Features

  • Switch a mounted editor view between editing and suggesting
  • Decorate proposed text, formatting, and structural edits
  • Keep the active card local to each mounted view
  • Read native authored changes and review cards for custom review UI
  • Save pending changes with the complete document
  • Add review cards and comment replies through copied registry UI
Report an issue

Kit Usage

Installation

Start with an Editor, then install the suggestion and discussion UI:

pnpm dlx shadcn@latest add https://platejs.org/r/basic-blocks.json https://platejs.org/r/suggestion.json https://platejs.org/r/discussion.json https://platejs.org/r/suggestion-toolbar-button.json https://platejs.org/r/history-toolbar-button.json
pnpm dlx shadcn@latest add https://platejs.org/r/basic-blocks.json https://platejs.org/r/suggestion.json https://platejs.org/r/discussion.json https://platejs.org/r/suggestion-toolbar-button.json https://platejs.org/r/history-toolbar-button.json
'use client';
 
import { AuthoredPlugin } from 'platejs/authored';
import {
  type EditableSiblingProps,
  useEditor,
  useEditorSelector,
} from 'platejs/react';
import { suggestionColorOf } from 'platejs/suggestion';
import {
  SuggestionPlugin,
  useActiveSuggestion,
} from 'platejs/suggestion/react';
import * as React from 'react';
import { toast } from 'sonner';
 
type SuggestionColor = Readonly<{
  active























































































































































































































SuggestionKit configures the package SuggestionPlugin with render.contentAttributes for its default styles. The package supplies semantic attributes, active-card behavior, and authored-change hooks. Core applies the kit's classes to the existing content root, including when you render EditorContent directly. DiscussionKit adds block buttons, Accept and Reject cards, and comment replies.

Add the kits

components/editor/suggestion-editor.tsx
'use client';
 
import { CommentsPlugin } from 'platejs/comments/react';
import { EditorRoot, useCreateEditor } from 'platejs/react';
 
import { BasicBlocksKit } from '@/components/editor/basic-blocks';
import { DiscussionKit } from '@/components/editor/discussion';
import { Editor, EditorContainer } from '@/components/editor/editor';
import {
  RedoToolbarButton,
  UndoToolbarButton,
} from '@/components/editor/history-toolbar-button';
import { SuggestionKit } from '@/components/editor/suggestion';
import { SuggestionToolbarButton } from '@/components/editor/suggestion-toolbar-button';
































Replace 'alice' with the authenticated user's ID. The editor's userId attributes document changes and comments, and users supplies names and optional avatars. A solo editor can omit userId; it then suggests and comments as the local user, 'local'. To suggest or comment as another author, such as an AI, write through a view made with createEditorView(editor, { authorId }), as Authored Changes shows.

SuggestionPlugin depends on AuthoredPlugin, which reads the author of the writing view, else the editor's userId, once per write transaction. Do not install a second authored descriptor alongside the kit.

Set the mode

Set the starting view with EditorRoot authored={{ intent: 'propose' }} as in the example above. Changing the value updates that view. Rerendering with an equivalent value preserves mode changes made by its controls.

For an interactive mode control, set and read the intent of the mounted editor view through AuthoredPlugin:

import { AuthoredPlugin } from 'platejs/authored';
import { useEditor, useEditorViewState } from 'platejs/react';
 
export function SuggestionModeButton() {
  const editor = useEditor();
  const authored = editor.plugin(AuthoredPlugin);
  const isSuggesting = useEditorViewState(editor, () => {
    const view = authored.read.view();
 
    return 'intent' in view && view.intent === 'propose';
  });
 
  return (
    <button
      onClick={() =>
        authored.api.setView({ intent: isSuggesting ? 'edit' : 'propose' })
      }
    >
      {isSuggesting ? 'Stop suggesting' : 'Suggest edits'}
    </button>
  );
}
import { AuthoredPlugin } from 'platejs/authored';
import { useEditor, useEditorViewState } from 'platejs/react';
 
export function SuggestionModeButton() {
  const editor = useEditor();
  const authored = editor.plugin(AuthoredPlugin);
  const isSuggesting = useEditorViewState(editor, () => {
    const view = authored.read.view();
 
    return 'intent' in view && view.intent === 'propose';
  });
 
  return (
    <button
      onClick






{ intent: 'propose' } is Suggestion mode and { intent: 'edit' } is Editing mode. Both show the pending insertions and deletions. In Editing mode, ordinary edits apply directly; in Suggestion mode, they become proposals by the current author.

Mode belongs to the exact mounted view. Two views over one document can use different modes without changing each other.

Changing the mode affects only subsequent input. It does not accept, reject, delete, or hide pending changes, and it does not add an undo step.

To read the document with every pending change accepted or rejected, switch the view to a preview:

import { AuthoredPlugin } from 'platejs/authored';
 
const authored = editor.plugin(AuthoredPlugin);
 
authored.api.setView({ preview: 'proposed' });
import { AuthoredPlugin } from 'platejs/authored';
 
const authored = editor.plugin(AuthoredPlugin);
 
authored.api.setView({ preview: 'proposed' });

A preview throws on a plain edit, but some other writes still change the document, such as an update that makes a decision, undo and redo, and remote collaboration changes. read.view() returns the preview, such as { preview: 'proposed' }, which has no intent. Switching to a preview does not accept or reject changes. Coordinates can differ between views, so read selections and apply edits through the view that produced them. Set an intent with setView to leave the preview.

Under a preview, each block reads the cards and changes of the stored content it shows, with what the preview hides inside it, and those of an element around it that the preview takes away, such as a quote whose pending unwrap the preview applies. A preview reads them by a node's key or path only, as the hooks below do; a point or a range throws AuthoredPlaceError, which platejs/authored exports. The cards of a top-level block the preview hides show on no block, so switch to Editing to see and decide them. The exception is a joined line, which shows the cards of a hidden block between its two halves. A top-level block the preview adds to complete the document, such as the empty paragraph it shows when a suggestion deletes the only block, shows no cards. One it adds inside a container, as when a suggestion deletes the only paragraph of a quote, can show the cards of the hidden paragraph it replaces. Under a preview, the copied discussion anchors the popover of a suggestion or a change thread on the paragraph whose trigger was pressed last, and opens it only when that paragraph shows the thread.

Read view state

The React entrypoint exposes focused hooks for custom controls and review UI:

import {
  useActiveSuggestion,
  useSuggestionChanges,
  useSuggestionGroups,
} from 'platejs/suggestion/react';
 
const changes = useSuggestionChanges(path);
const cards = useSuggestionGroups(blockKey);
const { activeId, setActiveId } = useActiveSuggestion();
import {
  useActiveSuggestion,
  useSuggestionChanges,
  useSuggestionGroups,
} from 'platejs/suggestion/react';
 
const changes = useSuggestionChanges(path);
const cards = useSuggestionGroups(blockKey);
const { activeId, setActiveId } = useActiveSuggestion();

useSuggestionChanges(path) returns the native AuthoredChange records of the block at that path of the mounted view. A nested block's path returns its own changes and those of a container around it that the preview takes away. It never returns the pending wrap or unwrap of a container the view still shows, which that container's own path returns. It rereads on each commit that changes the document or its state and when the review delta names the path's top-level block, and keeps its result stable while those records are unchanged. A change's ranges stay places of the stored document on every view.

useSuggestionGroups(blockKey) returns the review cards of the block with that key, as read.groups summaries. A nested block's key reads that block's own cards. It rereads when the component that calls it renders and when the review delta names the block, which happens when a change reaches or leaves that block or one of its changes moves to another card. A delta names top-level blocks only, so for a nested block's key it rereads only when that component renders. An edit to the same card in another block does neither, so a summary's changeCount or revision can trail; read editor.plugin(AuthoredPlugin).read.groupOf(card.id) when a control needs the current one. Read a card's changes a page at a time with read.changes({ group: card.id }), or the changes and parts a review card shows with read.groupDetails(card.id, { limit }).

In the current view, clicking a marked element activates the first card its data-editor-authored-groups attribute names. Clicking unmarked editor content clears it. In Safari with an input method such as WeType, a tap gets no click of its own, so its press activates or clears instead. A drag clears the active card when the card under the pointer changes from the one where the drag started, or when the pointer leaves the editor. Unmounting the view, switching it to another intent or preview, or deciding the card also clears stale active state. Use setActiveId when a custom card or control needs to activate a card directly.

Examples

Formatting and blocks

The first proposal makes a sentence bold; the second inserts a paragraph. Open each block's discussion button to accept or reject it. Select text and use Bold, or press Enter to propose another paragraph.

Loading…

Add Basic Marks for supported text formatting. Editor commands record text, mark, and node operations as proposals while the view is in suggesting mode. Text edits inside a table cell record too. Adding or deleting a whole table records as one change, such as Delete table or a table pasted between paragraphs. So do list edits, such as Enter or Tab in a list item, or Backspace at its start. Suggesting still refuses these edits for now:

  • a change to a table's rows, columns, cells or sizes, such as adding a row or merging cells
  • adding or deleting a table that holds another table or a code block, or a block that holds a table
  • pasting a table into a cell, or pasting over a selection across cells
  • any edit inside a code block

A propose view refuses a write it cannot record as a proposal and rolls it back, and both modes refuse some edits beside a paragraph a pending join shows away from where it is saved; see Authored Changes. Formatting in Editing mode over a pending format suggestion applies directly and leaves the suggestion pending, so rejecting it later keeps the direct edit. If a collaborator decides or withdraws that suggestion while the edit syncs, the direct edit can be lost.

Accepted, proposed, and markup

Switch views to compare accepted content, the proposed result, and the markup view that shows pending insertions and deletions. The proposals stay pending in all three views.

Loading…

The Accepted and Proposed controls set a preview view; Markup sets { intent: 'edit' }. This example sets readOnly on both EditorRoot and Editor, so no view takes document input. The application still owns authorization for review actions and remote writes.

Save proposals and replies

Open a change's discussion button and add a reply, then save a snapshot. Accept or reject that change, or type another proposal, and reload the snapshot.

Loading…

The snapshot stays in memory and disappears when the page reloads. Reload snapshot creates a fresh editor from the saved document, its comment ranges and the thread rows saved beside them, discarding unsaved work and starting an empty local undo stack. Pending changes belong to the document; conversations persist separately from document undo.

Create and decide changes

Suggesting mode turns ordinary input and editor commands into native proposals. A headless or explicit transaction can begin a proposal with tx.authored.propose():

let changeId = '';
 
editor.update((tx) => {
  changeId = tx.authored.propose();
  tx.text.insert(' proposed', {
    at: { offset: 4, path: [0, 0] },
  });
});
let changeId = '';
 
editor.update((tx) => {
  changeId = tx.authored.propose();
  tx.text.insert(' proposed', {
    at: { offset: 4, path: [0, 0] },
  });
});

Pass { changeId } to add the transaction's writes to the pending change with that ID. Use separate proposing transactions when reviewers need to decide the edits independently.

Authored owns review decisions and their structured results. Read the change, then decide the record you read:

import { AuthoredPlugin } from 'platejs/authored';
 
const authored = editor.plugin(AuthoredPlugin);
const change = authored.read.change(changeId);
 
if (change) {
  const result = authored.update.decide({
    action: 'accept',
    changes: [change],
  });
}
import { AuthoredPlugin } from 'platejs/authored';
 
const authored = editor.plugin(AuthoredPlugin);
const change = authored.read.change(changeId);
 
if (change) {
  const result = authored.update.decide({
    action: 'accept',
    changes: [change],
  });
}

Use action: 'reject' to reject the change. Inspect result.status: another edit can make the change stale, and a decision that needs other changes decided with it returns blocked. To decide a whole card, pass { action, groups: [card] }. Authored Changes covers paging, cards, previews, and result handling.

Decide every suggestion

To accept or reject every pending suggestion, read every page of changes and decide them in one call:

import { type AuthoredChange, AuthoredPlugin } from 'platejs/authored';
 
const authored = editor.plugin(AuthoredPlugin);
const changes: AuthoredChange[] = [];
 
for (let cursor: string | undefined; ; ) {
  const page = authored.read.changes({ cursor, limit: 200 });
 
  changes.push(...page.items);
  if (!page.cursor) break;
  ({ cursor } = page);
}
 
const result = authored.update.decide({ action: 'accept', changes });
import { type AuthoredChange, AuthoredPlugin } from 'platejs/authored';
 
const authored = editor.plugin(AuthoredPlugin);
const changes: AuthoredChange[] = [];
 
for (let cursor: string | undefined; ; ) {
  const page = authored.read.changes({ cursor, limit: 200 });
 
  changes.push(...page.items);
  if (!page.cursor) break;
  ({ cursor } = page);
}
 
const result = authored.update.

One call decides every change together, so it never returns blocked. When it applies, it leaves the same document as deciding the changes one at a time in any order, where each blocked step adds the changes its with names. One case still depends on order. When a suggested Enter cut a link into pieces and other suggestions remove or unwrap a piece or a node between them, rejecting the Enter can rejoin the pieces differently one at a time than in one call. One undo restores every change it decided. Read and decide in the same event handler, because an edit between them can make a change stale. When the schema refuses the decided document, the result is invalid and nothing changes. The copied ModeToolbarButton offers this as Accept all suggestions and Reject all suggestions in its menu.

Decide a table

Accepting a struck table, or rejecting a suggested one, removes the whole table with every pending change inside it, another author's text included. One undo brings back the table with those changes pending. A change that lies wholly inside the table leaves the review with no verdict, so its card disappears and authored.read.outcome(id) returns null for it, as Authored Changes describes. The change that struck or added the table keeps its verdict.

Until someone decides a struck table, both modes refuse typing in it, a table command aimed at it, and Backspace or Delete that would join the paragraphs on either side of it. authored.api.subscribeRefusals reports each with code unrepresentable and reason grid, and SuggestionKit shows a toast.

Save and reload

Save the complete value returned by editor.read.value(). Pending review marks live in each node's authored property and review records in the document's records; leave both to the editor.

const savedDocument = editor.read.value();
const savedRanges = editor.plugin(CommentsPlugin).api.ranges();
const savedDocument = editor.read.value();
const savedRanges = editor.plugin(CommentsPlugin).api.ranges();

Persist the document and its comment ranges atomically for the same application revision, and keep thread rows in your tables. Verify that association before loading, and use the same content plugins. Saving only children discards the review records.

Create a fresh editor with the saved document as initialValue and CommentsPlugin.configure({ initialState: { initialComments: { ranges: savedRanges, threads } } }), with threads read from your table. Local undo starts empty. The document preserves each change's author and ID, so replies can locate the same suggestions. Set userId to the current author; loading another author's suggestions does not require changing it or replaying their edits. For historical previews and restores, join current conversations with the selected revision's targets.

Choose an explicit export projection. HTML and Markdown carry visible accepted or proposed content only. Save authored JSON when Plate must recover the review, or use DOCX review export for Word revisions.

Headless usage

Use BaseSuggestionPlugin for semantic decorations without React, Comments, or copied UI. Set Suggestion mode through AuthoredPlugin, which it installs:

suggestion-editor.ts
import { BaseParagraphPlugin, createEditor } from 'platejs';
import { AuthoredPlugin } from 'platejs/authored';
import { BaseSuggestionPlugin } from 'platejs/suggestion';
 
const editor = createEditor({
  plugins: [BaseParagraphPlugin, BaseSuggestionPlugin],
  initialValue: [
    { type: 'paragraph', children: [{ text: 'Edit this sentence.' }] },
  ],
  userId: 'alice',
});
 
editor.plugin(AuthoredPlugin).api.setView({ intent: 'propose' });
suggestion-editor.ts
import { BaseParagraphPlugin, createEditor } from 'platejs';
import { AuthoredPlugin } from 'platejs/authored';
import { BaseSuggestionPlugin } from 'platejs/suggestion';
 
const editor = createEditor({
  plugins: [BaseParagraphPlugin, BaseSuggestionPlugin],
  initialValue: [
    { type: 'paragraph', children: [{ text: 'Edit this sentence.' }] },
  ],
  userId: 'alice',
});
 
editor.plugin(AuthoredPlugin).api.setView({ intent: 'propose' });

Marked text and elements expose data-editor-authored-change, data-editor-authored-kind, data-editor-authored-author, data-editor-authored-groups, and data-editor-authored-color. Each holds a space-separated list, except color, which holds the palette slot, 0 to 6, of the card the element paints. A pending deletion has delete in its kind. Add application styles against these attributes through the plugin's render.contentAttributes. Static presets can configure BaseSuggestionPlugin with a server-safe attribute object; SuggestionKit supplies the live default styles.

Discussion review

Add DiscussionKit for Accept and Reject cards and replies attached to a change. It composes optional Comments data with native authored changes; review presentation remains copied application code.

To attach a conversation programmatically, target the authored change ID:

import { CommentsPlugin } from 'platejs/comments/react';
 
const comments = editor.plugin(CommentsPlugin).api;
const result = await comments.createThread({
  body: [
    { type: 'paragraph', children: [{ text: 'Can we explain this edit?' }] },
  ],
  target: { type: 'change', id: changeId },
});
 
if (result.status === 'applied') {
  comments.setActive([result.value]);
}
import { CommentsPlugin } from 'platejs/comments/react';
 
const comments = editor.plugin(CommentsPlugin).api;
const result = await comments.createThread({
  body: [
    { type: 'paragraph', children: [{ text: 'Can we explain this edit?' }] },
  ],
  target: { type: 'change', id: changeId },
});
 
if (result.status === 'applied') {
  comments.setActive([result.value]);
}

Preserve input for non-applied results and thrown errors. Comments authorizes durable writes through initialState.mutate and publishes only the canonical committed record. Accepting or rejecting a change is a document action that can be undone; it hides the review card without deleting or resolving its discussion. All comments then labels the thread with what the review did, such as Suggestion accepted; see Comments. Undo restores the pending change with its messages and resolution intact. Resolving or reopening the thread stays outside document undo.

API Reference

BaseSuggestionPlugin

Import from platejs/suggestion. It supplies CSS-free semantic decorations and depends on AuthoredPlugin, which owns change records, identity and the view's intent.

SuggestionPlugin

Import from platejs/suggestion/react. It extends BaseSuggestionPlugin with exact-view active state and pointer activation.

React hooks

HookResult
useSuggestionChanges(path)Native AuthoredChange records of the block at path.
useSuggestionGroups(blockKey)Summaries of the review cards of the block with that key.
useActiveSuggestion()The view-local active card's activeId and the setActiveId function.

SuggestionKit

The copied registry kit configures SuggestionPlugin with content-root styles. Generic editor components remain independent of suggestions. Review cards, Comments integration, toolbars, and popovers remain in registry code.

:
string
;
background: string;
foreground: string;
hover: string;
}>;
const SUGGESTION_COLORS: readonly SuggestionColor[] = [
{
active: 'var(--color-emerald-800)',
background: 'var(--color-emerald-100)',
foreground: 'var(--color-emerald-700)',
hover: 'color-mix(in oklab, var(--color-emerald-200) 80%, transparent)',
},
{
active: 'var(--color-violet-800)',
background: 'var(--color-violet-100)',
foreground: 'var(--color-violet-700)',
hover: 'color-mix(in oklab, var(--color-violet-200) 80%, transparent)',
},
{
active: 'var(--color-sky-800)',
background: 'var(--color-sky-100)',
foreground: 'var(--color-sky-700)',
hover: 'color-mix(in oklab, var(--color-sky-200) 80%, transparent)',
},
{
active: 'var(--color-fuchsia-800)',
background: 'var(--color-fuchsia-100)',
foreground: 'var(--color-fuchsia-700)',
hover: 'color-mix(in oklab, var(--color-fuchsia-200) 80%, transparent)',
},
{
active: 'var(--color-orange-800)',
background: 'var(--color-orange-100)',
foreground: 'var(--color-orange-700)',
hover: 'color-mix(in oklab, var(--color-orange-200) 80%, transparent)',
},
{
active: 'var(--color-cyan-800)',
background: 'var(--color-cyan-100)',
foreground: 'var(--color-cyan-700)',
hover: 'color-mix(in oklab, var(--color-cyan-200) 80%, transparent)',
},
{
active: 'var(--color-rose-800)',
background: 'var(--color-rose-100)',
foreground: 'var(--color-rose-700)',
hover: 'color-mix(in oklab, var(--color-rose-200) 80%, transparent)',
},
] as const;
const escapeCssString = (value: string) =>
Array.from(value)
.map((character) => {
const code = character.codePointAt(0) ?? 0;
if (character === '"' || character === '\\') return `\\${character}`;
if (code < 0x20 || code === 0x7f) return `\\${code.toString(16)} `;
return character;
})
.join('');
const colorDeclarations = ({
active,
background,
foreground,
hover,
}: SuggestionColor) =>
`--suggestion-active:${active};--suggestion-bg:${background};--suggestion-fg:${foreground};--suggestion-hover:${hover};`;
function SuggestionColorStyles({ editableRef }: EditableSiblingProps) {
const scopeId = React.useId();
const { activeId } = useActiveSuggestion();
// The active change's card, read again after each review commit, so the
// active rule follows the card through a merge or a new oldest change.
const activeCard = useEditorSelector((editor) =>
activeId
? (editor.plugin(AuthoredPlugin).read.groupOf(activeId)?.id ?? null)
: null
);
React.useLayoutEffect(() => {
const root = editableRef.current;
if (!root) return undefined;
root.setAttribute('data-editor-suggestion-scope', scopeId);
return () => {
if (root.getAttribute('data-editor-suggestion-scope') === scopeId) {
root.removeAttribute('data-editor-suggestion-scope');
}
};
}, [editableRef, scopeId]);
const scope = `[data-editor-suggestion-scope="${escapeCssString(scopeId)}"]`;
// The active rule follows the color rules, so it wins on a highlight that
// also paints another card, and it shows the active card's own colors.
const rules = SUGGESTION_COLORS.map(
(color, slot) =>
`${scope} [data-editor-authored-color="${slot}"]{${colorDeclarations(color)}}`
);
if (activeCard) {
const color =
SUGGESTION_COLORS[
suggestionColorOf(activeCard, SUGGESTION_COLORS.length)
];
rules.push(
`${scope} [data-editor-authored-groups~="${escapeCssString(
activeCard
)}"]{${colorDeclarations(color)}--suggestion-bg:${color.hover};--suggestion-fg:${color.active};}`
);
}
return (
<style
data-editor-suggestion-active={activeId ?? undefined}
data-editor-suggestion-colors=""
>
{rules.join('')}
</style>
);
}
const REFUSED = new Map([
[
'code-block',
"Suggesting can't change a code block yet, or a table that holds one. Switch to Editing to change them.",
],
[
'table',
"Suggesting can add or delete a whole table, but can't yet change its rows, columns, cells or sizes, or add or delete a block that holds a table. Switch to Editing to make those changes.",
],
]);
const refusedPlaces = new Intl.ListFormat('en');
function vetoMessage(reasons: readonly string[]) {
const places = reasons.filter((reason) => !REFUSED.has(reason));
const sentences =
places.length > 0
? [
`Suggesting is off in ${refusedPlaces.format(places)} for now. Switch to Editing to change them.`,
]
: [];
return [
...sentences,
...reasons.flatMap((reason) => REFUSED.get(reason) ?? []),
].join(' ');
}
function SuggestionRefusals() {
const editor = useEditor();
React.useEffect(() => {
const authored = editor.plugin(AuthoredPlugin);
return authored.api.subscribeRefusals((refusal) => {
const view = authored.read.view();
// A reason names content a pending join moves, which Editing refuses
// too, so a Suggesting writer reads why instead of a hint to switch.
const unrecorded =
'intent' in view && view.intent === 'edit'
? 'Editing cannot record this change next to a pending suggestion yet. Accept or reject that suggestion first.'
: refusal.reasons.length > 0
? refusal.message
: 'Suggesting cannot record this change yet. Switch to Editing to make it.';
toast.error(
refusal.code === 'veto'
? vetoMessage(refusal.reasons)
: refusal.code === 'generated-values'
? 'Suggesting is off in this editor.'
: unrecorded,
{ id: 'suggestion-refusal' }
);
});
}, [editor]);
return null;
}
function SuggestionSiblings(props: EditableSiblingProps) {
return (
<>
<SuggestionColorStyles {...props} />
<SuggestionRefusals />
</>
);
}
const SUGGESTED_TEXT =
'[&_:is([data-editor-node=text],[data-editor-text-piece])[data-editor-authored-change]]:bg-[var(--suggestion-bg,var(--color-emerald-100))] [&_:is([data-editor-node=text],[data-editor-text-piece])[data-editor-authored-change]]:text-[var(--suggestion-fg,var(--color-emerald-700))] [&_:is([data-editor-node=text],[data-editor-text-piece])[data-editor-authored-change]:hover]:bg-[var(--suggestion-hover,var(--color-emerald-200))] [&_:is([data-editor-node=text],[data-editor-text-piece])[data-editor-authored-kind~=insert]]:underline [&_:is([data-editor-node=text],[data-editor-text-piece])[data-editor-authored-kind~=insert]]:decoration-2 [&_:is([data-editor-node=text],[data-editor-text-piece])[data-editor-authored-kind~=insert]]:underline-offset-2 [&_:is([data-editor-node=text],[data-editor-text-piece])[data-editor-authored-kind~=delete]]:line-through';
const CHANGED_BLOCK_BAR =
'[&_[data-editor-node=element][data-editor-authored-change]:not([data-editor-inline])]:after:pointer-events-none [&_[data-editor-node=element][data-editor-authored-change]:not([data-editor-inline])]:after:absolute [&_[data-editor-node=element][data-editor-authored-change]:not([data-editor-inline])]:after:inset-y-1 [&_[data-editor-node=element][data-editor-authored-change]:not([data-editor-inline])]:after:-start-7 [&_[data-editor-node=element][data-editor-authored-change]:not([data-editor-inline])]:after:w-0.5 [&_[data-editor-node=element][data-editor-authored-change]:not([data-editor-inline])]:after:rounded-full [&_[data-editor-node=element][data-editor-authored-change]:not([data-editor-inline])]:after:bg-[var(--suggestion-fg,var(--color-emerald-700))] [&_[data-editor-node=element][data-editor-authored-change]:not([data-editor-inline])]:after:content-[""]';
const LINE_BREAK_PILCROW =
'[&_[data-editor-node=element][data-editor-authored-change]:is([data-editor-authored-kind~=split],[data-editor-authored-kind~=join]):not([data-editor-inline])]:after:-start-8 [&_[data-editor-node=element][data-editor-authored-change]:is([data-editor-authored-kind~=split],[data-editor-authored-kind~=join]):not([data-editor-inline])]:after:w-auto [&_[data-editor-node=element][data-editor-authored-change]:is([data-editor-authored-kind~=split],[data-editor-authored-kind~=join]):not([data-editor-inline])]:after:bg-transparent [&_[data-editor-node=element][data-editor-authored-change]:is([data-editor-authored-kind~=split],[data-editor-authored-kind~=join]):not([data-editor-inline])]:after:font-semibold [&_[data-editor-node=element][data-editor-authored-change]:is([data-editor-authored-kind~=split],[data-editor-authored-kind~=join]):not([data-editor-inline])]:after:text-[var(--suggestion-fg,var(--color-emerald-700))] [&_[data-editor-node=element][data-editor-authored-change]:is([data-editor-authored-kind~=split],[data-editor-authored-kind~=join]):not([data-editor-inline])]:after:content-["¶"] [&_[data-editor-node=element][data-editor-authored-change][data-editor-authored-kind~=join]:not([data-editor-inline])]:after:line-through';
const WHOLE_TABLE_TINT =
'[&_:is(td,th):is([data-editor-authored-kind~=insert],[data-editor-authored-kind~=delete])]:bg-[var(--suggestion-bg,var(--color-emerald-100))] [&_:is(tr,td,th)[data-editor-node=element]:is([data-editor-authored-kind~=insert],[data-editor-authored-kind~=delete]):not([data-editor-inline],[data-editor-authored-kind~=format])]:after:content-none [&_:is(td,th):is([data-editor-authored-kind~=insert],[data-editor-authored-kind~=delete])_[data-editor-node=element][data-editor-authored-change]:not([data-editor-authored-kind~=split],[data-editor-authored-kind~=join],[data-editor-authored-kind~=format])]:after:content-none';
export const SuggestionKit = [
SuggestionPlugin.configure(() => ({
render: {
contentAttributes: {
className: [
SUGGESTED_TEXT,
CHANGED_BLOCK_BAR,
LINE_BREAK_PILCROW,
WHOLE_TABLE_TINT,
].join(' '),
},
},
slots: { afterEditable: SuggestionSiblings },
})),
];
'use client';
 
import { AuthoredPlugin } from 'platejs/authored';
import {
  type EditableSiblingProps,
  useEditor,
  useEditorSelector,
} from 'platejs/react';
import { suggestionColorOf } from 'platejs/suggestion';
import {
  SuggestionPlugin,
  useActiveSuggestion,
} from 'platejs/suggestion/react';
import * as React from 'react';
import { toast } from 'sonner';
 
type SuggestionColor = Readonly<{
  active: string;
  background: string;
  foreground: string;
  hover: string;
}>;
 
const SUGGESTION_COLORS: readonly SuggestionColor[] = [
  {
    active: 'var(--color-emerald-800)',
    background: 'var(--color-emerald-100)',
    foreground: 'var(--color-emerald-700)',
    hover: 'color-mix(in oklab, var(--color-emerald-200) 80%, transparent)',
  },
  {
    active: 'var(--color-violet-800)',
    background: 'var(--color-violet-100)',
    foreground: 'var(--color-violet-700)',
    hover: 'color-mix(in oklab, var(--color-violet-200) 80%, transparent)',
  },
  {
    active: 'var(--color-sky-800)',
    background: 'var(--color-sky-100)',
    foreground: 'var(--color-sky-700)',
    hover: 'color-mix(in oklab, var(--color-sky-200) 80%, transparent)',
  },
  {
    active: 'var(--color-fuchsia-800)',
    background: 'var(--color-fuchsia-100)',
    foreground: 'var(--color-fuchsia-700)',
    hover: 'color-mix(in oklab, var(--color-fuchsia-200) 80%, transparent)',
  },
  {
    active: 'var(--color-orange-800)',
    background: 'var(--color-orange-100)',
    foreground: 'var(--color-orange-700)',
    hover: 'color-mix(in oklab, var(--color-orange-200) 80%, transparent)',
  },
  {
    active: 'var(--color-cyan-800)',
    background: 'var(--color-cyan-100)',
    foreground: 'var(--color-cyan-700)',
    hover: 'color-mix(in oklab, var(--color-cyan-200) 80%, transparent)',
  },
  {
    active: 'var(--color-rose-800)',
    background: 'var(--color-rose-100)',
    foreground: 'var(--color-rose-700)',
    hover: 'color-mix(in oklab, var(--color-rose-200) 80%, transparent)',
  },
] as const;
 
const escapeCssString = (value: string) =>
  Array.from(value)
    .map((character) => {
      const code = character.codePointAt(0) ?? 0;
 
      if (character === '"' || character === '\\') return `\\${character}`;
      if (code < 0x20 || code === 0x7f) return `\\${code.toString(16)} `;
 
      return character;
    })
    .join('');
 
const colorDeclarations = ({
  active,
  background,
  foreground,
  hover,
}: SuggestionColor) =>
  `--suggestion-active:${active};--suggestion-bg:${background};--suggestion-fg:${foreground};--suggestion-hover:${hover};`;
 
function SuggestionColorStyles({ editableRef }: EditableSiblingProps) {
  const scopeId = React.useId();
  const { activeId } = useActiveSuggestion();
  // The active change's card, read again after each review commit, so the
  // active rule follows the card through a merge or a new oldest change.
  const activeCard = useEditorSelector((editor) =>
    activeId
      ? (editor.plugin(AuthoredPlugin).read.groupOf(activeId)?.id ?? null)
      : null
  );
 
  React.useLayoutEffect(() => {
    const root = editableRef.current;
    if (!root) return undefined;
 
    root.setAttribute('data-editor-suggestion-scope', scopeId);
 
    return () => {
      if (root.getAttribute('data-editor-suggestion-scope') === scopeId) {
        root.removeAttribute('data-editor-suggestion-scope');
      }
    };
  }, [editableRef, scopeId]);
 
  const scope = `[data-editor-suggestion-scope="${escapeCssString(scopeId)}"]`;
  // The active rule follows the color rules, so it wins on a highlight that
  // also paints another card, and it shows the active card's own colors.
  const rules = SUGGESTION_COLORS.map(
    (color, slot) =>
      `${scope} [data-editor-authored-color="${slot}"]{${colorDeclarations(color)}}`
  );
 
  if (activeCard) {
    const color =
      SUGGESTION_COLORS[
        suggestionColorOf(activeCard, SUGGESTION_COLORS.length)
      ];
 
    rules.push(
      `${scope} [data-editor-authored-groups~="${escapeCssString(
        activeCard
      )}"]{${colorDeclarations(color)}--suggestion-bg:${color.hover};--suggestion-fg:${color.active};}`
    );
  }
 
  return (
    <style
      data-editor-suggestion-active={activeId ?? undefined}
      data-editor-suggestion-colors=""
    >
      {rules.join('')}
    </style>
  );
}
 
const REFUSED = new Map([
  [
    'code-block',
    "Suggesting can't change a code block yet, or a table that holds one. Switch to Editing to change them.",
  ],
  [
    'table',
    "Suggesting can add or delete a whole table, but can't yet change its rows, columns, cells or sizes, or add or delete a block that holds a table. Switch to Editing to make those changes.",
  ],
]);
const refusedPlaces = new Intl.ListFormat('en');
 
function vetoMessage(reasons: readonly string[]) {
  const places = reasons.filter((reason) => !REFUSED.has(reason));
  const sentences =
    places.length > 0
      ? [
          `Suggesting is off in ${refusedPlaces.format(places)} for now. Switch to Editing to change them.`,
        ]
      : [];
 
  return [
    ...sentences,
    ...reasons.flatMap((reason) => REFUSED.get(reason) ?? []),
  ].join(' ');
}
 
function SuggestionRefusals() {
  const editor = useEditor();
 
  React.useEffect(() => {
    const authored = editor.plugin(AuthoredPlugin);
 
    return authored.api.subscribeRefusals((refusal) => {
      const view = authored.read.view();
      // A reason names content a pending join moves, which Editing refuses
      // too, so a Suggesting writer reads why instead of a hint to switch.
      const unrecorded =
        'intent' in view && view.intent === 'edit'
          ? 'Editing cannot record this change next to a pending suggestion yet. Accept or reject that suggestion first.'
          : refusal.reasons.length > 0
            ? refusal.message
            : 'Suggesting cannot record this change yet. Switch to Editing to make it.';
 
      toast.error(
        refusal.code === 'veto'
          ? vetoMessage(refusal.reasons)
          : refusal.code === 'generated-values'
            ? 'Suggesting is off in this editor.'
            : unrecorded,
        { id: 'suggestion-refusal' }
      );
    });
  }, [editor]);
 
  return null;
}
 
function SuggestionSiblings(props: EditableSiblingProps) {
  return (
    <>
      <SuggestionColorStyles {...props} />
      <SuggestionRefusals />
    </>
  );
}
 
const SUGGESTED_TEXT =
  '[&_:is([data-editor-node=text],[data-editor-text-piece])[data-editor-authored-change]]:bg-[var(--suggestion-bg,var(--color-emerald-100))] [&_:is([data-editor-node=text],[data-editor-text-piece])[data-editor-authored-change]]:text-[var(--suggestion-fg,var(--color-emerald-700))] [&_:is([data-editor-node=text],[data-editor-text-piece])[data-editor-authored-change]:hover]:bg-[var(--suggestion-hover,var(--color-emerald-200))] [&_:is([data-editor-node=text],[data-editor-text-piece])[data-editor-authored-kind~=insert]]:underline [&_:is([data-editor-node=text],[data-editor-text-piece])[data-editor-authored-kind~=insert]]:decoration-2 [&_:is([data-editor-node=text],[data-editor-text-piece])[data-editor-authored-kind~=insert]]:underline-offset-2 [&_:is([data-editor-node=text],[data-editor-text-piece])[data-editor-authored-kind~=delete]]:line-through';
const CHANGED_BLOCK_BAR =
  '[&_[data-editor-node=element][data-editor-authored-change]:not([data-editor-inline])]:after:pointer-events-none [&_[data-editor-node=element][data-editor-authored-change]:not([data-editor-inline])]:after:absolute [&_[data-editor-node=element][data-editor-authored-change]:not([data-editor-inline])]:after:inset-y-1 [&_[data-editor-node=element][data-editor-authored-change]:not([data-editor-inline])]:after:-start-7 [&_[data-editor-node=element][data-editor-authored-change]:not([data-editor-inline])]:after:w-0.5 [&_[data-editor-node=element][data-editor-authored-change]:not([data-editor-inline])]:after:rounded-full [&_[data-editor-node=element][data-editor-authored-change]:not([data-editor-inline])]:after:bg-[var(--suggestion-fg,var(--color-emerald-700))] [&_[data-editor-node=element][data-editor-authored-change]:not([data-editor-inline])]:after:content-[""]';
const LINE_BREAK_PILCROW =
  '[&_[data-editor-node=element][data-editor-authored-change]:is([data-editor-authored-kind~=split],[data-editor-authored-kind~=join]):not([data-editor-inline])]:after:-start-8 [&_[data-editor-node=element][data-editor-authored-change]:is([data-editor-authored-kind~=split],[data-editor-authored-kind~=join]):not([data-editor-inline])]:after:w-auto [&_[data-editor-node=element][data-editor-authored-change]:is([data-editor-authored-kind~=split],[data-editor-authored-kind~=join]):not([data-editor-inline])]:after:bg-transparent [&_[data-editor-node=element][data-editor-authored-change]:is([data-editor-authored-kind~=split],[data-editor-authored-kind~=join]):not([data-editor-inline])]:after:font-semibold [&_[data-editor-node=element][data-editor-authored-change]:is([data-editor-authored-kind~=split],[data-editor-authored-kind~=join]):not([data-editor-inline])]:after:text-[var(--suggestion-fg,var(--color-emerald-700))] [&_[data-editor-node=element][data-editor-authored-change]:is([data-editor-authored-kind~=split],[data-editor-authored-kind~=join]):not([data-editor-inline])]:after:content-["¶"] [&_[data-editor-node=element][data-editor-authored-change][data-editor-authored-kind~=join]:not([data-editor-inline])]:after:line-through';
const WHOLE_TABLE_TINT =
  '[&_:is(td,th):is([data-editor-authored-kind~=insert],[data-editor-authored-kind~=delete])]:bg-[var(--suggestion-bg,var(--color-emerald-100))] [&_:is(tr,td,th)[data-editor-node=element]:is([data-editor-authored-kind~=insert],[data-editor-authored-kind~=delete]):not([data-editor-inline],[data-editor-authored-kind~=format])]:after:content-none [&_:is(td,th):is([data-editor-authored-kind~=insert],[data-editor-authored-kind~=delete])_[data-editor-node=element][data-editor-authored-change]:not([data-editor-authored-kind~=split],[data-editor-authored-kind~=join],[data-editor-authored-kind~=format])]:after:content-none';
 
export const SuggestionKit = [
  SuggestionPlugin.configure(() => ({
    render: {
      contentAttributes: {
        className: [
          SUGGESTED_TEXT,
          CHANGED_BLOCK_BAR,
          LINE_BREAK_PILCROW,
          WHOLE_TABLE_TINT,
        ].join(' '),
      },
    },
    slots: { afterEditable: SuggestionSiblings },
  })),
];
import { Toolbar } from '@/components/editor/toolbar';
export function SuggestionEditor() {
const editor = useCreateEditor({
plugins: [
...BasicBlocksKit,
...SuggestionKit,
...DiscussionKit,
CommentsPlugin.configure({
initialState: {
users: { alice: { id: 'alice', name: 'Alice' } },
},
}),
],
initialValue: [
{ type: 'paragraph', children: [{ text: 'Edit this sentence.' }] },
],
userId: 'alice',
});
return (
<EditorRoot editor={editor} authored={{ intent: 'propose' }}>
<EditorContainer>
<Toolbar>
<UndoToolbarButton />
<RedoToolbarButton />
<SuggestionToolbarButton />
</Toolbar>
<Editor />
</EditorContainer>
</EditorRoot>
);
}
components/editor/suggestion-editor.tsx
'use client';
 
import { CommentsPlugin } from 'platejs/comments/react';
import { EditorRoot, useCreateEditor } from 'platejs/react';
 
import { BasicBlocksKit } from '@/components/editor/basic-blocks';
import { DiscussionKit } from '@/components/editor/discussion';
import { Editor, EditorContainer } from '@/components/editor/editor';
import {
  RedoToolbarButton,
  UndoToolbarButton,
} from '@/components/editor/history-toolbar-button';
import { SuggestionKit } from '@/components/editor/suggestion';
import { SuggestionToolbarButton } from '@/components/editor/suggestion-toolbar-button';
import { Toolbar } from '@/components/editor/toolbar';
 
export function SuggestionEditor() {
  const editor = useCreateEditor({
    plugins: [
      ...BasicBlocksKit,
      ...SuggestionKit,
      ...DiscussionKit,
      CommentsPlugin.configure({
        initialState: {
          users: { alice: { id: 'alice', name: 'Alice' } },
        },
      }),
    ],
    initialValue: [
      { type: 'paragraph', children: [{ text: 'Edit this sentence.' }] },
    ],
    userId: 'alice',
  });
 
  return (
    <EditorRoot editor={editor} authored={{ intent: 'propose' }}>
      <EditorContainer>
        <Toolbar>
          <UndoToolbarButton />
          <RedoToolbarButton />
          <SuggestionToolbarButton />
        </Toolbar>
        <Editor />
      </EditorContainer>
    </EditorRoot>
  );
}
=
{()
=>
authored.api.setView({ intent: isSuggesting ? 'edit' : 'propose' })
}
>
{isSuggesting ? 'Stop suggesting' : 'Suggest edits'}
</button>
);
}
decide
({ action:
'accept'
, changes });