Add comments to text, reply in threads, and keep them attached as your document changes.
Click a highlight to open its conversation. Select text and use the Comment button or Mod+Shift+M to start a thread. You are Alice: reply to an existing conversation, or create your own thread to try editing, deleting, and resolving comments. Press Escape to cancel a new comment.
For comments alongside proposed edits, see Discussion.
DiscussionKit supplies comment styling, block buttons, and the floating thread view. Add SuggestionKit only when the editor reviews authored changes. The example uses comments without suggestions.
'use client';
import {
CheckIcon,
MessageSquareTextIcon,
MessagesSquareIcon,
PencilLineIcon,
XIcon,
} from 'lucide-react';
import {
ElementApi,
type NodeKey,
type Path,
PathApi,
type Point,
type Range,
RangeApi,
} from 'platejs';
import type {
AuthoredChange,
AuthoredChangeGroup,
AuthoredChangePart,
AuthoredGroupDetails,
AuthoredGroupPart,
AuthoredResult,
Load thread rows from your tables and the ranges saved with the matching document revision:
"use client";
import type { EditorValueInput, Value } from "platejs";
import type { CommentRanges, CommentThread, CommentUser } from "platejs/comments";
import { CommentsPlugin } from "platejs/comments/react";
import { EditorRoot, useCreateEditor } from "platejs/react";
import { BasicBlocksKit } from "@/components/editor/basic-blocks";
import { AllCommentsButton, CommentToolbarButton } from "@/components/editor/comment-toolbar-button";
import { DiscussionKit } from "@/components/editor/discussion";
import { Editor, EditorContainer } from "@/components/editor/editor";
import { LinkKit } from
initialComments initializes each editor once. Pass the ranges saved with value, never ranges from another revision. Updating initial props does not replace the current records.
Click “overlapping” to open both conversations. Edit the highlighted text, then undo and redo. Use All comments to find published conversations after their quoted text disappears.
Inserting text inside a range expands it; deleting text contracts it. Text inserted at either boundary stays outside. An intentional atomic replacement carries the target to its replacement text. Deleting the target and typing later is a separate edit, so the later text does not inherit the comment. Content that lands between a deleted range's ends can still join it, such as text typed into a paragraph the range emptied or a block moved into that spot. When no range can be shown, attachment(id) reports unavailable; All comments keeps the thread and its original excerpt reachable without a stale block badge. Undo and redo in the live session restore mapped coverage, including backward direction and overlaps.
Drag a commented phrase, or cut it and paste it right away in the same editor, and the comment moves with the text. Undo and redo move it back and forth. When only part of the phrase moves, the comment keeps the part that stays, and letters the move brings from outside never join it. In Suggesting, the comment stays on the struck original until the move is accepted or rejected. A pasted copy, and a cut pasted a second time, carry no comment. A paste without formatting, a paste after another edit or into another editor, and any move in a document bound to Yjs map the comment by position, so a comment whose whole text moves reads unavailable.
Save a snapshot, change the document or add a comment, then reload. The fresh editor loads the saved document and its ranges with the threads in the example's in-memory table, and starts an empty local undo stack. A thread created after the snapshot has no saved range, so it loads as unavailable. Open All comments to review resolved or unavailable conversations. The reply form simulates one failed send: the draft stays in place, and sending again adds the reply.
Choose Preview saved version with current comments to open the saved document with current conversations and that revision's targets. Threads created after the snapshot remain in the panel with unavailable targets.
Await the Comments mutation in CommentComposer's onSubmit and treat only status: 'applied' as success. Preserve the rich-text input on rejection or an error, and block duplicate submissions while waiting. Configure persistence and authorization through initialState.mutate.
Open All comments in the read-only document to read, navigate, and reply. Document read-only prevents range creation and text edits. Conversation actions still record the editor's userId, and mutate still authorizes them. The static snapshot paints the same initial ranges without thread controls.
Set readOnly on both EditorRoot and Editor to prevent document edits. Comment permissions remain an application decision; this example permits replies.
For static rendering, configure BaseCommentsPlugin with commentDecorationAttributes from the copied comment-static item, then pass the editor to EditorStatic. Install those items when adding a static view:
Each independently loaded editor needs the ranges saved with its document revision. Views of one model share that loaded data. Plain coordinates cannot identify edits that happened in a different document.
CommentThread contains conversation data and a semantic target: { type: 'range' } or { type: 'change', id }. It never contains a mapped Range. Message bodies use Plate Value; timestamps use ISO 8601 strings. resolution is null for an open thread, or { resolvedAt: string | null, userId: string | null } for a resolved thread.
Thread records and private anchors belong to the shared editor model. Each view reads its own placement: the same thread can have different ranges, or be unavailable, in different projections without copying its record or anchor.
Read placement through the exact view's plugin API. In this example, editor is the view that will use the returned coordinates; React UI can obtain its mounted editor with useEditor():
import { CommentsPlugin } from "platejs/comments/react";
const comments = editor.plugin(CommentsPlugin).api;
const thread = comments.getThread(threadId);
const attachment = comments.attachment(threadId);
if (attachment?.type === "range" && attachment.status === "attached") {
editor.update.selection.set(attachment.range);
}import { CommentsPlugin } from "platejs/comments/react";
const comments = editor.plugin(CommentsPlugin).api;
const thread = comments.getThread(threadId);
const attachment = comments.attachment(threadId);
if (attachment?.type === "range" && attachment.status === "attached") {
editor.update.selection.set(attachment.range);
}attachment(id) returns one of these values:
| Value | Meaning |
|---|---|
{ type: 'range', status: 'attached', range } | Current mapped coverage is available |
{ type: 'range', status: 'unavailable' } | No range can be shown in this document projection |
{ type: 'change', id } | Locate the stable change ID through Authored |
null | No thread exists for that ID |
An unavailable attachment does not prove deletion. It can also mean that a projection hides the target or that a historical revision has no target for the thread. Keep conversation data visible independently of inline placement.
A thread on a suggestion keeps its { type: 'change', id } target after the change stops being pending. Read editor.plugin(AuthoredPlugin).read.outcome(id) to tell whether the change is still pending, was accepted, rejected or both, or left with no verdict, as Authored Changes describes.
A thread can sit in a named root, such as the text of a board note. The page's view reads it with the note's root on both points of its range. A note's view reads a thread in any other root, the page's included, as unavailable.
A thread and each of its messages can carry data, a JSON object your application owns, such as reactions or the model that wrote a comment. Comments checks that it is JSON, stores a frozen copy with the record, and never reads its keys. Set it when you create a thread or reply, and change it with setData:
import { CommentsPlugin } from "platejs/comments/react";
const comments = editor.plugin(CommentsPlugin).api;
await comments.createThread({ body, data: { priority: "high" }, target });
await comments.reply(threadId, body, { data: { reactions: [] } });
await comments.setData(threadId, { priority: "low" });
await comments.setData(threadId, { reactions: ["+1"] }, { messageId });
await comments.setData(threadId, null);import { CommentsPlugin } from "platejs/comments/react";
const comments = editor.plugin(CommentsPlugin).api;
await comments.createThread({ body, data: { priority: "high" }, target });
await comments.reply(threadId, body, { data: { reactions: [] } });
await comments.setData(threadId, { priority: "low" });
await comments.setData(threadId, { reactions: ["+1"] }, { messageId });
await comments.setData(threadId, null);The data passed to createThread or createDraft belongs to the thread; its first message gets none. setData replaces the data of a published thread, or of one message when you pass messageId, and null removes it. It runs through mutate with the operation 'setData' and stays outside document history. Replies, message edits and resolution keep the data a record already has. A value that is not a JSON object answers invalid, and createDraft returns null for it. A saved row or a record mutate returns with data: null reads as one without data, such as a nullable JSON column. A saved row whose data is any other value that is not a JSON object drops with an 'invalid-thread' issue.
Render AllCommentsButton inside a toolbar whenever the editor installs Comments. It opens a lazy, paginated dialog over published records and works without a document selection, in read-only views, and without Suggestions. The All, Open, and Resolved filters use conversation state; target availability does not remove a record from those filters.
Each row labels its target. A target the current view can show reads Attached to document, and a range it cannot show reads Target unavailable in this view. A thread on a suggestion says what the review did once the suggestion is no longer pending: Suggestion accepted, Suggestion rejected, Suggestion accepted and rejected when it holds both verdicts, or Suggestion deleted when it left with no verdict, such as when accepting a struck table took it. These labels read the same after a reload. A pending suggestion reads Target unavailable in this view under a preview, because its ranges name places of the stored document.
Only the mounted page resolves targets. Show in document works only for an attached target. It reads the target again when clicked and on the next frame, then selects and scrolls the exact current-view range. For a thread in a board note, it selects the note's text, focuses the note and pans the board when part of the note is out of view. Dirty reply or edit input and pending actions keep their page mounted and block dismissal, filtering, paging, navigation, and destructive deletion until the action succeeds or the user cancels.
Comments keeps each conversation in two parts. The thread row holds what people wrote. Store it in your own tables and change it through mutate. The range is where the thread sits in the text, and it changes with the document. Save api.ranges() with each document revision:
import { CommentsPlugin } from "platejs/comments/react";
const revision = {
commentRanges: editor.plugin(CommentsPlugin).api.ranges(),
document: editor.read.value(),
revisionId,
};
await repository.put(revision, { ifMatch: previousRevision });import { CommentsPlugin } from "platejs/comments/react";
const revision = {
commentRanges: editor.plugin(CommentsPlugin).api.ranges(),
document: editor.read.value(),
revisionId,
};
await repository.put(revision, { ifMatch: previousRevision });In this example, repository is your application's storage adapter. It checks the expected revision before it commits.
ranges() returns CommentRanges, a record of plain Range values keyed by thread ID. It includes published threads, creates and draft publishes still waiting on mutate, drafts whose publish threw, and orphans. Other local drafts, ranges that no longer resolve and threads on a suggestion have no entry; a suggestion's thread row keeps the change's ID instead. A thread whose text was deleted reads unavailable but keeps its entry, so text that comes back between its saved points attaches it again. Other content that lands between those points attaches it too. A range matches only the revision it was saved with.
A range in a named root, such as the text of a board note, carries that root on both points. A page range carries none:
editor.plugin(CommentsPlugin).api.ranges();
// {
// t1: {
// anchor: { path: [0, 0], offset: 0 },
// focus: { path: [0, 0], offset: 5 },
// },
// t2: {
// anchor: { path: [0, 0, 0], offset: 0, root: "board:demo" },
// focus: { path: [0, 0, 0], offset: 4, root: "board:demo" },
// },
// }editor.plugin(CommentsPlugin).api.ranges();
// {
// t1: {
// anchor: { path: [0, 0], offset: 0 },
// focus: { path: [0, 0], offset: 5 },
// },
// t2: {
// anchor: { path: [0, 0, 0], offset: 0, root: "board:demo" },
// focus: { path: [0, 0, 0], offset: 4, root: "board:demo" },
// },
// }To load, create a fresh editor from revision.document with the same content plugins, and pass { threads, ranges: revision.commentRanges } as initialComments, with threads read from your table. The pair has the type SavedComments.
When a schema migration upgrades the document, pass the revision's ranges as ranges to the same migrateDocument call and save the ranges it returns, as Migrate comment ranges shows.
Comments admits each row on its own. A malformed or unpublished thread, a duplicate thread ID and a range outside the document each drop alone. getSnapshot().issues lists them as CommentsLoadIssue values, { code, id }, with one 'orphan-range' for each current orphan:
code | Meaning |
|---|---|
'invalid-thread' | The thread row was malformed or unpublished and did not load |
'duplicate-thread' | A second row reused a thread ID; the first row loaded |
'invalid-range' | The range was malformed, outside the document, across two roots or on a suggestion's thread |
'orphan-range' | A saved range has no loaded thread; it leaves issues when the orphan attaches or is discarded |
A load throws only when threads is not an array or ranges is not a record. Comments cannot tell a foreign document whose coordinates happen to be valid.
An orphan is a saved range with no loaded thread. It maps with the document, ranges() saves it again, and it paints nothing. A thread missing from one load, such as one whose query failed, keeps its range this way, and so does a create whose mutate threw. The orphan attaches when its thread loads through replace or a committed create.
When your server says the thread was rejected or deleted, call api.discardOrphan(id). It returns 'discarded', or 'not-orphan' when the ID holds no orphan. A thrown mutate keeps the create's range as an orphan, because the server may have stored the create. The orphan is the create's own range, so an undo that restores its words restores the saved range too. A create that mutate rejects drops only the range that attempt added. An orphan an earlier attempt kept stays, so a retry the server rejects because it already stored the thread keeps its range.
A draft whose publish threw keeps its range in ranges() while it stays a draft. Discarding a draft whose publish threw, or is still waiting on mutate, turns its range into an orphan. If that waiting publish is then rejected, or never reaches mutate, the orphan goes, unless an earlier publish of the draft threw. The server may have stored that earlier publish, so its range stays. createDraft returns null for an ID that holds an orphan, so an ID never has two saved ranges.
Creating a comment changes no document value, so EditorRoot's onValueChange alone misses it. An app that autosaves also schedules a save from api.subscribeRanges(listener). The listener runs when a thread gains or loses its saved range or saves a different one, and never for document mapping:
import { CommentsPlugin } from "platejs/comments/react";
import * as React from "react";
React.useEffect(
() => editor.plugin(CommentsPlugin).api.subscribeRanges(scheduleSave),
[editor, scheduleSave]
);import { CommentsPlugin } from "platejs/comments/react";
import * as React from "react";
React.useEffect(
() => editor.plugin(CommentsPlugin).api.subscribeRanges(scheduleSave),
[editor, scheduleSave]
);Ranges stay readable in every React layout and passive effect cleanup when the editor unmounts. ranges() throws once the editor is destroyed. A queued save that runs after unmount must capture the revision in a cleanup:
React.useEffect(
() => () => {
queueSave({
commentRanges: editor.plugin(CommentsPlugin).api.ranges(),
document: editor.read.value(),
});
},
[editor]
);React.useEffect(
() => () => {
queueSave({
commentRanges: editor.plugin(CommentsPlugin).api.ranges(),
document: editor.read.value(),
});
},
[editor]
);scheduleSave and queueSave are your application's save functions.
For an explicit full-document import, construct the complete replacement editor with the imported document, comment threads and ranges, and users before changing the mounted editor. Swap the editor instance only after construction succeeds. This keeps the previous document, comments, users, history, drafts and pending work intact when preparation fails.
import { createEditor } from 'platejs';
const candidate = createEditor({
initialValue: importedDocument,
plugins: [
...documentPlugins,
CommentsPlugin.configure({
initialState: {
initialComments: importedComments,
users: importedUsers,
},
}),
],
userId: editor.userId,
});
setEditor(candidate);import { createEditor } from 'platejs';
const candidate = createEditor({
initialValue: importedDocument,
plugins: [
...documentPlugins,
CommentsPlugin.configure({
initialState: {
initialComments: importedComments,
users: importedUsers,
},
}),
],
userId: editor.userId,
});
setEditor(candidate);replace({ threads, ranges }) admits rows as a load does and stages every
comment before atomic publication. It releases the prior attachments, clears drafts and the pending
composer, and fences late mutation results. It does not invoke mutate or add
comment history. Use it to prepare an authoritative snapshot against its
matching detached document, never to apply one server mutation. Replacing the
document and comments separately on a mounted editor is not atomic:
rollback cannot restore cleared document history, comment drafts, pending
composer state or retired mutation queues. Applications that must preserve the
editor instance need one owner that can commit or discard all of those runtime
resources together.
Authored remains optional for ordinary range comments. Ordinary reload starts fresh local undo. getThreads() reads the live thread records; your tables keep their durable copy.
Configure your application adapter through CommentsPlugin.configure({ initialState: { mutate } }). The callback receives a structurally valid CommentMutationRequest and returns a CommentMutationDecision, synchronously or through a promise:
import type { Range } from "platejs";
import type { CommentOperation, CommentThread } from "platejs/comments";
export type CommentMutationRequest = Readonly<{
mutationId: string;
operation: CommentOperation;
previous: CommentThread | null;
proposed: CommentThread | null;
range?: Range;
}>;
export type CommentMutationDecision =
| Readonly<{ status: 'commit'; thread: CommentThread | null }>
| Readonly<{ code?: string; status: 'reject' }>;import type { Range } from "platejs";
import type { CommentOperation, CommentThread } from "platejs/comments";
export type CommentMutationRequest = Readonly<{
mutationId: string;
operation: CommentOperation;
previous: CommentThread | null;
proposed: CommentThread | null;
range?: Range;
}>;
export type CommentMutationDecision =
| Readonly<{ status: 'commit'; thread: CommentThread
Authenticate the actor, authorize the operation, and persist it in your service before returning { status: 'commit', thread }. Return the canonical approved record, or thread: null for deletion. The committed record preserves the proposed thread ID and target identity. Return { status: 'reject' } with an optional code to deny a write. A create or draft publish also receives range, the range that ranges() saves for it. Use mutationId for idempotency and enforce cross-client compare-and-swap in your storage layer.
Comments publishes only after commit. Rejection or a thrown error preserves the previous record and composer. Actions are serialized per thread; an editor or thread retired while work is pending can return stale. The default adapter commits locally. Hiding controls or setting document readOnly does not authorize comment writes.
Comments records each thread, draft, reply and resolution as the author of the editor or view the action runs through. To comment as someone other than the editor's user, such as an AI, run the action through a view that names that author:
import { createEditorView } from "platejs";
import { CommentsPlugin } from "platejs/comments/react";
const ai = createEditorView(editor, { authorId: "ai" });
await ai.plugin(CommentsPlugin).api.createThread({
body,
target: { range, type: "range" },
});import { createEditorView } from "platejs";
import { CommentsPlugin } from "platejs/comments/react";
const ai = createEditorView(editor, { authorId: "ai" });
await ai.plugin(CommentsPlugin).api.createThread({
body,
target: { range, type: "range" },
});The new thread and its first message record 'ai' as their userId. The editor and views without an authorId keep the editor's user. Add the author to users so the comment UI shows its name. A view's author is a claim the client makes. mutate receives it in the proposed record, so check there that the signed-in user may write as that author.
Successful local thread creation joins the same session undo order as document edits. History waits for the configured mutation adapter before moving its branch. Undo removes the unchanged one-message thread; redo restores its saved target and canonical thread. A reply, edit, resolution, canonical replacement, rejected mutation, or storage error blocks that replay and keeps it at the history head, so the next document batch is never skipped. A thread created through a read-only view joins no undo order, because that view cannot commit.
Resolve and reopen update conversation metadata outside document undo. Replies, message edits, and explicit message or thread deletion also stay outside document history. Undoing a text deletion can restore its highlight, but never recreates an explicitly deleted conversation.
Accepting or rejecting a suggestion is a document action that can be undone. These decisions preserve its discussion, including messages and resolution. A change-targeted thread follows the same Authored change ID when the pending change becomes visible again.
For a read-only version preview, load the current thread rows with the ranges saved for that exact document revision. This example reads currentThreads from your table:
import type { SavedComments } from "platejs/comments";
const initialComments: SavedComments = {
ranges: revision.commentRanges,
threads: currentThreads,
};import type { SavedComments } from "platejs/comments";
const initialComments: SavedComments = {
ranges: revision.commentRanges,
threads: currentThreads,
};Open a fresh read-only editor with revision.document and this initialComments. Newer threads without a saved range are unavailable. A saved range whose thread has since been deleted loads as an orphan and paints nothing. Change targets can be located only when their IDs exist in that revision's Authored document.
Restoring a version creates a new application revision under a document-head check. Keep the current thread rows, load only the selected revision's ranges, and open a fresh editor with empty local history. Local thread-creation undo is session-only and is not restored from saved ranges or History.toJSON(). See History for local undo.
Independent editors can load the same saved revision and bind their own attachments. Real-time remote comment synchronization is not supported by this persistence API. Mutation results provide canonical records to the initiating editor.
Saved range targets cannot be restored against a changed Yjs room baseline. A state vector alone does not map missed edits, and persisted local undo is not supported on Yjs admission. Your application must establish the exact saved baseline before admitting its targets.
| Owner | Responsibility |
|---|---|
platejs/comments | Own records, actions, subscriptions, and private native range handles |
platejs/comments/react | Add selection commands, shortcuts, and highlight clicks |
Copied comment, comment-toolbar-button, and discussion items | Style highlights; render forms, cards, live block triggers, Floating Discussion, and document-level discovery |
| Your application | Store thread rows, save ranges with each document revision, supply users, and authorize mutations |
Comment messages remain separate from document nodes and marks. A message edit notifies that thread's subscribers without resolving anchors or refreshing editor decorations. users uses the plugin store; subscribe with usePluginStore and update it through store.set. Threads, replies and resolutions record the author of the view they run through, else the editor's userId, or the local user, 'local', when the editor has none.
The headless plugin provides the same data and attachment API without React. This example loads a paragraph-only revision with thread rows from your table; install the matching content plugins for richer documents:
import { BaseParagraphPlugin, createEditor } from "platejs";
import { BaseCommentsPlugin } from "platejs/comments";
const editor = createEditor({
plugins: [BaseParagraphPlugin, BaseCommentsPlugin.configure({
initialState: {
initialComments: { ranges: revision.commentRanges, threads },
},
})],
initialValue: revision.document,
userId: "alice",
});import { BaseParagraphPlugin, createEditor } from "platejs";
import { BaseCommentsPlugin } from "platejs/comments";
const editor = createEditor({
plugins: [BaseParagraphPlugin, BaseCommentsPlugin.configure({
initialState: {
initialComments: { ranges: revision.commentRanges, threads },
},
})],
initialValue: revision.document,
userId: "alice",
});For stored documents with inline comment properties, see Import comment annotations.
Before loading documents that contain comment, comment_*, comment_draft, or commentTransient properties, run extractLegacyCommentRanges and pass its document and ranges to one migrateDocument call:
import {
extractLegacyCommentRanges,
migrateDocument,
} from "platejs/migrations";
const {
document: cleanDocument,
ranges,
report,
} = extractLegacyCommentRanges(legacyDocument, {
threadIds: storedThreads.map((thread) => thread.id),
});
const migrated = migrateDocument(cleanDocument, {
migrations: EditorMigrations,
ranges,
source: 53,
});
console.table(report);import {
extractLegacyCommentRanges,
migrateDocument,
} from "platejs/migrations";
const {
document: cleanDocument,
ranges,
report,
} = extractLegacyCommentRanges(legacyDocument, {
threadIds: storedThreads.map((thread) => thread.id),
});
const migrated = migrateDocument(cleanDocument, {
migrations: EditorMigrations,
ranges,
source: 53,
});
console.table(report);Review every report row, then save migrated.output with the non-null entries of migrated.ranges as its commentRanges. A thread split by visible text without its mark gets no range and a split-group row that lists each part's range. The extractor never invents missing thread IDs. Run the migration offline; the runtime plugin has no legacy fallback. See Migrate comment ranges.
BaseCommentsPlugin from platejs/comments owns headless data and range behavior.CommentsPlugin from platejs/comments/react adds React view interactions.| Method | Purpose |
|---|---|
api.getThreads() | Read immutable semantic thread records |
api.getThread(id) | Read one stable record, or undefined |
api.ranges() | Read CommentRanges to save with this document revision; throws once the editor is destroyed |
api.getSnapshot() | Read stable thread IDs, visible IDs, draft IDs, pending input, and issues |
api.discardOrphan(id) | Remove a saved range with no loaded thread; return 'discarded' or 'not-orphan' |
api.attachment(id) | Read CommentAttachment in the calling view, or null when the thread is absent |
api.idsAt(location) | Read unresolved IDs overlapping a location in the calling view, in record order. A location without a root is in the view's root |
api.setActive(ids) | Select an ordered group; use [] to clear it |
api.subscribeAttachments(listener) | Observe attachment mapping and projection changes in the calling view |
api.subscribeRanges(listener) | Observe a thread gaining, losing or replacing its saved range |
| Method | Purpose |
|---|---|
api.begin(range?) | Capture input in the calling view; a caret expands to its text block |
api.pendingRange() | Read the pending input's mapped range in the calling view |
api.cancel() | Close the pending composer and release its range. A create already sent from it still finishes |
api.create(body) | Publish the pending thread; await CommentMutationResult<string> |
api.createThread(input) | Publish a range or authored-change thread; await CommentMutationResult<string> |
api.reply(id, body, options?) | Append a message to an unresolved thread; { data } sets the new message's app data |
api.edit(id, messageId, body) | Edit a message under adapter authorization |
api.removeMessage(id, messageId) | Remove a message; remove its thread when no messages remain |
api.removeThread(id) | Delete a thread under adapter authorization |
api.setData(id, data, options?) | Replace a published thread's app data, or a message's with { messageId }; null removes it |
api.resolve(id) | Record canonical resolution actor and time |
api.reopen(id) | Clear resolution metadata |
api.publishDraft(id) | Commit a local draft through the mutation adapter |
api.createDraft(input) | Create a local unpublished draft; synchronously return string or null |
api.discardDraft(id) | Remove a local unpublished draft; synchronously return boolean |
createThread and createDraft accept CreateCommentThreadInput:
import type { Range, Value } from "platejs";
import type { CommentData } from "platejs/comments";
export type CreateCommentThreadInput = Readonly<{
body: Value;
data?: CommentData;
excerpt?: string;
id?: string;
target:
| Readonly<{ range: Range; type: 'range' }>
| Readonly<{ id: string; type: 'change' }>;
}>;import type { Range, Value } from "platejs";
import type { CommentData } from "platejs/comments";
export type CreateCommentThreadInput = Readonly<{
body: Value;
data?: CommentData;
excerpt?: string;
id?: string;
target:
| Readonly<{ range: Range; type: 'range' }>
| Readonly<{ id: string; type: 'change' }>;
}>;CommentData is a JSON object of CommentDataValue values: strings, finite numbers, booleans, null, arrays and nested objects. Creation requires a current user and a nonempty body. Range creation requires a noncollapsed range within one root. Comments supplies actors and timestamps, or accepts canonical values from the adapter.
Pass ranges from the calling view to begin, createThread, and createDraft. A range without a root is in that view's root, and the page's view also takes a range that names a note's root, as ranges() returns it. Their anchors capture that view's coordinates. Read pendingRange() and attachment(id) through the view that will consume them rather than reusing coordinates from another projection.
create and createThread return Promise<CommentMutationResult<string>>. All other durable methods return Promise<CommentMutationResult<undefined>>. begin, cancel, createDraft, and discardDraft stay local.
export type CommentMutationResult<T = undefined> =
| Readonly<{ status: 'applied'; value: T }>
| Readonly<{ status: 'invalid' }>
| Readonly<{ code?: string; status: 'rejected' }>
| Readonly<{ status: 'stale' }>;export type CommentMutationResult<T = undefined> =
| Readonly<{ status: 'applied'; value: T }>
| Readonly<{ status: 'invalid' }>
| Readonly<{ code?: string; status: 'rejected' }>
| Readonly<{ status: 'stale' }>;Await the result before clearing input or updating selection:
const result = await comments.create(body);
if (result.status === "applied") {
comments.setActive([result.value]);
}const result = await comments.create(body);
if (result.status === "applied") {
comments.setActive([result.value]);
}Handle invalid, rejected, stale, and thrown errors without discarding input. The AI integration publishes completed generated comments as ordinary threads without an approval prompt; local draft operations do not require a separate approval step.
subscribeThread(id, listener) observes one shared semantic record. subscribeThreads(listener) reports { ids } for semantic record changes only. Document edits that map attachments and view projection changes do not rewrite threads or wake semantic subscribers.
Use subscribeAttachments(listener) through the exact view's API for its placement changes. Decorations read and observe that same view. Switching another view's projection does not switch this subscription's view. Unsubscribing releases the view observation without releasing shared conversation targets.
subscribeVisibleThreadIds, subscribeDraftThreadIds, and subscribePending observe their respective snapshots. subscribeRanges calls its listener when a thread ID enters or leaves ranges(), when an ID's saved range is replaced by another, such as a retried create on other words, and when the orphans in issues change. A create or draft publish wakes it when submitted, before mutate settles; a rejection, a removal, discardOrphan and replace wake it too. Document mapping never wakes it. Each method returns an unsubscribe function.
A listener runs after its action's outcome is decided, except a subscribeRanges listener that a create or draft publish wakes, which runs before mutate. The action then checks again: when that listener destroyed the editor or retired the thread, mutate is never called and the action answers stale, and request.range is read after the listener, so an edit it made moves the range with the words. Any listener may throw or call any action. A synchronous throw goes to the editor's lifecycleErrorSink, later listeners still run, and the action still answers what landed. A notification means "read again", because a nested action can already have moved past it, so read getThread, getSnapshot and attachment for current state. An attachment or decoration listener that a Comments action wakes runs once every view has refreshed, so each view gives it the same locations. A listener added during a notification first runs on the next one, and a listener removed during it is skipped.
CommentKit from the copied comment item configures highlight styling. DiscussionKit adds block buttons and the floating thread view. Use the exported CommentThreadCard and CommentComposer to build a custom thread layout.
onSubmit(body) returns Promise<CommentMutationResult<string | undefined>>. Return the awaited durable action's result; the composer clears input only for status: 'applied'. It preserves rich input while saving and blocks duplicate submissions. Failed actions retain the draft and display a retry message.
'use client';
import {
CheckIcon,
MessageSquareTextIcon,
MessagesSquareIcon,
PencilLineIcon,
XIcon,
} from 'lucide-react';
import {
ElementApi,
type NodeKey,
type Path,
PathApi,
type Point,
type Range,
RangeApi,
} from 'platejs';
import type {
AuthoredChange,
AuthoredChangeGroup,
AuthoredChangePart,
AuthoredGroupDetails,
AuthoredGroupPart,
AuthoredResult,
} from 'platejs/authored';
import { AuthoredPlugin } from 'platejs/authored';
import { CommentsPlugin } from 'platejs/comments/react';
import {
type EditableSiblingProps,
type RenderNodeWrapperDescriptor,
type RenderNodeWrapperProps,
type WrapRootProps,
useEditor,
useEditorRootElement,
useEditorSelector,
useEditorViewState,
useModelEditor,
usePath,
usePluginStore,
} from 'platejs/react';
import {
SuggestionPlugin,
useActiveSuggestion,
useSuggestionGroups,
} from 'platejs/suggestion/react';
import {
BaseTableCellPlugin,
BaseTablePlugin,
BaseTableRowPlugin,
} from 'platejs/table';
import * as React from 'react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import {
CommentComposer,
CommentThreadCard,
formatCommentDate,
useCommentUser,
CommentKit,
usePendingComment,
useVisibleCommentThreadIds,
} from '@/components/editor/comment';
import {
FloatingPopover,
FloatingPopoverAnchor,
FloatingPopoverContent,
} from '@/components/editor/floating-popover';
import { useVisibleAnchor } from '@/hooks/use-visible-anchor';
type RuntimeEditor = ReturnType<typeof useEditor>;
type DiscussionItem =
| Readonly<{
blockKeys: readonly NodeKey[];
createdAt: Date;
id: string;
kind: 'comment';
}>
| Readonly<{
createdAt: Date;
group: AuthoredChangeGroup;
id: string;
kind: 'suggestion';
threadIds: readonly string[];
}>;
type CommentItem = Extract<DiscussionItem, { kind: 'comment' }>;
type SuggestionItem = Extract<DiscussionItem, { kind: 'suggestion' }>;
type CommentAnchor = Readonly<{ changeId: string | null; range: Range }>;
type DiscussionBlockSnapshot = Readonly<{
active: boolean;
comments: number;
}>;
type DiscussionTarget = Readonly<{
anchor: HTMLElement;
blockKey: NodeKey;
}>;
type DiscussionSnapshot = Readonly<{
lastTrigger: NodeKey | null;
revision: number;
target: DiscussionTarget | null;
}>;
const EMPTY_BLOCK_SNAPSHOT: DiscussionBlockSnapshot = Object.freeze({
active: false,
comments: 0,
});
const EMPTY_DISCUSSION_SNAPSHOT: DiscussionSnapshot = Object.freeze({
lastTrigger: null,
revision: 0,
target: null,
});
const DISCUSSION_PAGE_SIZE = 20;
const sortDiscussionItems = (items: readonly DiscussionItem[]) =>
items.toSorted(
(left, right) => left.createdAt.getTime() - right.createdAt.getTime()
);
const NO_GROUPS: readonly AuthoredChangeGroup[] = Object.freeze([]);
const NO_THREADS: ReadonlyMap<string, readonly string[]> = new Map();
const sameGroups = (
left: readonly AuthoredChangeGroup[],
right: readonly AuthoredChangeGroup[]
) =>
left.length === right.length &&
left.every(
(group, index) =>
group.id === right[index]?.id && group.revision === right[index].revision
);
const sameCommentAnchor = (
left: CommentAnchor | null,
right: CommentAnchor | null
) =>
left?.changeId === right?.changeId &&
RangeApi.equals(left?.range ?? null, right?.range ?? null);
const suggestionItemOf = (
editor: RuntimeEditor,
threads: ReadonlyMap<string, readonly string[]>,
group: AuthoredChangeGroup
): SuggestionItem => {
const { read } = editor.plugin(AuthoredPlugin);
return {
createdAt: new Date(group.createdAt),
group,
id: group.id,
kind: 'suggestion',
threadIds: [...threads].flatMap(([changeId, ids]) =>
read.groupOf(changeId)?.id === group.id ? ids : []
),
};
};
const blockThreadCount = (
editor: RuntimeEditor,
threads: ReadonlyMap<string, readonly string[]>,
blockKey: NodeKey
) => {
const { read } = editor.plugin(AuthoredPlugin);
let count = 0;
for (let cursor: string | undefined; threads.size > 0;) {
const page = read.changes({ at: blockKey, cursor, limit: 200 });
for (const change of page.items) {
count += threads.get(change.id)?.length ?? 0;
}
if (!page.cursor) break;
({ cursor } = page);
}
return count;
};
type RootTops = ReadonlyMap<string, number | undefined>;
const rootTops = (editor: RuntimeEditor): RootTops =>
new Map(editor.read.roots().map(({ root, top }) => [root, top?.[0]]));
const pageIndexOf = (tops: RootTops, point: Point) =>
point.root === undefined ? (point.path[0] ?? 0) : tops.get(point.root);
const discussionBlocks = (
editor: RuntimeEditor,
tops: RootTops,
range: Range
) => {
const [start, end] = RangeApi.edges(range);
const first = pageIndexOf(tops, start);
const last = pageIndexOf(tops, end);
if (first === undefined || last === undefined) return [];
return Array.from({ length: last - first + 1 }).flatMap(
(_, offset) => editor.key([first + offset]) ?? []
);
};
const sameBlockSnapshot = (
left: DiscussionBlockSnapshot | undefined,
right: DiscussionBlockSnapshot
) => left?.active === right.active && left.comments === right.comments;
const createDiscussionStore = () => {
const listeners = new Set<() => void>();
const blockListeners = new Map<NodeKey, Set<() => void>>();
const blockTriggers = new Map<NodeKey, HTMLElement>();
const blockSnapshots = new Map<NodeKey, DiscussionBlockSnapshot>();
const threadListeners = new Set<() => void>();
let commentBlocks = new Map<NodeKey, readonly CommentItem[]>();
let commentsById = new Map<string, CommentItem>();
let notifyQueued = false;
let prepareSelection: (() => void) | null = null;
let suggestionThreads = NO_THREADS;
let snapshot = EMPTY_DISCUSSION_SNAPSHOT;
const notifyBlocks = (keys: ReadonlySet<NodeKey>) => {
keys.forEach((key) => {
blockListeners.get(key)?.forEach((listener) => {
listener();
});
});
};
const notify = () => {
if (notifyQueued) return;
notifyQueued = true;
queueMicrotask(() => {
notifyQueued = false;
listeners.forEach((listener) => {
listener();
});
});
};
const readBlockSnapshot = (blockKey: NodeKey): DiscussionBlockSnapshot => {
const active = snapshot.target?.blockKey === blockKey;
const comments = commentBlocks.get(blockKey)?.length ?? 0;
return active || comments > 0 ? { active, comments } : EMPTY_BLOCK_SNAPSHOT;
};
const publishBlockSnapshots = (keys: ReadonlySet<NodeKey>) => {
const changedKeys = new Set<NodeKey>();
keys.forEach((key) => {
const previous = blockSnapshots.get(key);
const next = readBlockSnapshot(key);
if (next === EMPTY_BLOCK_SNAPSHOT) blockSnapshots.delete(key);
else if (previous && sameBlockSnapshot(previous, next)) return;
else blockSnapshots.set(key, next);
if (previous !== next) changedKeys.add(key);
});
notifyBlocks(changedKeys);
};
const publishTarget = (target: DiscussionTarget | null) => {
if (snapshot.target === target) return;
const keys = new Set<NodeKey>();
if (snapshot.target) keys.add(snapshot.target.blockKey);
if (target) keys.add(target.blockKey);
snapshot = { ...snapshot, target };
listeners.forEach((listener) => {
listener();
});
publishBlockSnapshots(keys);
};
return {
clearTarget() {
publishTarget(null);
},
forgetTrigger() {
if (!snapshot.lastTrigger) return;
snapshot = { ...snapshot, lastTrigger: null };
listeners.forEach((listener) => {
listener();
});
},
getBlockSnapshot(key: NodeKey) {
return blockSnapshots.get(key) ?? EMPTY_BLOCK_SNAPSHOT;
},
getBlockTrigger(key: NodeKey) {
return blockTriggers.get(key) ?? null;
},
getComment(id: string) {
return commentsById.get(id) ?? null;
},
getComments(blockKey: NodeKey) {
return commentBlocks.get(blockKey) ?? [];
},
getSnapshot: () => snapshot,
getThreads: () => suggestionThreads,
selectBlock(blockKey: NodeKey, anchor: HTMLElement) {
if (!prepareSelection) return;
prepareSelection();
snapshot = { ...snapshot, lastTrigger: blockKey };
publishTarget(
snapshot.target?.blockKey === blockKey ? null : { anchor, blockKey }
);
},
subscribe: (listener: () => void) => {
listeners.add(listener);
return () => listeners.delete(listener);
},
subscribeBlock(key: NodeKey, listener: () => void) {
const keyListeners = blockListeners.get(key) ?? new Set<() => void>();
keyListeners.add(listener);
blockListeners.set(key, keyListeners);
return () => {
keyListeners.delete(listener);
if (keyListeners.size === 0) blockListeners.delete(key);
};
},
subscribeThreads: (listener: () => void) => {
threadListeners.add(listener);
return () => threadListeners.delete(listener);
},
setPrepareSelection(next: typeof prepareSelection) {
prepareSelection = next;
},
setBlockTrigger(key: NodeKey, element: HTMLElement | null) {
if (element) {
blockTriggers.set(key, element);
} else {
blockTriggers.delete(key);
}
},
update(
items: readonly CommentItem[],
threads: ReadonlyMap<string, readonly string[]>
) {
const previousKeys = new Set(commentBlocks.keys());
const nextBlocks = new Map<NodeKey, CommentItem[]>();
commentsById = new Map(items.map((item) => [item.id, item]));
items.forEach((item) => {
item.blockKeys.forEach((blockKey) => {
const block = nextBlocks.get(blockKey);
if (block) block.push(item);
else nextBlocks.set(blockKey, [item]);
});
});
commentBlocks = nextBlocks;
suggestionThreads = new Map(threads);
threadListeners.forEach((listener) => {
listener();
});
publishBlockSnapshots(
new Set([...previousKeys, ...commentBlocks.keys()])
);
snapshot = { ...snapshot, revision: snapshot.revision + 1 };
notify();
},
};
};
type DiscussionStore = ReturnType<typeof createDiscussionStore>;
const DiscussionContext = React.createContext<DiscussionStore | null>(null);
const SuggestionsInstalledContext = React.createContext(false);
const useDiscussionStore = () => {
const store = React.useContext(DiscussionContext);
if (!store) throw new Error('Discussion requires DiscussionSlots.');
return store;
};
const useDiscussionController = () => {
const editor = useEditor();
const { api: comments } = useEditor().plugin(CommentsPlugin);
const visibleThreadIds = useVisibleCommentThreadIds();
const [store] = React.useState(createDiscussionStore);
React.useEffect(() => {
const { api } = editor.plugin(CommentsPlugin);
const locate = (
id: string,
thread: ReturnType<typeof comments.getThread>,
tops: RootTops
) => {
if (!thread || thread.resolution) return null;
const attachment = api.attachment(id);
if (thread.target.type === 'change') return null;
if (attachment?.type !== 'range' || attachment.status !== 'attached') {
return null;
}
return {
blockKeys: discussionBlocks(editor, tops, attachment.range),
createdAt: new Date(thread.createdAt),
id,
kind: 'comment' as const,
};
};
const publish = () => {
const suggestionThreads = new Map<string, string[]>();
const commentItems: CommentItem[] = [];
const visible = new Set(visibleThreadIds);
const tops = rootTops(editor);
comments.getThreads().forEach((thread) => {
if (thread.resolution) return;
if (thread.target.type === 'change') {
const ids = suggestionThreads.get(thread.target.id) ?? [];
ids.push(thread.id);
suggestionThreads.set(thread.target.id, ids);
return;
}
if (!visible.has(thread.id)) return;
const item = locate(thread.id, thread, tops);
if (item) commentItems.push(item);
});
store.update(commentItems, suggestionThreads);
};
const unsubscribeAttachments = api.subscribeAttachments(publish);
const unsubscribeThreads = api.subscribeThreads(publish);
publish();
return () => {
unsubscribeAttachments();
unsubscribeThreads();
};
}, [comments, editor, store, visibleThreadIds]);
return store;
};
function DiscussionRoot({ children }: WrapRootProps) {
const store = useDiscussionController();
const suggestions = useEditorSelector(
(current) =>
current.plugin(AuthoredPlugin).installed &&
current.plugin(SuggestionPlugin).installed
);
return (
<DiscussionContext value={store}>
<SuggestionsInstalledContext value={suggestions}>
{children}
</SuggestionsInstalledContext>
</DiscussionContext>
);
}
function DiscussionCard({
item,
onDecisionApplied,
}: {
item: DiscussionItem;
onDecisionApplied: () => void;
}) {
return item.kind === 'comment' ? (
<CommentThreadCard id={item.id} />
) : (
<SuggestionDiscussionCard
createdAt={item.createdAt}
group={item.group}
onDecisionApplied={onDecisionApplied}
threadIds={item.threadIds}
/>
);
}
const readContentText = (value: unknown): string => {
if (!value || typeof value !== 'object') return '';
const node = value as { children?: unknown; text?: unknown };
if (typeof node.text === 'string') return node.text;
if (!Array.isArray(node.children)) return '';
return node.children.map(readContentText).join('');
};
const contentText = (
content: Extract<AuthoredGroupPart, { kind: 'content' }>['after']
) => {
if (!content) return '';
// Only a line break between two blocks; inline content runs on.
return content.content
.map((node, index) =>
index > 0 &&
ElementApi.isElement(node) &&
ElementApi.isElement(content.content[index - 1])
? `\n${readContentText(node)}`
: readContentText(node)
)
.join('');
};
const textPreview = (text: string) => {
const preview = text.trim();
return preview.length > 80 ? `${preview.slice(0, 77)}…` : preview;
};
const contentPreview = (
content: Extract<AuthoredGroupPart, { kind: 'content' }>['after']
) => textPreview(contentText(content));
const formatPropertyName = (key: string) =>
`${key[0]?.toUpperCase() ?? ''}${key.slice(1)}`
.replaceAll(/[_-]+/g, ' ')
.replaceAll(/([a-z0-9])([A-Z])/g, '$1 $2');
const formatPropertyValue = (value: unknown) => {
if (value === undefined) return 'none';
if (typeof value === 'boolean') return value ? 'on' : 'off';
if (typeof value === 'string' || typeof value === 'number') {
return String(value);
}
return JSON.stringify(value);
};
const describeSuggestionPart = (part: AuthoredGroupPart): readonly string[] => {
const { kind } = part;
switch (kind) {
case 'boundary': {
return [
part.action === 'split'
? 'Add paragraph break'
: 'Delete paragraph break',
];
}
case 'content': {
const before = contentPreview(part.before);
const after = contentPreview(part.after);
const { action } = part;
switch (action) {
case 'delete': {
return [before ? `Delete “${before}”` : 'Delete content'];
}
case 'insert': {
return [after ? `Add “${after}”` : 'Add content'];
}
case 'replace': {
return [
before || after
? `Replace ${before ? `“${before}”` : 'content'} with ${
after ? `“${after}”` : 'content'
}`
: 'Replace content',
];
}
default: {
const unsupportedAction: never = action;
throw new Error(
`Unsupported content action: ${String(unsupportedAction)}`
);
}
}
}
case 'properties': {
const keys = [
...new Set([...Object.keys(part.before), ...Object.keys(part.after)]),
].sort();
return keys.map(
(key) =>
`${formatPropertyName(key)}: ${formatPropertyValue(
part.before[key]
)} → ${formatPropertyValue(part.after[key])}`
);
}
case 'enclosure': {
return [
`${part.action === 'wrap' ? 'Wrap in' : 'Unwrap'} ${formatPropertyName(
part.type
)}`,
];
}
default: {
const unsupportedKind: never = kind;
throw new Error(
`Unsupported suggestion part: ${String(unsupportedKind)}`
);
}
}
};
const describeSuggestion = (details: AuthoredGroupDetails | null) => {
const descriptions = (details?.parts ?? []).flatMap(describeSuggestionPart);
if (descriptions.length > 0) return descriptions;
return [
{
delete: 'Delete content',
format: 'Change formatting',
insert: 'Add content',
mixed: 'Edit content',
structure: 'Change structure',
}[details?.changes[0]?.kind ?? 'mixed'],
];
};
const partPaths = (part: AuthoredChangePart): readonly Path[] =>
part.kind === 'boundary'
? [part.at.path]
: part.kind === 'content'
? [part.range.anchor.path, part.range.focus.path]
: [part.path];
const changeName = (
kind: 'delete' | 'insert',
noun: 'column' | 'row' | 'table',
count: number
) =>
`${kind === 'insert' ? 'Add' : 'Delete'} ${
count === 1 ? noun : `${count} ${noun}s`
}`;
const tableChangeName = (
current: RuntimeEditor,
{ id: changeId, ranges }: AuthoredChange
) => {
const table = current.plugin(BaseTablePlugin);
const viewRoot = current.read.view.root();
const inView = ({ root }: Point) => root === viewRoot;
if (
!table.installed ||
!ranges.every(({ anchor, focus }) => inView(anchor) && inView(focus))
) {
return null;
}
const path = ranges[0]?.anchor.path ?? [];
const tables = path.flatMap((_, index) => {
const tablePath = path.slice(0, index + 1);
const node = current.read.nodes.get(tablePath)?.[0];
return ElementApi.isElement(node) && node.type === table.schema.type
? [{ node, tablePath }]
: [];
});
const { read } = current.plugin(AuthoredPlugin);
const details = tables.length > 0 ? read.details(changeId) : null;
if (!details) return null;
const rowType = current.plugin(BaseTableRowPlugin).schema.type;
const cellType = current.plugin(BaseTableCellPlugin).schema.type;
const kindOf = (node: unknown) =>
read
.reviewOf(node)
.marks.flatMap((mark) =>
mark.change === changeId &&
(mark.kind === 'delete' || mark.kind === 'insert')
? [mark.kind]
: []
)[0] ?? null;
const markedAt = (depth: number) => {
const node =
path.length >= depth
? current.read.nodes.get(path.slice(0, depth))?.[0]
: undefined;
return node ? kindOf(node) : null;
};
const covers = (tablePath: Path, members: readonly Path[], column = false) =>
details.parts.every((part) =>
part.kind === 'properties' && PathApi.equals(part.path, tablePath)
? column &&
Object.keys({ ...part.before, ...part.after }).every(
(key) => key === 'columnWidths'
)
: partPaths(part).every((partPath) =>
members.some((member) => PathApi.isCommon(member, partPath))
)
);
for (const { node, tablePath } of tables) {
const tableKind = kindOf(node);
// A column change's width write on the table can be its first range.
if (
!read.reviewOf(node).marks.some((mark) => mark.change === changeId) &&
!markedAt(tablePath.length + 1) &&
!markedAt(tablePath.length + 2)
) {
continue;
}
if (tableKind) {
return covers(tablePath, [tablePath])
? changeName(tableKind, 'table', 1)
: null;
}
const rows = node.children.flatMap((row, index) =>
ElementApi.isElement(row) && row.type === rowType
? [{ path: [...tablePath, index], row }]
: []
);
if (
rows.some(({ row }) =>
row.children.some(
(cell) =>
ElementApi.isElement(cell) &&
[cell.colSpan, cell.rowSpan].some(
(span) => typeof span === 'number' && span > 1
)
)
)
) {
return null;
}
const markedRows = rows.flatMap((entry) => {
const kind = kindOf(entry.row);
return kind ? [{ kind, path: entry.path }] : [];
});
if (markedRows.length > 0) {
const { kind } = markedRows[0];
return markedRows.every((row) => row.kind === kind) &&
covers(
tablePath,
markedRows.map((row) => row.path)
)
? changeName(kind, 'row', markedRows.length)
: null;
}
const markedCells = rows.map((entry) =>
entry.row.children.flatMap((cell, index) => {
const kind =
ElementApi.isElement(cell) && cell.type === cellType
? kindOf(cell)
: null;
return kind ? [{ index, kind, path: [...entry.path, index] }] : [];
})
);
const cells = markedCells.flat();
if (cells.length === 0) continue;
const { kind } = cells[0];
const columns = markedCells[0].map((cell) => cell.index);
const wholeColumns = markedCells.every(
(rowCells) =>
rowCells.length === columns.length &&
rowCells.every((cell, index) => cell.index === columns[index])
);
return wholeColumns &&
cells.every((cell) => cell.kind === kind) &&
covers(
tablePath,
cells.map((cell) => cell.path),
true
)
? changeName(kind, 'column', columns.length)
: null;
}
return null;
};
const everyTableChangeName = (
current: RuntimeEditor,
groupId: string,
details: AuthoredGroupDetails | null,
shown: number
) => {
const changes =
details?.changes.length === shown
? (current.plugin(AuthoredPlugin).read.groupDetails(groupId)?.changes ??
[])
: (details?.changes ?? []);
const names = changes.map((change) => tableChangeName(current, change));
return names.length > 0 && names.every((name) => name !== null)
? names.slice(0, shown)
: null;
};
const sameLines = (left: readonly string[], right: readonly string[]) =>
left.length === right.length &&
left.every((line, index) => line === right[index]);
function SuggestionDiscussionCard({
createdAt,
group,
onDecisionApplied,
threadIds,
}: {
createdAt: Date;
group: AuthoredChangeGroup;
onDecisionApplied: () => void;
threadIds: readonly string[];
}) {
const editor = useEditor();
const { api: comments } = useEditor().plugin(CommentsPlugin);
const readOnly = useEditorViewState(editor, (view) => view.isReadOnly());
const user = useCommentUser(group.authorId);
const groupKey = `${group.id}:${group.revision}`;
const [outcomeState, setOutcomeState] = React.useState<{
groupKey: string;
result: AuthoredResult;
} | null>(null);
const outcome =
outcomeState?.groupKey === groupKey ? outcomeState.result : null;
const [shownState, setShownState] = React.useState({
count: DISCUSSION_PAGE_SIZE,
groupId: group.id,
});
const shown =
shownState.groupId === group.id ? shownState.count : DISCUSSION_PAGE_SIZE;
const authored = editor.plugin(AuthoredPlugin);
const readLines = React.useCallback(
(current: RuntimeEditor) => {
const { read } = current.plugin(AuthoredPlugin);
const details = read.groupDetails(group.id, { limit: shown });
return (
everyTableChangeName(current, group.id, details, shown) ??
describeSuggestion(details)
);
},
[group.id, shown]
);
const descriptions = useEditorSelector(readLines, {
equalityFn: sameLines,
shouldUpdate: (change) => !change || change.changed.hasAny('document'),
});
const setOutcome = (result: AuthoredResult) =>
setOutcomeState({ groupKey, result });
const decide = (
action: 'accept' | 'reject',
related: readonly string[] = []
) => {
const relatedChanges = related.flatMap((id) => {
const change = authored.read.change(id);
return change ? [change] : [];
});
const result = authored.update.decide([
{ action, groups: [group] },
...(relatedChanges.length > 0
? [{ action, changes: relatedChanges }]
: []),
]);
if (result.status === 'applied' || result.status === 'unchanged') {
onDecisionApplied();
return;
}
setOutcome(result);
};
const relatedIds = outcome?.status === 'blocked' ? outcome.with : [];
const outcomeMessage = (() => {
if (!outcome) return null;
const { status } = outcome;
switch (status) {
case 'applied': {
return null;
}
case 'unchanged': {
return null;
}
case 'blocked': {
return `This decision also affects ${
relatedIds.length
} related suggestion${relatedIds.length === 1 ? '' : 's'}.`;
}
case 'invalid': {
return 'This decision would leave the document invalid.';
}
case 'stale': {
return 'This suggestion changed. Review it again before deciding.';
}
default: {
const unsupportedStatus: never = status;
throw new Error(
`Unsupported authored result: ${String(unsupportedStatus)}`
);
}
}
})();
return (
<article
className="relative flex flex-col focus-within:[&>header>.editor-suggestion-actions]:pointer-events-auto focus-within:[&>header>.editor-suggestion-actions]:opacity-100 hover:[&>header>.editor-suggestion-actions]:pointer-events-auto hover:[&>header>.editor-suggestion-actions]:opacity-100"
data-suggestion-review={group.id}
>
<header className="relative flex items-center">
<Avatar className="size-5">
<AvatarImage alt={user?.name} src={user?.avatarUrl} />
<AvatarFallback>{user?.name?.[0] ?? '?'}</AvatarFallback>
</Avatar>
<span className="mx-2 text-sm leading-none font-semibold">
{user?.name ?? group.authorId}
</span>
<span className="text-xs leading-none text-muted-foreground/80">
{formatCommentDate(createdAt)}
</span>
<span className="editor-suggestion-actions pointer-events-none absolute end-0 top-0 flex gap-2 opacity-0 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100">
<Button
aria-label="Accept suggestion"
className="size-6 p-1 text-muted-foreground"
disabled={readOnly}
onClick={() => decide('accept')}
variant="ghost"
>
<CheckIcon className="size-4" />
</Button>
<Button
aria-label="Reject suggestion"
className="size-6 p-1 text-muted-foreground"
disabled={readOnly}
onClick={() => decide('reject')}
variant="ghost"
>
<XIcon className="size-4" />
</Button>
</span>
</header>
<div className="relative mt-1 mb-4 flex flex-col gap-2 ps-[32px] text-sm">
{descriptions.map((description, index) => (
<p className="text-muted-foreground" key={`${index}:${description}`}>
{description}
</p>
))}
{group.changeCount > shown && (
<Button
className="self-start"
onClick={() =>
setShownState({
count: shown + DISCUSSION_PAGE_SIZE,
groupId: group.id,
})
}
size="sm"
variant="ghost"
>
Show {Math.min(DISCUSSION_PAGE_SIZE, group.changeCount - shown)}{' '}
more changes
</Button>
)}
{outcomeMessage && (
<div className="flex flex-col items-start gap-2" role="alert">
<p>{outcomeMessage}</p>
{outcome?.status === 'blocked' && relatedIds.length > 0 && (
<div className="flex gap-2">
<Button
disabled={readOnly}
onClick={() => decide('accept', relatedIds)}
size="sm"
variant="outline"
>
Accept related
</Button>
<Button
disabled={readOnly}
onClick={() => decide('reject', relatedIds)}
size="sm"
variant="outline"
>
Reject related
</Button>
</div>
)}
</div>
)}
</div>
{threadIds.map((id) => (
<CommentThreadCard id={id} key={id} showReply={false} />
))}
<CommentComposer
ariaLabel="Comment on suggestion"
onSubmit={(body) =>
comments.createThread({
body,
excerpt: descriptions[0] ?? 'Suggestion',
target: { id: group.id, type: 'change' },
})
}
placeholder="Reply..."
/>
</article>
);
}
function NewComment({
autoFocus,
focusEditor,
}: {
autoFocus: boolean;
focusEditor: () => void;
}) {
const { api: comments } = useEditor().plugin(CommentsPlugin);
return (
<CommentComposer
ariaLabel="New comment"
autoFocus={autoFocus}
onCancel={() => {
comments.cancel();
focusEditor();
}}
onSubmit={async (body) => {
const result = await comments.create(body);
if (result.status === 'applied') comments.setActive([result.value]);
return result;
}}
placeholder="Add a comment"
/>
);
}
function DiscussionBlock({
children,
editor,
}: RenderNodeWrapperProps<typeof CommentsPlugin>) {
const path = usePath();
const blockKey = editor.key(path);
const suggestions = React.useContext(SuggestionsInstalledContext);
if (!blockKey) return children;
return suggestions ? (
<SuggestionDiscussionBlock blockKey={blockKey}>
{children}
</SuggestionDiscussionBlock>
) : (
<DiscussionBlockContent blockKey={blockKey} cards={0} threads={0}>
{children}
</DiscussionBlockContent>
);
}
function SuggestionDiscussionBlock({
blockKey,
children,
}: React.PropsWithChildren<{ blockKey: NodeKey }>) {
const editor = useEditor();
const store = useDiscussionStore();
const cards = useSuggestionGroups(blockKey);
const threads = React.useSyncExternalStore(
store.subscribeThreads,
store.getThreads,
store.getThreads
);
return (
<DiscussionBlockContent
blockKey={blockKey}
cards={cards.length}
threads={
cards.length > 0 ? blockThreadCount(editor, threads, blockKey) : 0
}
>
{children}
</DiscussionBlockContent>
);
}
function DiscussionBlockContent({
blockKey,
cards,
children,
threads,
}: React.PropsWithChildren<{
blockKey: NodeKey;
cards: number;
threads: number;
}>) {
const store = useDiscussionStore();
const subscribe = React.useCallback(
(listener: () => void) => store.subscribeBlock(blockKey, listener),
[blockKey, store]
);
const block = React.useSyncExternalStore(
subscribe,
() => store.getBlockSnapshot(blockKey),
() => store.getBlockSnapshot(blockKey)
);
const setTriggerRef = React.useCallback(
(trigger: HTMLButtonElement | null) => {
store.setBlockTrigger(blockKey, trigger);
},
[blockKey, store]
);
const isActive = block.active;
const hasComments = block.comments > 0 || threads > 0;
const totalCount = block.comments + cards + threads;
const icon =
hasComments && cards > 0 ? (
<MessagesSquareIcon aria-hidden="true" className="size-4 shrink-0" />
) : cards > 0 ? (
<PencilLineIcon aria-hidden="true" className="size-4 shrink-0" />
) : (
<MessageSquareTextIcon aria-hidden="true" className="size-4 shrink-0" />
);
const itemLabel = totalCount === 1 ? 'item' : 'items';
return (
<div className="flex w-full justify-between">
<div className="w-full min-w-0">{children}</div>
<div
className="relative start-0 size-0 select-none"
contentEditable={false}
>
{totalCount > 0 && (
<Button
aria-expanded={isActive}
aria-label={`${isActive ? 'Close' : 'Open'} ${
totalCount
} discussion ${itemLabel} for this block`}
className="ms-1 mt-1 flex h-6 gap-1 !px-1.5 py-0 text-muted-foreground/80 hover:text-muted-foreground/80 data-[active=true]:bg-muted"
contentEditable={false}
data-active={isActive}
data-discussion-block-trigger
data-editor-keep-selection-visible
onClick={(event) => {
event.stopPropagation();
store.selectBlock(blockKey, event.currentTarget);
}}
onMouseDown={(event) => event.preventDefault()}
ref={setTriggerRef}
type="button"
variant="ghost"
>
{icon}
<span
aria-hidden="true"
className="text-xs font-semibold after:content-[attr(data-count)]"
data-count={totalCount}
/>
</Button>
)}
</div>
</div>
);
}
const DiscussionBlockSlot: RenderNodeWrapperDescriptor<typeof CommentsPlugin> =
{
component: DiscussionBlock,
match: ({ renderPath }) => renderPath.length === 1,
};
function DiscussionPopover({
activeSuggestionId,
editableRef,
setActiveSuggestionId,
snapshot,
}: EditableSiblingProps & {
activeSuggestionId: string | null;
setActiveSuggestionId?: (id: string | null) => void;
snapshot: DiscussionSnapshot;
}) {
const editor = useEditor();
const model = useModelEditor();
const rootElement = useEditorRootElement(editor);
const store = useDiscussionStore();
const popoverRef = React.useRef<HTMLDivElement>(null);
const { api: comments } = useEditor().plugin(CommentsPlugin);
const pending = usePendingComment();
// React focus events bubble out of portals, so a menu opened from the
// popover counts as a control inside it.
const focusedControlRef = React.useRef<EventTarget | null>(null);
// Safari focuses the popover itself, not a pressed button, so a press holds
// the popover until the pointer is released.
const pressingRef = React.useRef(false);
const releasedPendingRef = React.useRef<typeof pending>(null);
const activeCommentIds = usePluginStore(CommentsPlugin, 'activeIds');
const activeOrder = new Map(activeCommentIds.map((id, index) => [id, index]));
const suggestions = React.useContext(SuggestionsInstalledContext);
const targetKey = snapshot.target?.blockKey ?? null;
const threads = React.useSyncExternalStore(
store.subscribeThreads,
store.getThreads,
store.getThreads
);
// An edit before a change can move its range and keep its revision, so the
// anchor reads each range through its own selector.
const commentAnchor = useEditorSelector(
(current) => {
const authored = current.plugin(AuthoredPlugin);
for (const id of activeCommentIds) {
const attachment = comments.attachment(id);
if (attachment?.type === 'range' && attachment.status === 'attached') {
return { changeId: null, range: attachment.range };
}
if (attachment?.type === 'change' && authored.installed) {
const range = authored.read.change(attachment.id)?.ranges[0];
if (range) return { changeId: attachment.id, range };
}
}
return null;
},
{ equalityFn: sameCommentAnchor }
);
const changeId = commentAnchor?.changeId ?? null;
// Open cards read their summaries after each commit, so the revision a
// decision sends stays current when another block changes the card. A
// thread opened alone, such as from a list, opens its change's card.
const activeGroups = useEditorSelector(
(current) => {
const id = activeSuggestionId ?? changeId;
const group =
suggestions && id
? current.plugin(AuthoredPlugin).read.groupOf(id)
: null;
return group ? [group] : NO_GROUPS;
},
{ equalityFn: sameGroups }
);
const activeGroupId = activeGroups[0]?.id;
const activeSuggestionRange = useEditorSelector(
(current) =>
activeGroupId
? (current.plugin(AuthoredPlugin).read.changes({
group: activeGroupId,
limit: 1,
}).items[0]?.ranges[0] ?? null)
: null,
{ equalityFn: RangeApi.equals }
);
const targetGroups = useEditorSelector(
(current) =>
suggestions && targetKey
? current.plugin(AuthoredPlugin).read.groups({ at: targetKey })
: NO_GROUPS,
{ equalityFn: sameGroups }
);
const activeItems: DiscussionItem[] = [
...activeCommentIds.flatMap((id) => {
const item = store.getComment(id);
return item ? [item] : [];
}),
...activeGroups.map((group) => suggestionItemOf(editor, threads, group)),
].toSorted(
(left, right) =>
(activeOrder.get(left.id) ?? activeCommentIds.length) -
(activeOrder.get(right.id) ?? activeCommentIds.length)
);
const targetItems = targetKey
? sortDiscussionItems([
...store.getComments(targetKey),
...targetGroups.map((group) =>
suggestionItemOf(editor, threads, group)
),
])
: [];
const target = !pending && activeItems.length === 0 ? snapshot.target : null;
const [pagination, setPagination] = React.useState<{
count: number;
targetKey: NodeKey | null;
}>({ count: DISCUSSION_PAGE_SIZE, targetKey });
const visibleCount =
pagination.targetKey === targetKey
? pagination.count
: DISCUSSION_PAGE_SIZE;
const shownItems =
activeItems.length > 0 ? activeItems : targetItems.slice(0, visibleCount);
const view = useEditorViewState(editor, () => {
const authored = editor.plugin(AuthoredPlugin);
const current = authored.installed ? authored.read.view() : null;
if (!current) return null;
return 'intent' in current ? current.intent : `preview:${current.preview}`;
});
const preview = view?.startsWith('preview:') ?? false;
const pendingRange = useEditorSelector(
() => (pending ? comments.pendingRange() : null),
{
equalityFn: RangeApi.equals,
shouldUpdate: (change) => !change || change.changed.hasAny('document'),
}
);
// A suggestion's ranges are places of the stored document, so a preview
// anchors on the block whose trigger was pressed last, and only while that
// block shows the open card.
const previewHidesRange =
preview &&
!pendingRange &&
(commentAnchor
? commentAnchor.changeId !== null
: Boolean(activeSuggestionRange));
const shownTrigger = useEditorSelector((current) => {
const key = snapshot.lastTrigger;
if (!previewHidesRange || !key) return null;
const { read } = current.plugin(AuthoredPlugin);
const openId = changeId ? read.groupOf(changeId)?.id : activeGroupId;
return read.groups({ at: key }).some(({ id }) => id === openId)
? key
: null;
});
// Editing and Proposed can give a block one key, and a pressed block
// belongs to the view it was pressed in.
React.useLayoutEffect(() => {
store.forgetTrigger();
}, [store, view]);
const anchorRange = previewHidesRange
? null
: (pendingRange ?? commentAnchor?.range ?? activeSuggestionRange ?? null);
const anchorRangeJson = anchorRange ? JSON.stringify(anchorRange) : null;
const focusEditor = () => {
const selection = model.read.selection();
const root = selection ? RangeApi.start(selection).root : undefined;
if (root === undefined || root === editor.read.view.root()) {
editableRef.current?.focus();
} else {
model.api.dom.focus();
}
};
const anchorRangeKey = useEditorSelector((current) => {
if (!anchorRange) return null;
const index = pageIndexOf(rootTops(current), RangeApi.start(anchorRange));
return index === undefined ? null : current.key([index]);
});
const anchorBlockKey = previewHidesRange ? shownTrigger : anchorRangeKey;
const targetElement = target?.anchor ?? null;
const measureAnchor = React.useMemo(() => {
if (targetElement) return () => [targetElement.getBoundingClientRect()];
const range = anchorRangeJson
? (JSON.parse(anchorRangeJson) as Range)
: null;
if (!range) {
if (!anchorBlockKey) return null;
return () => {
const block = editor.api.dom.resolveDOMNode(anchorBlockKey);
return block ? [block.getBoundingClientRect()] : [];
};
}
return () => {
const { root } = RangeApi.start(range);
const domRange = (
root === undefined || root === editor.read.view.root() ? editor : model
).api.dom.resolveDOMRange(range);
const lines = domRange
? Array.from(domRange.getClientRects()).filter(
({ height, width }) => height > 0 || width > 0
)
: [];
if (lines.length > 0) return lines.reverse();
const rangeRect = domRange?.getBoundingClientRect();
if (rangeRect && (rangeRect.height > 0 || rangeRect.width > 0)) {
return [rangeRect];
}
const trigger = anchorBlockKey
? store.getBlockTrigger(anchorBlockKey)
: null;
if (trigger) return [trigger.getBoundingClientRect()];
return rangeRect ? [rangeRect] : [];
};
}, [anchorBlockKey, anchorRangeJson, editor, model, store, targetElement]);
const { anchor: anchorElement, hidden } = useVisibleAnchor({
editableRef,
keepShown: () =>
pressingRef.current ||
focusedControlRef.current ===
editableRef.current?.ownerDocument.activeElement ||
(Boolean(pending) && releasedPendingRef.current !== pending),
measure: measureAnchor,
});
const open = Boolean(
anchorElement &&
(pending || activeItems.length > 0 || targetItems.length > 0)
);
const openRef = React.useRef(open);
const [placedPending, setPlacedPending] =
React.useState<typeof pending>(null);
const [composerMount, setComposerMount] = React.useState({
count: 0,
pending,
});
if (pending && composerMount.pending !== pending) {
setComposerMount({ count: composerMount.count + 1, pending });
}
React.useLayoutEffect(() => {
openRef.current = open;
}, [open]);
React.useEffect(() => {
if (
snapshot.target &&
(pending || activeItems.length > 0 || targetItems.length === 0)
) {
store.clearTarget();
}
}, [activeItems.length, pending, snapshot.target, store, targetItems.length]);
const editorDecidesOpen = !pending && activeItems.length > 0;
return (
<div data-discussion-root="">
<FloatingPopover
insideElement={editorDecidesOpen ? rootElement : null}
modal={false}
open={open}
onOpenChange={(nextOpen) => {
if (nextOpen) return;
if (
activeCommentIds.some((id) =>
comments.getSnapshot().draftThreadIds.includes(id)
)
) {
return;
}
store.clearTarget();
comments.cancel();
editor.plugin(CommentsPlugin).api.setActive([]);
setActiveSuggestionId?.(null);
}}
>
{anchorElement && <FloatingPopoverAnchor element={anchorElement} />}
<FloatingPopoverContent
align="center"
anchorHidden={hidden}
key={composerMount.count}
aria-label={pending ? 'New comment' : 'Discussion items'}
className="max-h-[min(50dvh,calc(-24px+var(--floating-popover-available-height)))] w-[380px] max-w-[calc(100vw-24px)] min-w-[130px] gap-0 overflow-y-auto p-0 data-[state=closed]:opacity-0"
data-discussion-popover=""
data-editor-keep-selection-visible
ref={popoverRef}
tabIndex={-1}
onFinalFocus={(event) => {
event.preventDefault();
const document = editableRef.current?.ownerDocument;
const active = document?.activeElement;
if (
!openRef.current &&
(!active ||
active === document?.body ||
popoverRef.current?.contains(active))
) {
focusEditor();
}
}}
onFocus={(event) => {
const onControl = event.target !== event.currentTarget;
focusedControlRef.current = onControl ? event.target : null;
if (onControl && pending) releasedPendingRef.current = pending;
}}
onInitialFocus={(event) => event.preventDefault()}
onPointerDown={(event) => {
const release = new AbortController();
const end = () => {
pressingRef.current = false;
release.abort();
};
pressingRef.current = true;
for (const type of ['pointerup', 'pointercancel']) {
event.currentTarget.ownerDocument.addEventListener(type, end, {
capture: true,
signal: release.signal,
});
}
}}
onPlaced={() => {
if (pending) setPlacedPending(pending);
}}
side="bottom"
>
{pending ? (
<div className="p-4">
<NewComment
autoFocus={placedPending === pending}
focusEditor={focusEditor}
/>
</div>
) : (
<>
{shownItems.map((item, index) => (
<React.Fragment key={`${item.kind}-${item.id}`}>
<div className="p-4">
<DiscussionCard
item={item}
onDecisionApplied={() => {
if (!snapshot.target && item.kind === 'suggestion') {
comments.setActive(item.threadIds);
requestAnimationFrame(() => {
popoverRef.current?.focus();
});
return;
}
popoverRef.current?.focus();
}}
/>
</div>
{(index < shownItems.length - 1 ||
shownItems.length < targetItems.length) && (
<Separator data-discussion-separator="" />
)}
</React.Fragment>
))}
{activeItems.length === 0 &&
shownItems.length < targetItems.length && (
<div className="p-3">
<Button
className="w-full"
onClick={() =>
setPagination({
count: Math.min(
visibleCount + DISCUSSION_PAGE_SIZE,
targetItems.length
),
targetKey,
})
}
size="sm"
variant="ghost"
>
Show more discussion items
</Button>
</div>
)}
</>
)}
</FloatingPopoverContent>
</FloatingPopover>
</div>
);
}
const usePrepareDiscussionSelection = (
setActiveSuggestionId?: (id: string | null) => void
) => {
const editor = useEditor();
const store = useDiscussionStore();
const { api: comments } = editor.plugin(CommentsPlugin);
React.useEffect(() => {
store.setPrepareSelection(() => {
comments.cancel();
editor.plugin(CommentsPlugin).api.setActive([]);
setActiveSuggestionId?.(null);
});
return () => store.setPrepareSelection(null);
}, [comments, editor, setActiveSuggestionId, store]);
};
function SuggestionDiscussion({
editableRef,
snapshot,
}: EditableSiblingProps & { snapshot: DiscussionSnapshot }) {
const { activeId, setActiveId } = useActiveSuggestion();
usePrepareDiscussionSelection(setActiveId);
return (
<DiscussionPopover
activeSuggestionId={activeId}
editableRef={editableRef}
setActiveSuggestionId={setActiveId}
snapshot={snapshot}
/>
);
}
function CommentDiscussion({
editableRef,
snapshot,
}: EditableSiblingProps & { snapshot: DiscussionSnapshot }) {
usePrepareDiscussionSelection();
return (
<DiscussionPopover
activeSuggestionId={null}
editableRef={editableRef}
snapshot={snapshot}
/>
);
}
function Discussion({ editableRef }: EditableSiblingProps) {
const store = useDiscussionStore();
const snapshot = React.useSyncExternalStore(
store.subscribe,
store.getSnapshot,
store.getSnapshot
);
const suggestionsInstalled = React.useContext(SuggestionsInstalledContext);
return suggestionsInstalled ? (
<SuggestionDiscussion editableRef={editableRef} snapshot={snapshot} />
) : (
<CommentDiscussion editableRef={editableRef} snapshot={snapshot} />
);
}
export const DiscussionSlots = {
afterEditable: Discussion,
wrapNode: DiscussionBlockSlot,
wrapRoot: DiscussionRoot,
} satisfies typeof CommentsPlugin.slots;
export const DiscussionKit = [
...CommentKit,
CommentsPlugin.configure({ slots: DiscussionSlots }),
];"use client";
import type { EditorValueInput, Value } from "platejs";
import type { CommentRanges, CommentThread, CommentUser } from "platejs/comments";
import { CommentsPlugin } from "platejs/comments/react";
import { EditorRoot, useCreateEditor } from "platejs/react";
import { BasicBlocksKit } from "@/components/editor/basic-blocks";
import { AllCommentsButton, CommentToolbarButton } from "@/components/editor/comment-toolbar-button";
import { DiscussionKit } from "@/components/editor/discussion";
import { Editor, EditorContainer } from "@/components/editor/editor";
import { LinkKit } from "@/components/editor/link";
import { Toolbar } from "@/components/editor/toolbar";
export function CommentsEditor({ value, ranges, threads, users, userId }: {
value: EditorValueInput<Value>;
ranges: CommentRanges;
threads: readonly CommentThread[];
users: Record<string, CommentUser>;
userId: string;
}) {
const editor = useCreateEditor({
plugins: [
...BasicBlocksKit,
...LinkKit,
...DiscussionKit,
CommentsPlugin.configure({
initialState: { initialComments: { ranges, threads }, users },
}),
],
initialValue: value,
userId,
});
return (
<EditorRoot editor={editor}>
<EditorContainer>
<Toolbar>
<CommentToolbarButton />
<AllCommentsButton />
</Toolbar>
<Editor />
</EditorContainer>
</EditorRoot>
);
}