@nextgensoftwares/folio-plugin-comments adds Google-Docs-style comments: select text (or a figure, table, equation, code block) and choose Comment, discuss in threads beside the page, resolve, reopen, react and @mention people. Who sees and does what is entirely up to the host, and the reference server enforces the same rules.
ts
import { composePlugins } from '@nextgensoftwares/folio-editor';import { commentsPlugin, ServerCommentStore } from '@nextgensoftwares/folio-plugin-comments';const comments = commentsPlugin({ user: { id: 'u42', name: 'Mona Adel', color: '#db2777', role: 'editor' }, readers: 'hidden', // 'hidden' (default) | 'view' | 'comment' mentionables: (q) => searchPeople(q), onMention: (e) => notify(e.mentioned, e.thread),});const composed = composePlugins(standardSchema, [comments /* , docxExportPlugin(...), pdfExportPlugin(...) */]);// Threads for this document on the server (default: in memory).comments.setStore(new ServerCommentStore({ baseUrl: 'https://docs.example.com', docId, headers: () => ({ Authorization: token() }) }));
Render composed.ui in <FolioView ui={...}> and pass composed.pageLayers and composed.painters: the plugin contributes
a Comment item (bubble bar and context menu; Mod-Alt-M). The bubble shows it on a selection in editable views, in read-only views that let readers select (readerInteraction: 'select', when the policy lets them comment) and in book mode (FolioBookApp), including chapters opened for comments, where the toolbar keeps it too. Route it elsewhere with a plugin of the app's own, last in plugins: { name: 'app', ui: { route: { 'comments.add': ['toolbar'] } } } moves it to the toolbar, ['bubble', 'contextMenu', 'toolbar'] adds the toolbar. In edit mode it follows the bubble's built-in formatting, after a separator, and never folds into "⋯"; its group is comment (move: [{ id: 'bubble:comment', before: 'bubble:format' }] for comment-first). Its tooltip says "Comment: add a note for others" (tooltip option, or translate that string through the host's labels).
an overlay slot component: the margin rail (cards beside the pages),
a page layer that highlights commented text (stronger for the active thread),
a Comments tab in the sidebar slot (all threads, open/resolved filter, search, jump to text),
optionally a Comments settings section (settings: true).
A thread is anchored by a comment mark carrying its id (text) or by the commentIds attr of a block (figures, tables, code, equations, callouts; blockTypes picks which). The mark is inclusive: false (typing at a comment's end doesn't extend it) and excludes: '' (comments overlap). Neither affects layout: highlights are a page layer, and exporters ignore the mark unless you export comments on purpose.
Why a mark and not decorations plus position mapping? An anchor that is part of the document survives everything the document survives, with no extra code: edits around and inside it, collab rebasing (it is just another step, so other clients and the server see the same anchors), undo, split/join (each half keeps the mark), copy/paste and reloads. Decorations only live in one editor session: they must be re-derived from stored positions after every reload, mapped through remote steps by hand, and drift whenever a client misses a step. The cost is that comment anchors are document content (so the server's schema must include commentSchema(), and a reader, who can't edit the document, can't add a mark; see below).
The threads themselves (CommentThread: author, time, body, replies, resolution, reactions) are kept outside the document in a CommentStore, so permissions and storage are separate from the document's.
Details worth knowing:
Pasting a copy of commented text drops the copy's anchor (the original keeps it); cut and paste moves the comment with its text.
Creating or deleting a comment is not undoable (as in Docs): the anchor edit is outside the undo history. Undoing the deletion of commented text brings the anchor back.
Deleting all of a comment's text orphans the thread: it leaves the rail and shows in the sidebar as "The commented text was removed".
The anchor index is incremental: a transaction maps the known anchors (O(anchors)) and rescans only the top-level blocks it touched, and only when it touches comments. Typing elsewhere costs a map over a short list.
Point comments (no selection) and readers' comments have a floating anchor: the quote and some context, found once and then mapped through edits. The next editor who opens the document turns a reader's floating anchor into a real mark.
When the document must stay exactly as it is (a server that validates every save against its own schema, documents published to readers as they are), commentsPlugin({ anchors: 'detached' }) adds no schema (no comment mark, no commentIds attrs) and never edits the document. Every thread keeps a detached anchor: the quote, some context before and after, and its positions as hints. It is found on load (near its old place first, then anywhere), mapped through edits while the editor is open, and drawn over the text like any comment. Rail, sidebar, composer, replies, resolving and reactions work the same, and read-only views can comment too (with readers: 'comment').
The trade-off is the one above: a detached anchor is re-found by its text, so it can lose its place when that text is rewritten. A thread whose quote can't be found anymore is orphaned: listed in the sidebar as "The commented text was removed". Threads made with marks elsewhere are placed by their quote too; a block comment is placed where it was while that block is still there.
A comment on the whole document, on no text: the Comments tab has a "Comment on document" button (documentComments: { label: 'Comment on chapter' } to rename it, false to remove it). Its anchor is { kind: 'doc' }; it lists first, exports at the document's start, and "go to" scrolls to the top. Servers older than this anchor kind refuse it as invalid.
Everything is configurable on commentsPlugin({...}) (and live with setOptions / setUser):
Option
Default
readers
'hidden': readers see no highlights, rail or sidebar. 'view': read-only threads. 'comment': they can comment and reply.
isReader(user)
user.role === 'reader'
canView(user)
editors; readers per readers; anonymous (user: null) never
canComment(user)
editors; readers with readers: 'comment'
canResolve(user, thread)
editors; a commenting reader for threads they started
canEdit(comment, user)
the comment's author
canDelete(comment, user, thread)
the comment's author (deleting a thread's root deletes the thread)
canReact(user, thread)
whoever can comment
A rule that throws denies.
Client rules are only UX
The plugin hides what the policy forbids, but a browser can send anything. Enforce on the server: @nextgensoftwares/folio-server-node's comment routes evaluate the same CommentPolicyOptions against the identity your identify hook returns, then your authorize hook, for every request. Never take the author from the request body.
MemoryCommentStore: in memory; every editor in the tab sharing it sees the same threads and typing indicators.
ServerCommentStore: the reference server's REST routes. Writes are optimistic and roll back when refused; other people's changes arrive over a live source (store.setLive(collabClient): the collab socket forwards comment events) or by polling with ETags (pollMs, default 4 s, 4× slower while live).
Your own: implement CommentStore (threads, subscribe, apply, optional typing/typists/status/error). applyOp is the shared reducer, so any backend can apply and validate ops identically.
import { createFolioServer, FileCommentBackend } from '@nextgensoftwares/folio-server-node';createFolioServer({ schema: toProseMirrorSchema(standardSchema.extend(commentSchema())), comments: { identify: (req) => sessionUser(req), // required: who is calling (null = 401) readers: 'view', // the same policy options as the client authorize: (req, docId, action, { user }) => isMember(user, docId), backend: new FileCommentBackend('./data/comments'), onMention: (e) => sendMentionEmails(e), },});
Routes under /docs/:id/comments: GET (list, ETag), POST (create), POST /:thread/replies, PATCH /:thread ({resolved} or {anchor}), PATCH /:thread/:comment (edit), DELETE /:thread[/:comment], PUT|DELETE /:thread/:comment/reactions/:emoji, POST /typing. Every change is also sent to the document's collaborators as a collab event ({ kind: 'comments' | 'comments-typing' }). insecureHeaderIdentity() trusts an X-Folio-User header and exists for demos only.
Comments that come from a file (a Word document's comments.xml, through @nextgensoftwares/folio-plugin-import) keep who wrote them there. The store still records the importing user as author (stores attribute every write to its actor, and permissions such as "edit your own" follow it), and the original is kept as origin: { name, createdAt? } on the thread and each reply:
cards show the original name, avatar initials and date, marked "from file" (the tooltip names who added it);
DOCX and PDF exports write the original author, initials and date, so a Word file opened and downloaded again shows its comments as they were;
shownAuthor(comment) gives the name and date to display for any comment.
origin is display data only: it grants no permissions, and the server sanitizes it like any input (controls and bidi overrides removed, 80 characters, a plausible date or none). A host's own import path sends it in the create / reply ops (thread.origin, comment.origin; REST bodies carry origin too).
DOCX export is on by default: a document's comments are written to the Word file (open threads; add resolved: true for resolved ones), and exportComments: { docx: false } turns it off. PDF annotations stay opt-in (pdf: true). Wire the exporters:
DOCX: real Word comments: comments.xml, commentRangeStart/End around the anchored text (across paragraphs too), commentReference runs, replies threaded under their root and resolved threads marked done (commentsExtended.xml, written whenever a thread is resolved, replies or not). Authors, initials and dates are kept; reactions have no Word equivalent and aren't exported. Block anchors wrap the block. Opened with importDocx, the file gives back the same threads (anchors, replies, resolved state).
PDF: a highlight annotation over each thread's text (a sticky note for blocks and points) with the replies as notes "in reply to" it.
Cards show the author's avatar or initials, name, relative time, body with @mentions, replies, a reply box (when active), resolve/reopen, edit/delete for your own comments and a "…" menu. Clicking highlighted text activates its card; clicking a card (or its quoted text) activates and selects the text. Cards are focusable (Enter opens the reply box, Escape returns to the text), menus work with arrow keys, the composer sends with Ctrl/⌘+Enter. Styles use Folio's UI tokens (light/dark), and highlights go through the document's colour adapter, so dark document themes adapt them.
The rail renders cards only for mounted (visible) pages and stacks them without overlaps around the active card; pages shift left to make room. When there's no room (narrow windows), in reflow and compact layouts, the rail collapses: the active thread opens in a sheet at the bottom of the view and the sidebar lists everything.
Comments plugin
@nextgensoftwares/folio-plugin-commentsadds Google-Docs-style comments: select text (or a figure, table, equation, code block) and choose Comment, discuss in threads beside the page, resolve, reopen, react and @mention people. Who sees and does what is entirely up to the host, and the reference server enforces the same rules.Render
composed.uiin<FolioView ui={...}>and passcomposed.pageLayersandcomposed.painters: the plugin contributesMod-Alt-M). The bubble shows it on a selection in editable views, in read-only views that let readers select (readerInteraction: 'select', when the policy lets them comment) and in book mode (FolioBookApp), including chapters opened for comments, where the toolbar keeps it too. Route it elsewhere with a plugin of the app's own, last inplugins:{ name: 'app', ui: { route: { 'comments.add': ['toolbar'] } } }moves it to the toolbar,['bubble', 'contextMenu', 'toolbar']adds the toolbar. In edit mode it follows the bubble's built-in formatting, after a separator, and never folds into "⋯"; its group iscomment(move: [{ id: 'bubble:comment', before: 'bubble:format' }]for comment-first). Its tooltip says "Comment: add a note for others" (tooltipoption, or translate that string through the host's labels).overlayslot component: the margin rail (cards beside the pages),sidebarslot (all threads, open/resolved filter, search, jump to text),settings: true).How it works
Anchors live in the document, threads don't
A thread is anchored by a
commentmark carrying its id (text) or by thecommentIdsattr of a block (figures, tables, code, equations, callouts;blockTypespicks which). The mark isinclusive: false(typing at a comment's end doesn't extend it) andexcludes: ''(comments overlap). Neither affects layout: highlights are a page layer, and exporters ignore the mark unless you export comments on purpose.Why a mark and not decorations plus position mapping? An anchor that is part of the document survives everything the document survives, with no extra code: edits around and inside it, collab rebasing (it is just another step, so other clients and the server see the same anchors), undo, split/join (each half keeps the mark), copy/paste and reloads. Decorations only live in one editor session: they must be re-derived from stored positions after every reload, mapped through remote steps by hand, and drift whenever a client misses a step. The cost is that comment anchors are document content (so the server's schema must include
commentSchema(), and a reader, who can't edit the document, can't add a mark; see below).The threads themselves (
CommentThread: author, time, body, replies, resolution, reactions) are kept outside the document in aCommentStore, so permissions and storage are separate from the document's.Details worth knowing:
Schema-free comments (
anchors: 'detached') When the document must stay exactly as it is (a server that validates every save against its own schema, documents published to readers as they are),
commentsPlugin({ anchors: 'detached' })adds no schema (nocommentmark, nocommentIdsattrs) and never edits the document. Every thread keeps a detached anchor: the quote, some context before and after, and its positions as hints. It is found on load (near its old place first, then anywhere), mapped through edits while the editor is open, and drawn over the text like any comment. Rail, sidebar, composer, replies, resolving and reactions work the same, and read-only views can comment too (withreaders: 'comment').The trade-off is the one above: a detached anchor is re-found by its text, so it can lose its place when that text is rewritten. A thread whose quote can't be found anymore is orphaned: listed in the sidebar as "The commented text was removed". Threads made with marks elsewhere are placed by their quote too; a block comment is placed where it was while that block is still there.
General comments
A comment on the whole document, on no text: the Comments tab has a "Comment on document" button (
documentComments: { label: 'Comment on chapter' }to rename it,falseto remove it). Its anchor is{ kind: 'doc' }; it lists first, exports at the document's start, and "go to" scrolls to the top. Servers older than this anchor kind refuse it as invalid.Permissions
Everything is configurable on
commentsPlugin({...})(and live withsetOptions/setUser):readers'hidden': readers see no highlights, rail or sidebar.'view': read-only threads.'comment': they can comment and reply.isReader(user)user.role === 'reader'canView(user)readers; anonymous (user: null) nevercanComment(user)readers: 'comment'canResolve(user, thread)canEdit(comment, user)canDelete(comment, user, thread)canReact(user, thread)A rule that throws denies.
Client rules are only UX
The plugin hides what the policy forbids, but a browser can send anything. Enforce on the server:
@nextgensoftwares/folio-server-node's comment routes evaluate the sameCommentPolicyOptionsagainst the identity youridentifyhook returns, then yourauthorizehook, for every request. Never take the author from the request body.Stores
MemoryCommentStore: in memory; every editor in the tab sharing it sees the same threads and typing indicators.ServerCommentStore: the reference server's REST routes. Writes are optimistic and roll back when refused; other people's changes arrive over a live source (store.setLive(collabClient): the collab socket forwards comment events) or by polling with ETags (pollMs, default 4 s, 4× slower while live).CommentStore(threads,subscribe,apply, optionaltyping/typists/status/error).applyOpis the shared reducer, so any backend can apply and validate ops identically.Server
Routes under
/docs/:id/comments:GET(list, ETag),POST(create),POST /:thread/replies,PATCH /:thread({resolved}or{anchor}),PATCH /:thread/:comment(edit),DELETE /:thread[/:comment],PUT|DELETE /:thread/:comment/reactions/:emoji,POST /typing. Every change is also sent to the document's collaborators as a collabevent({ kind: 'comments' | 'comments-typing' }).insecureHeaderIdentity()trusts anX-Folio-Userheader and exists for demos only.Imported comments
Comments that come from a file (a Word document's
comments.xml, through@nextgensoftwares/folio-plugin-import) keep who wrote them there. The store still records the importing user asauthor(stores attribute every write to its actor, and permissions such as "edit your own" follow it), and the original is kept asorigin: { name, createdAt? }on the thread and each reply:shownAuthor(comment)gives the name and date to display for any comment.originis display data only: it grants no permissions, and the server sanitizes it like any input (controls and bidi overrides removed, 80 characters, a plausible date or none). A host's own import path sends it in thecreate/replyops (thread.origin,comment.origin; REST bodies carryorigintoo).Export
DOCX export is on by default: a document's comments are written to the Word file (open threads; add
resolved: truefor resolved ones), andexportComments: { docx: false }turns it off. PDF annotations stay opt-in (pdf: true). Wire the exporters:comments.xml,commentRangeStart/Endaround the anchored text (across paragraphs too),commentReferenceruns, replies threaded under their root and resolved threads marked done (commentsExtended.xml, written whenever a thread is resolved, replies or not). Authors, initials and dates are kept; reactions have no Word equivalent and aren't exported. Block anchors wrap the block. Opened withimportDocx, the file gives back the same threads (anchors, replies, resolved state).UI and accessibility
Cards show the author's avatar or initials, name, relative time, body with @mentions, replies, a reply box (when active), resolve/reopen, edit/delete for your own comments and a "…" menu. Clicking highlighted text activates its card; clicking a card (or its quoted text) activates and selects the text. Cards are focusable (
Enteropens the reply box,Escapereturns to the text), menus work with arrow keys, the composer sends withCtrl/⌘+Enter. Styles use Folio's UI tokens (light/dark), and highlights go through the document's colour adapter, so dark document themes adapt them.The rail renders cards only for mounted (visible) pages and stacks them without overlaps around the active card; pages shift left to make room. When there's no room (narrow windows), in reflow and compact layouts, the rail collapses: the active thread opens in a sheet at the bottom of the view and the sidebar lists everything.
Known limits