Files
Docwell/Packages/editor/src/extensions.ts
T
tajniak81andClaude Opus 5.5 c98b127f1e
CI / go (Media) (push) Successful in 13m40s
CI / go (Server) (push) Failing after 23m20s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 10m35s
Docs / build (push) Canceled after 0s
Docs / deploy (push) Canceled after 0s
CI / desktop (ubuntu-latest) (push) Failing after 3h4m42s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / mobile (push) Failing after 9m19s
CI / docker (push) Successful in 2h2m57s
Add columns, suggesting mode, verified pages, scanned PDF search and server translations
- Columns: /columns puts 2 to 4 columns side by side, with widths dragged
  between them; they stack on phones. HTML export and import keep them
  (also Notion column lists and Confluence page layouts).
- Suggesting mode: edits become suggested insertions and deletions that
  editors accept or reject one by one or all at once. Text only.
- Verified pages: editors verify a page for a while or without end; the
  verifier is notified when it runs out (migration 1764700000).
- Scanned PDFs attached to pages are read by AI for search where a
  workspace turns it on.
- The server writes error messages, emails, digests and phone
  notifications in English, Polish, German, French and Spanish; the apps
  send their language with each request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 08:38:08 +01:00

263 lines
11 KiB
TypeScript

// SPDX-License-Identifier: AGPL-3.0-or-later
import { Extension, type AnyExtension, type Editor } from "@tiptap/core";
import Collaboration from "@tiptap/extension-collaboration";
import CollaborationCaret from "@tiptap/extension-collaboration-caret";
import { Placeholder } from "@tiptap/extensions";
import StarterKit from "@tiptap/starter-kit";
import { BlockLinks } from "./blocklinks";
import { docwellAlign, docwellTables, docwellTasks, HeadingShortcuts } from "./blocks";
import { Callout } from "./callout";
import { Column, Columns } from "./columns";
import { Database } from "./database";
import { DB_ORIGIN } from "./database/store";
import { DocwellCodeBlock } from "./codeblock";
import { DocwellHighlight, TextColor } from "./colors";
import { CommentHighlights } from "./comments";
import { DateMention } from "./dates";
import { SyncedPage, type SyncedPageHost } from "./syncedpage";
import type * as Y from "yjs";
import { DrawioBlock, ExcalidrawBlock, type ExcalidrawLoader } from "./diagrams";
import { Embed, LinkCard, type LinkHost } from "./embeds";
import { DocwellImage, FileAttachment, FileDrop, type FileHost } from "./files";
import { FindReplace } from "./find";
import { englishLabels, type EditorLabels } from "./labels";
import { docwellMath } from "./math";
import { docwellMention, type MentionHost } from "./mention";
import { MermaidBlock, type MermaidLoader } from "./mermaid";
import { PageLinks, type PageHost } from "./pagelinks";
import type { PdfLoader } from "./pdf";
import { SlashMenu, slashCommands } from "./slash";
import { Suggestions } from "./suggest";
import type { CollabProvider } from "./provider";
import { TableMove } from "./tablemove";
import { TableOfContents } from "./toc";
import { docwellToggles } from "./toggle";
export interface CollabUser {
name: string;
color: string;
}
export interface ExtensionOptions {
placeholder?: string;
/** Edits the provider's shared document and shows the other editors' carets. */
collab?: { provider: CollabProvider; user: CollabUser };
/** Loads and uploads attachments; without it images use their src as is. */
files?: FileHost;
/** Finds people for "@" mentions. */
mentions?: MentionHost;
/** Finds pages for "[[" links. */
pages?: PageHost;
/** Fetches previews for link cards; without it cards show the address only. */
links?: LinkHost;
/**
* The full address of a link to a block of this page, from its "#b-<id>"
* fragment. Without it the margin has no "copy link" button.
*/
blockLink?: (hash: string) => string;
/** Called after a block link was copied. */
onBlockLinkCopied?: (url: string) => void;
/** Opens an app route, e.g. "/p/<id>" when a page link is followed. */
onNavigate?: (path: string) => void;
/** Opens a date's journal page (clicking a date mention); hosts without journals leave it out. */
onOpenDate?: (date: string) => void;
/** Draws synced pages live; without it they show as links to the page. */
syncedPages?: SyncedPageHost;
/**
* Shows this document read-only (a synced page's copy): bound to it
* without carets, undo or synced pages of its own.
*/
syncedDoc?: Y.Doc;
/** Edits a database row's body (database/peek.ts): bound to this fragment of doc, without carets. */
rowBody?: { doc: Y.Doc; fragment: Y.XmlFragment };
/** The Draw.io embed address (default https://embed.diagrams.net). */
drawioUrl?: string;
/** Loads Mermaid; without it diagrams show as their text. */
loadMermaid?: MermaidLoader;
/** Loads the Excalidraw editor; without it drawings show but cannot be edited. */
loadExcalidraw?: ExcalidrawLoader;
/** Loads pdf.js; without it PDF attachments show as download cards. */
loadPdf?: PdfLoader;
/** Whether code blocks show line numbers unless one was switched on or off itself. */
codeLineNumbers?: boolean;
/** Opens a database record as a full page (the host's record route). */
recordPage?: (database: string, row: string) => void;
/** Shows a database row's body read-only (a row in a synced page). */
rowFragmentReadOnly?: Y.XmlFragment;
labels?: EditorLabels;
/** Clicking highlighted comment text calls this with the comment id. */
onCommentSelect?: (id: string) => void;
/** Clicking suggested text calls this with the suggestion id and the clicked element. */
onSuggestionSelect?: (id: string, el: HTMLElement) => void;
onError?: (e: unknown) => void;
}
/**
* The Docwell document schema. Every client (web, desktop, mobile WebView)
* must build its editor from this list so documents stay compatible.
*/
export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] {
const labels = opts.labels ?? englishLabels;
// Node views and click handlers that need the editor find it here.
let editor: Editor | null = null;
const editorRef = Extension.create({
name: "editorRef",
onCreate() {
editor = this.editor;
},
});
const diagrams = {
host: opts.files,
labels,
drawioUrl: opts.drawioUrl,
loadExcalidraw: opts.loadExcalidraw,
onError: opts.onError,
};
const list: AnyExtension[] = [
editorRef,
StarterKit.configure({
heading: { levels: [1, 2, 3, 4, 5, 6] },
codeBlock: false,
link: { openOnClick: false, autolink: true },
// Collaboration brings its own undo history, scoped to the local user.
undoRedo: opts.collab || opts.syncedDoc || opts.rowBody || opts.rowFragmentReadOnly ? false : undefined,
}),
Placeholder.configure({ placeholder: opts.placeholder ?? "Type '/' for commands…" }),
DocwellImage.configure({ host: opts.files }),
FileAttachment.configure({ host: opts.files, loadPdf: opts.loadPdf, labels }),
DocwellCodeBlock.configure({ lineNumbers: opts.codeLineNumbers ?? false }),
HeadingShortcuts,
docwellAlign,
TextColor,
DocwellHighlight,
...docwellTasks(),
...docwellTables(),
TableMove.configure({ labels }),
Callout.configure({ labels }),
Columns.configure({ labels }),
Column.configure({ labels }),
FileDrop.configure({ host: opts.files, onError: opts.onError }),
docwellMention(labels, opts.mentions),
DateMention.configure({ labels, me: () => opts.mentions?.me, onOpen: opts.onOpenDate }),
SlashMenu.configure({
commands: slashCommands(labels, opts.files, opts.onError, opts.pages, !!opts.loadExcalidraw, opts.links),
labels,
}),
CommentHighlights.configure({ onSelect: opts.onCommentSelect }),
Suggestions.configure({ onSelect: opts.onSuggestionSelect }),
docwellMath(labels, () => editor),
MermaidBlock.configure({ labels, load: opts.loadMermaid }),
TableOfContents.configure({ labels }),
DrawioBlock.configure(diagrams),
ExcalidrawBlock.configure(diagrams),
PageLinks.configure({ host: opts.pages, labels, onNavigate: opts.onNavigate }),
SyncedPage.configure({
host: opts.syncedPages,
pages: opts.pages,
labels,
onNavigate: opts.onNavigate,
// One level deep: a synced page's own synced pages show as links.
nested: (doc) =>
docwellExtensions({
syncedDoc: doc,
files: opts.files,
links: opts.links,
onNavigate: opts.onNavigate,
drawioUrl: opts.drawioUrl,
loadMermaid: opts.loadMermaid,
loadPdf: opts.loadPdf,
codeLineNumbers: opts.codeLineNumbers,
labels: opts.labels,
placeholder: "",
}),
}),
...docwellToggles(labels),
Embed.configure({ labels }),
LinkCard.configure({ labels }),
BlockLinks.configure({ labels, link: opts.blockLink, onCopied: opts.onBlockLinkCopied }),
FindReplace,
Database.configure({
labels,
doc: opts.collab?.provider.doc ?? opts.syncedDoc ?? opts.rowBody?.doc,
readOnlyDoc: !!opts.syncedDoc,
undoScope: !opts.rowBody,
files: opts.files,
people: opts.mentions,
// Records are linked like blocks: the page address plus a #fragment.
recordLink: opts.blockLink,
// Relations read other pages' databases the way synced pages are read.
linkedPages: opts.syncedPages,
pages: opts.pages,
onNavigate: opts.onNavigate,
recordPage: opts.recordPage,
onLinkCopied: opts.onBlockLinkCopied,
me: () => {
const id = opts.mentions?.me;
return id ? { id, name: opts.collab?.user.name ?? "" } : null;
},
// A row body is a page of its own: the same blocks, minus carets and synced pages.
rowExtensions: (fragment) => {
const doc = opts.collab?.provider.doc ?? opts.syncedDoc ?? opts.rowBody?.doc;
return docwellExtensions({
rowBody: fragment && doc && !opts.syncedDoc ? { doc, fragment } : undefined,
files: opts.files,
mentions: opts.mentions,
pages: opts.pages,
links: opts.links,
onNavigate: opts.onNavigate,
drawioUrl: opts.drawioUrl,
loadMermaid: opts.loadMermaid,
loadExcalidraw: opts.loadExcalidraw,
loadPdf: opts.loadPdf,
codeLineNumbers: opts.codeLineNumbers,
labels: opts.labels,
placeholder: labels.database.bodyPlaceholder,
rowFragmentReadOnly: !!fragment && !!opts.syncedDoc ? fragment : undefined,
});
},
}),
];
// Database edits (DB_ORIGIN) are undone with the text they were made with.
const yUndoOptions = { trackedOrigins: [DB_ORIGIN] };
if (opts.rowBody) {
list.push(Collaboration.configure({ document: opts.rowBody.doc, fragment: opts.rowBody.fragment, yUndoOptions }));
} else if (opts.rowFragmentReadOnly) {
list.push(Collaboration.configure({ fragment: opts.rowFragmentReadOnly }));
} else if (opts.syncedDoc) {
list.push(Collaboration.configure({ document: opts.syncedDoc }));
} else if (opts.collab) {
list.push(
Collaboration.configure({ document: opts.collab.provider.doc, yUndoOptions }),
CollaborationCaret.configure({ provider: opts.collab.provider, user: opts.collab.user, render: renderCaret }),
);
}
return list;
}
/**
* Another editor's caret with their name. The name is hidden from assistive
* tech, which would otherwise read it as part of the text.
*/
function renderCaret(user: Record<string, unknown>): HTMLElement {
const color = typeof user.color === "string" && /^#[0-9a-f]{3,8}$/i.test(user.color) ? user.color : "#888";
const caret = document.createElement("span");
caret.classList.add("collaboration-carets__caret");
caret.style.borderColor = color;
const label = document.createElement("div");
label.classList.add("collaboration-carets__label");
label.setAttribute("aria-hidden", "true");
label.style.backgroundColor = color;
label.textContent = typeof user.name === "string" ? user.name : "";
caret.append(label);
return caret;
}
/** A stable caret colour for a user id, from the design system's accent hues. */
export function userColor(id: string): string {
const hues = ["#2f7d6d", "#7c5cc4", "#c2571a", "#2f6fbf", "#b8327a", "#5f8a1f", "#a0761c", "#1f8a9a"];
let h = 0;
for (const ch of id) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
return hues[h % hues.length]!;
}