Files
Docwell/Packages/editor/src/comments.ts
T
tajniak81andClaude Opus 5.5 92cd81fd96 Add the slash menu, bubble menu, mentions and inline comments
Editor:
- "/" opens a filterable block menu (text, headings, lists, quote, code,
  divider, and image or file upload when the host can store files).
- Selecting text shows a formatting toolbar (bold, italic, strike, code,
  link) and, for anyone who may comment, a Comment button.
- "@" finds people in the page's workspace; the mention node is always in
  the schema so documents with mentions open in every client.
- The popups are plain DOM in the design system's slash-menu style, so
  the framework-free mobile bridge keeps building and can use them.
- Menu words come from the host; the web app passes English or Polish.

Inline comments (basic): commenters cannot edit the document, so a
comment's anchor is a pair of Yjs relative positions stored with the
comment rather than a mark in the text. Highlights follow local edits by
mapping and are re-resolved when comments change or remote edits arrive.
Pages get a comments panel (side column, or a bottom sheet on narrow
screens). Authors and space admins can delete comments.

Server: comments collection and endpoints, and a people lookup any
workspace member may use for mentions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:25:19 +01:00

139 lines
4.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: AGPL-3.0-or-later
import { Extension, type Editor } from "@tiptap/core";
import { Plugin, PluginKey, type EditorState } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
import {
absolutePositionToRelativePosition,
relativePositionToAbsolutePosition,
ySyncPluginKey,
} from "@tiptap/y-tiptap";
import { fromBase64, toBase64 } from "lib0/buffer";
import * as Y from "yjs";
/**
* Where a comment points: Yjs relative positions of the range's ends, which
* keep pointing at the same text while people edit around it. Only editors
* on a shared (collaborative) document can make or read them.
*/
export interface CommentAnchor {
from: string;
to: string;
}
/** A comment to highlight: its id and anchor (null anchors are not drawn). */
export interface CommentMark {
id: string;
anchor: CommentAnchor | null;
}
type SyncState = {
type: Y.XmlFragment;
doc: Y.Doc;
binding: { mapping: Parameters<typeof absolutePositionToRelativePosition>[2] };
};
function sync(state: EditorState): SyncState | null {
const s = ySyncPluginKey.getState(state) as Partial<SyncState> | undefined;
return s?.type && s.binding && s.doc ? (s as SyncState) : null;
}
/** Encodes the range from–to of the editor's document. */
export function encodeAnchor(editor: Editor, from: number, to: number): CommentAnchor | null {
const s = sync(editor.state);
if (!s) return null;
const rel = (pos: number) =>
toBase64(Y.encodeRelativePosition(absolutePositionToRelativePosition(pos, s.type, s.binding.mapping)));
return { from: rel(from), to: rel(to) };
}
/**
* The range an anchor points at in state's document, or null when its text
* was deleted. The Yjs document must already contain state's changes.
*/
export function decodeAnchor(state: EditorState, anchor: CommentAnchor | null): { from: number; to: number } | null {
const s = sync(state);
if (!s || !anchor?.from || !anchor.to) return null;
try {
const abs = (b64: string) =>
relativePositionToAbsolutePosition(s.doc, s.type, Y.decodeRelativePosition(fromBase64(b64)), s.binding.mapping);
const from = abs(anchor.from);
const to = abs(anchor.to);
if (from === null || to === null || to <= from || to > state.doc.content.size) return null;
return { from, to };
} catch {
return null;
}
}
type Highlights = { marks: CommentMark[]; active: string; decos: DecorationSet };
const key = new PluginKey<Highlights>("docwellComments");
/** Replaces the highlighted comments (and which one is active). */
export function setCommentMarks(editor: Editor, marks: CommentMark[], active = "") {
editor.view.dispatch(editor.state.tr.setMeta(key, { marks, active }));
}
function draw(state: EditorState, marks: CommentMark[], active: string): DecorationSet {
const decos: Decoration[] = [];
for (const m of marks) {
const range = decodeAnchor(state, m.anchor);
if (!range) continue;
decos.push(
Decoration.inline(range.from, range.to, {
class: m.id === active ? "dw-comment is-active" : "dw-comment",
"data-comment": m.id,
}),
);
}
return DecorationSet.create(state.doc, decos);
}
/**
* Highlights commented text. Clicking a highlight calls onSelect with the
* comment's id, so the host can scroll its comment list to it.
*
* Anchors are resolved through Yjs only when the comments change or a remote
* edit arrives; a local edit reaches the Yjs document after the transaction,
* so for those the highlights are mapped through the edit instead.
*/
export const CommentHighlights = Extension.create<{ onSelect?: (id: string) => void }>({
name: "commentHighlights",
addOptions() {
return { onSelect: undefined };
},
addProseMirrorPlugins() {
const onSelect = () => this.options.onSelect;
return [
new Plugin<Highlights>({
key,
state: {
init: () => ({ marks: [], active: "", decos: DecorationSet.empty }),
apply(tr, value, _old, state) {
const set = tr.getMeta(key) as { marks: CommentMark[]; active: string } | undefined;
if (set) return { ...set, decos: draw(state, set.marks, set.active) };
if (!tr.docChanged || !value.marks.length) return value;
const remote = (tr.getMeta(ySyncPluginKey) as { isChangeOrigin?: boolean } | undefined)?.isChangeOrigin;
return {
...value,
decos: remote ? draw(state, value.marks, value.active) : value.decos.map(tr.mapping, tr.doc),
};
},
},
props: {
decorations: (state) => key.getState(state)?.decos ?? DecorationSet.empty,
handleClick(_view, _pos, event) {
const id = (event.target as HTMLElement | null)?.closest?.("[data-comment]")?.getAttribute("data-comment");
if (!id) return false;
onSelect()?.(id);
return false;
},
},
}),
];
},
});