Files
outline/server/models/helpers/DocumentHelper.tsx
T
Tom Moor d5bc88f893 perf: Memoize Prosemirror parsing in DocumentHelper (#13892)
Nodes are cached against the content or state they were parsed from, so
repeated helper calls on the same document parse it once. JSON transform
helpers now replace attrs instead of mutating them, as Node.toJSON shares
attrs with the cached node.
2026-09-25 20:57:58 -04:00

1439 lines
48 KiB
TypeScript

import { isEqual, omit } from "es-toolkit/compat";
import type { JSDOM } from "jsdom";
import { Node, Fragment, type NodeType } from "prosemirror-model";
import ukkonen from "ukkonen";
import { updateYFragment, yDocToProsemirrorJSON } from "y-prosemirror";
import * as Y from "yjs";
import {
ChangesetHelper,
type ExtendedChange,
} from "@shared/editor/lib/ChangesetHelper";
import headingToSlug from "@shared/editor/lib/headingToSlug";
import textBetween from "@shared/editor/lib/textBetween";
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
import type { NavigationNode, ProsemirrorData } from "@shared/types";
import { DocumentPreference, IconType, TextEditMode } from "@shared/types";
import { determineIconType } from "@shared/utils/icon";
import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper";
import type { CommentMark } from "@shared/utils/ProsemirrorHelper";
import { parser, serializer, schema } from "@server/editor";
import { ValidationError } from "@server/errors";
import { addTags } from "@server/logging/tracer";
import { trace } from "@server/logging/tracing";
import type { Template } from "@server/models";
import { Collection, Document, Revision } from "@server/models";
import type { MentionAttrs } from "./ProsemirrorHelper";
import { ProsemirrorHelper } from "./ProsemirrorHelper";
import { TextHelper } from "./TextHelper";
/** Maps a range of text-content offsets to ProseMirror Fragment offsets. */
interface InlineSegment {
textFrom: number;
textTo: number;
pmFrom: number;
pmTo: number;
/** Whether this segment is an atom node whose text length differs from nodeSize. */
isAtom?: boolean;
}
/** Context for a patch operation, shared across surgical patch methods. */
interface PatchContext {
/** The full document markdown string. */
markdown: string;
/** Start of the findText match in the markdown. */
matchIndex: number;
/** End of the findText match in the markdown. */
matchEnd: number;
/** Start of the target node's markdown in the full string. */
nodeMdFrom: number;
/** End of the target node's markdown in the full string. */
nodeMdTo: number;
/** The markdown replacement text. */
replacementText: string;
}
type HTMLOptions = {
/** Whether to include the document title in the generated HTML (defaults to true) */
includeTitle?: boolean;
/** Whether to include style tags in the generated HTML (defaults to true) */
includeStyles?: boolean;
/** Whether to include the Mermaid script in the generated HTML (defaults to false) */
includeMermaid?: boolean;
/** Whether to include the doctype,head, etc in the generated HTML (defaults to false) */
includeHead?: boolean;
/** Whether to include styles to center diff (defaults to true) */
centered?: boolean;
/**
* Whether to replace attachment urls with pre-signed versions. If set to a
* number then the urls will be signed for that many seconds. (defaults to false)
*/
signedUrls?: boolean | number;
/** The base URL to use for relative links */
baseUrl?: string;
/** Changes to highlight in the document */
changes?: readonly ExtendedChange[];
/** CSP nonce to apply to injected inline scripts */
cspNonce?: string;
};
@trace()
export class DocumentHelper {
/**
* Returns all of the comment marks in the document. Results are memoized
* against the document body so that repeated calls for the same content do
* not reparse the document.
*
* @param document The document to read comment marks from
* @returns The comment marks in the document
*/
static getCommentMarks(document: Document | Revision): CommentMark[] {
const key =
document.content ?? ("state" in document ? document.state : undefined);
if (!key) {
return ProsemirrorHelper.getComments(
DocumentHelper.toProsemirror(document)
);
}
let marks = DocumentHelper.commentMarksCache.get(key);
if (!marks) {
marks = ProsemirrorHelper.getComments(
DocumentHelper.toProsemirror(document)
);
DocumentHelper.commentMarksCache.set(key, marks);
}
return marks;
}
/**
* Returns the document as a Prosemirror Node. This method uses the derived content if available
* then the collaborative state, otherwise it falls back to Markdown. Results are memoized
* against the content or state they were parsed from, so the returned node must not be mutated.
*
* @param document The document or revision to convert
* @returns The document content as a Prosemirror Node
*/
static toProsemirror(
document: Document | Revision | Collection | ProsemirrorData
) {
const source =
"type" in document && document.type === "doc"
? document
: "content" in document && document.content
? document.content
: "state" in document && document.state
? document.state
: undefined;
if (!source) {
const text =
document instanceof Collection ? document.description : document.text;
return parser.parse(text ?? "") || Node.fromJSON(schema, {});
}
let node = DocumentHelper.prosemirrorCache.get(source);
if (!node) {
if (source instanceof Uint8Array) {
const ydoc = new Y.Doc();
Y.applyUpdate(ydoc, source);
node = Node.fromJSON(schema, yDocToProsemirrorJSON(ydoc, "default"));
} else {
node = Node.fromJSON(schema, source);
}
DocumentHelper.prosemirrorCache.set(source, node);
}
return node;
}
/**
* Returns the collaborative state for a document. Documents that have never been opened in a
* collaborative session have no state, in which case one is derived from the content, falling
* back to Markdown.
*
* @param document The document to convert
* @returns The collaborative state
*/
static toState(document: Document): Uint8Array {
if (document.state) {
return document.state;
}
return ProsemirrorHelper.toState(
ProsemirrorHelper.toYDoc(document.content ?? document.text ?? "")
);
}
/**
* Returns the document as a plain JSON object. This method uses the derived content if available
* then the collaborative state, otherwise it falls back to Markdown.
*
* @param document The document or revision to convert
* @param options Options for the conversion
* @returns The document content as a plain JSON object
*/
static async toJSON(
document: Document | Revision | Collection | Template,
options?: {
/** The team context */
teamId?: string;
/** Whether to sign attachment urls, and if so for how many seconds is the signature valid */
signedUrls?: number;
/** Marks to remove from the document */
removeMarks?: string[];
/** The base path to use for internal links (will replace /doc/) */
internalUrlBase?: string;
}
): Promise<ProsemirrorData> {
let doc: Node | null;
let data: ProsemirrorData;
if ("content" in document && document.content) {
// Optimized path for documents with content available and no transformation required.
if (
!options?.removeMarks &&
!options?.signedUrls &&
!options?.internalUrlBase
) {
return document.content;
}
doc = Node.fromJSON(schema, document.content);
} else if ("state" in document && document.state) {
const ydoc = new Y.Doc();
Y.applyUpdate(ydoc, document.state);
doc = Node.fromJSON(schema, yDocToProsemirrorJSON(ydoc, "default"));
} else if (document instanceof Collection) {
doc = parser.parse(document.description ?? "");
} else {
doc = parser.parse("text" in document ? (document.text ?? "") : "");
}
if (doc && options?.signedUrls && options?.teamId) {
data = await ProsemirrorHelper.signAttachmentUrls(
doc,
options.teamId,
options.signedUrls
);
} else {
data = doc?.toJSON() ?? ProsemirrorDataHelper.getEmpty();
}
if (options?.internalUrlBase) {
data = ProsemirrorHelper.replaceInternalUrls(
data,
options.internalUrlBase
);
}
if (options?.removeMarks) {
data = ProsemirrorHelper.removeMarks(data, options.removeMarks);
}
return data;
}
/**
* Returns the document as plain text. This method uses the
* collaborative state if available, otherwise it falls back to Markdown.
*
* @param document The document or revision or prosemirror data to convert
* @returns The document content as plain text without formatting.
*/
static toPlainText(document: Document | Revision | ProsemirrorData) {
const node = DocumentHelper.toProsemirror(document);
return textBetween(node, 0, node.content.size);
}
/**
* Returns the Markdown content of the section beginning at the heading that
* matches the given anchor. A section spans from the matched heading up to
* (but not including) the next heading of the same or higher level.
*
* @param document The document or revision or prosemirror data to extract from
* @param anchor The heading anchor to locate, with or without a leading "#"
* @returns the section content as Markdown, or undefined if no heading matches.
*/
static getAnchorContent(
document: Document | Revision | ProsemirrorData,
anchor: string
): string | undefined {
let id = anchor.replace(/^#/, "");
try {
id = decodeURIComponent(id);
} catch {
// Keep the raw anchor if it cannot be decoded.
}
if (!id) {
return undefined;
}
const node = DocumentHelper.toProsemirror(document);
// Headings are always top-level nodes, so iterating the document's direct
// children is sufficient to locate the section.
const children: Node[] = [];
node.content.forEach((child) => children.push(child));
const previouslySeen: Record<string, number> = {};
let startIndex = -1;
let level = 0;
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (child.type.name !== "heading") {
continue;
}
// Calculate the heading id using the same de-duplication logic as the
// editor so that anchors to repeated headings resolve correctly.
const slug = headingToSlug(child);
const headingId =
previouslySeen[slug] > 0
? headingToSlug(child, previouslySeen[slug])
: slug;
previouslySeen[slug] =
previouslySeen[slug] !== undefined ? previouslySeen[slug] + 1 : 1;
if (startIndex === -1 && headingId === id) {
startIndex = i;
level = child.attrs.level;
}
}
if (startIndex === -1) {
return undefined;
}
const sectionNodes: Node[] = [children[startIndex]];
for (let i = startIndex + 1; i < children.length; i++) {
const child = children[i];
if (child.type.name === "heading" && child.attrs.level <= level) {
break;
}
sectionNodes.push(child);
}
const sectionDoc = schema.topNodeType.create(
null,
Fragment.fromArray(sectionNodes)
);
return serializer
.serialize(sectionDoc)
.replace(/(^|\n)\\(\n|$)/g, "\n\n")
.trim();
}
/**
* Returns the document as Markdown. This is a lossy conversion and should only be used for export.
*
* @param document The document or revision to convert
* @param options Options for the conversion
* @returns The document title and content as a Markdown string
*/
static async toMarkdown(
document: Document | Revision | Collection | ProsemirrorData,
options?: {
/** Whether to include the document title (default: true) */
includeTitle?: boolean;
/** Whether to sign attachment urls, and if so for how many seconds is the signature valid */
signedUrls?: number;
/** The team context */
teamId?: string;
/**
* Whether the Markdown is leaving Outline, in which case portable
* CommonMark is written in place of Outline's internal representation
* (default: false)
*/
commonMark?: boolean;
}
) {
let node = DocumentHelper.toProsemirror(document);
if (options?.signedUrls && options?.teamId) {
const data = await ProsemirrorHelper.signAttachmentUrls(
node,
options.teamId,
options.signedUrls
);
node = Node.fromJSON(schema, data);
}
const text = serializer
.serialize(node, { commonMark: options?.commonMark })
.replace(/(^|\n)\\(\n|$)/g, "\n\n")
.trim();
if (
(document instanceof Collection ||
document instanceof Document ||
document instanceof Revision) &&
options?.includeTitle !== false
) {
const iconType = determineIconType(document.icon);
const name =
document instanceof Collection ? document.name : document.title;
const title = `${iconType === IconType.Emoji ? document.icon + " " : ""}${name}`;
return `# ${title}\n\n${text}`;
}
return text;
}
/**
* Returns the document as plain HTML. This is a lossy conversion and should only be used for export.
*
* @param model The document or revision or collection to convert
* @param options Options for the HTML output
* @returns The document title and content as a HTML string
*/
static async toHTML(
model: Document | Revision | Collection,
options?: HTMLOptions
) {
const node = DocumentHelper.toProsemirror(model);
// Heading numbering is a preference of the document, which a revision
// inherits from the document it belongs to.
const document =
model instanceof Document
? model
: model instanceof Revision
? await model.$get("document")
: null;
let output = await ProsemirrorHelper.toHTML(node, {
title:
options?.includeTitle !== false
? model instanceof Collection
? model.name
: model.title
: undefined,
includeStyles: options?.includeStyles,
includeMermaid: options?.includeMermaid,
includeHead: options?.includeHead,
centered: options?.centered,
baseUrl: options?.baseUrl,
changes: options?.changes,
cspNonce: options?.cspNonce,
headingPrefix: document?.getPreference(DocumentPreference.HeadingPrefix),
});
addTags({
collectionId: model instanceof Collection ? model.id : undefined,
documentId: !(model instanceof Collection) ? model.id : undefined,
});
if (options?.signedUrls) {
const teamId =
model instanceof Collection ? model.teamId : document?.teamId;
if (!teamId) {
return output;
}
output = await TextHelper.attachmentsToSignedUrls(
output,
teamId,
typeof options.signedUrls === "number" ? options.signedUrls : undefined
);
}
return output;
}
/**
* Parse a list of mentions contained in a document or revision
*
* @param document Document or Revision
* @param options Attributes to use for filtering mentions
* @returns An array of mentions in passed document or revision
*/
static parseMentions(
document: Document | Revision,
options?: Partial<MentionAttrs>
) {
const node = DocumentHelper.toProsemirror(document);
return ProsemirrorHelper.parseMentions(node, options);
}
/**
* Parse a list of document IDs contained in a document or revision
*
* @param document Document or Revision
* @returns An array of identifiers in passed document or revision
*/
static parseDocumentIds(document: Document | Revision) {
const node = DocumentHelper.toProsemirror(document);
return ProsemirrorHelper.parseDocumentIds(node);
}
/**
* Generates a HTML diff between documents or revisions.
*
* @param before The before document
* @param after The after document
* @param options Options passed to HTML generation
* @returns The diff as a HTML string
*/
static async diff(
before: Document | Revision | null,
after: Revision,
options: HTMLOptions = {}
) {
addTags({
beforeId: before?.id,
documentId: after.documentId,
options,
});
if (!before) {
return await DocumentHelper.toHTML(after, options);
}
const beforeJSON = await DocumentHelper.toJSON(before);
const afterJSON = await DocumentHelper.toJSON(after);
const changeset = ChangesetHelper.getChangeset(afterJSON, beforeJSON);
return DocumentHelper.toHTML(after, {
...options,
changes: changeset ? changeset.changes : undefined,
});
}
/**
* Generates a compact HTML diff between documents or revisions, the
* diff is reduced up to show only the parts of the document that changed and
* the immediate context. Breaks in the diff are denoted with
* "div.diff-context-break" nodes.
*
* @param before The before document
* @param after The after document
* @param options Options passed to HTML generation
* @returns The diff as an HTML string, an empty string when there is no
* before document, or undefined when the documents contain no changes or
* the changeset was too expensive to compute.
*/
static async toEmailDiff(
before: Document | Revision | null,
after: Revision,
options?: HTMLOptions
): Promise<string | undefined> {
if (!before) {
return "";
}
addTags({
beforeId: before.id,
documentId: after.documentId,
options,
});
const beforeJSON = await DocumentHelper.toJSON(before);
const afterJSON = await DocumentHelper.toJSON(after);
const changeset = ChangesetHelper.getChangeset(afterJSON, beforeJSON);
// Without a changeset no diff elements can render, so skip the expensive
// HTML generation and clipping entirely.
if (!changeset?.changes.length) {
return undefined;
}
const html = await DocumentHelper.toHTML(after, {
...options,
changes: changeset.changes,
});
// Loaded lazily to keep jsdom off the startup path — only HTML export needs it.
const { JSDOM } = await import("jsdom");
const dom = new JSDOM(html);
try {
return DocumentHelper.clipEmailDiff(dom.window.document);
} finally {
try {
dom.window.close();
} catch (_err) {
// Best effort, closing the window releases its timers and resources.
}
}
}
/**
* Clips a rendered diff document down to only the changed nodes and their
* surrounding context, returning the resulting HTML or undefined when the
* document contains no diff elements.
*
* @param doc The rendered diff document to clip.
* @returns The clipped HTML, or undefined when there is nothing to show.
*/
private static clipEmailDiff(doc: JSDOM["window"]["document"]) {
const containsDiffElement = (node: Element | null) => {
if (!node) {
return false;
}
const diffClasses = [
EditorStyleHelper.diffInsertion,
EditorStyleHelper.diffDeletion,
EditorStyleHelper.diffModification,
EditorStyleHelper.diffNodeInsertion,
EditorStyleHelper.diffNodeDeletion,
EditorStyleHelper.diffNodeModification,
];
return diffClasses.some(
(className) =>
node.classList.contains(className) ||
node.querySelector(`.${className}`)
);
};
// The diffing lib isn't able to catch all changes currently, e.g. changing
// the type of a mark will result in an empty diff.
// see: https://github.com/tnwinc/htmldiff.js/issues/10
if (!containsDiffElement(doc.querySelector("#content"))) {
return;
}
// We use querySelectorAll to get a static NodeList as we'll be modifying
// it as we iterate, rather than getting content.childNodes.
const contents = doc.querySelectorAll("#content > *");
let previousNodeRemoved = false;
let previousDiffClipped = false;
const br = doc.createElement("div");
br.innerHTML = "…";
br.className = "diff-context-break";
for (const childNode of contents) {
// If the block node contains a diff tag then we want to keep it
if (containsDiffElement(childNode as Element)) {
if (previousNodeRemoved && previousDiffClipped) {
childNode.parentElement?.insertBefore(br.cloneNode(true), childNode);
}
previousNodeRemoved = false;
previousDiffClipped = true;
// Special case for largetables, as this block can get very large we
// want to clip it to only the changed rows and surrounding context.
if (childNode.classList.contains(EditorStyleHelper.table)) {
const rows = childNode.querySelectorAll("tr");
if (rows.length < 3) {
continue;
}
let previousRowRemoved = false;
let previousRowDiffClipped = false;
for (const row of rows) {
if (containsDiffElement(row)) {
const cells = row.querySelectorAll("td");
if (previousRowRemoved && previousRowDiffClipped) {
const tr = doc.createElement("tr");
const br = doc.createElement("td");
br.colSpan = cells.length;
br.innerHTML = "…";
br.className = "diff-context-break";
tr.appendChild(br);
childNode.parentElement?.insertBefore(tr, childNode);
}
previousRowRemoved = false;
previousRowDiffClipped = true;
continue;
}
if (containsDiffElement(row.nextElementSibling)) {
previousRowRemoved = false;
continue;
}
if (containsDiffElement(row.previousElementSibling)) {
previousRowRemoved = false;
continue;
}
previousRowRemoved = true;
row.remove();
}
}
continue;
}
// If the block node does not contain a diff tag and the previous
// block node did not contain a diff tag then remove the previous.
if (
childNode.nodeName === "P" &&
childNode.textContent &&
childNode.nextElementSibling?.nodeName === "P" &&
containsDiffElement(childNode.nextElementSibling)
) {
if (previousDiffClipped) {
childNode.parentElement?.insertBefore(br.cloneNode(true), childNode);
}
previousNodeRemoved = false;
continue;
}
if (
childNode.nodeName === "P" &&
childNode.textContent &&
childNode.previousElementSibling?.nodeName === "P" &&
containsDiffElement(childNode.previousElementSibling)
) {
previousNodeRemoved = false;
continue;
}
previousNodeRemoved = true;
childNode.remove();
}
const head = doc.querySelector("head");
const body = doc.querySelector("body");
return `${head?.innerHTML} ${body?.innerHTML}`;
}
/**
* Applies the given Markdown to the document, this essentially creates a
* single change in the collaborative state that makes all the edits to get
* to the provided Markdown.
*
* @param document The document to apply the changes to
* @param text The markdown to apply
* @param editMode The edit mode to use: "replace" (default), "append", "prepend", or "patch"
* @param findText The markdown text to find when using "patch" edit mode
* @returns The document
*/
static applyMarkdownToDocument(
document: Document,
text: string,
editMode: TextEditMode = TextEditMode.Replace,
findText?: string
) {
let doc: Node;
if (editMode === TextEditMode.Patch) {
if (!findText) {
throw ValidationError(
"findText is required when using patch edit mode"
);
}
const existingDoc = DocumentHelper.toProsemirror(document);
const { markdown, blockMap } =
serializer.serializeWithPositions(existingDoc);
const matchIndex = markdown.indexOf(findText);
if (matchIndex === -1) {
throw ValidationError(
"The specified text was not found in the document"
);
}
const matchEnd = matchIndex + findText.length;
// Find which top-level blocks overlap the matched range
const affected = blockMap.filter(
(b) => b.mdTo > matchIndex && b.mdFrom < matchEnd
);
if (affected.length === 0) {
throw ValidationError(
"Could not map the matched text to document content"
);
}
const pmFrom = affected[0].pmFrom;
const pmTo = affected[affected.length - 1].pmTo;
// Try a surgical patch that preserves sibling nodes and their rich
// content. Falls back to a full markdown re-parse of the affected
// blocks when a surgical patch is not possible.
const patch: PatchContext = {
markdown,
matchIndex,
matchEnd,
nodeMdFrom: affected[0].mdFrom,
nodeMdTo: affected[0].mdTo,
replacementText: text,
};
const surgicalResult =
affected.length === 1
? DocumentHelper.trySurgicalPatch(existingDoc, pmFrom, pmTo, patch)
: undefined;
if (surgicalResult) {
doc = surgicalResult;
} else {
const regionMdFrom = affected[0].mdFrom;
const regionMdTo = affected[affected.length - 1].mdTo;
const regionMarkdown = markdown.slice(regionMdFrom, regionMdTo);
const localMatchStart = matchIndex - regionMdFrom;
const localMatchEnd = matchEnd - regionMdFrom;
const modifiedRegion =
regionMarkdown.slice(0, localMatchStart) +
text +
regionMarkdown.slice(localMatchEnd);
const newContent = parser.parse(modifiedRegion);
const before = existingDoc.content.cut(0, pmFrom);
const after = existingDoc.content.cut(pmTo);
doc = existingDoc.copy(before.append(newContent.content).append(after));
}
} else if (editMode === TextEditMode.Append) {
const existingDoc = DocumentHelper.toProsemirror(document);
const newDoc = parser.parse(text);
const lastChild = existingDoc.lastChild;
const firstChild = newDoc.firstChild;
if (
!text.match(/^\s*\n/) &&
lastChild &&
firstChild &&
lastChild.type.name === "paragraph" &&
firstChild.type.name === "paragraph"
) {
const mergedPara = lastChild.copy(
lastChild.content.append(firstChild.content)
);
doc = existingDoc.copy(
existingDoc.content
.cut(0, existingDoc.content.size - lastChild.nodeSize)
.append(Fragment.from(mergedPara))
.append(newDoc.content.cut(firstChild.nodeSize))
);
} else {
doc = existingDoc.copy(existingDoc.content.append(newDoc.content));
}
} else if (editMode === TextEditMode.Prepend) {
const existingDoc = DocumentHelper.toProsemirror(document);
const newDoc = parser.parse(text);
const lastChild = newDoc.lastChild;
const firstChild = existingDoc.firstChild;
if (
!text.match(/\n\s*$/) &&
lastChild &&
firstChild &&
lastChild.type.name === "paragraph" &&
firstChild.type.name === "paragraph"
) {
const mergedPara = lastChild.copy(
lastChild.content.append(firstChild.content)
);
doc = existingDoc.copy(
newDoc.content
.cut(0, newDoc.content.size - lastChild.nodeSize)
.append(Fragment.from(mergedPara))
.append(existingDoc.content.cut(firstChild.nodeSize))
);
} else {
doc = existingDoc.copy(newDoc.content.append(existingDoc.content));
}
} else {
doc = parser.parse(text);
}
document.content = doc.toJSON();
document.text = serializer.serialize(doc);
if (document.state) {
const ydoc = new Y.Doc();
Y.applyUpdate(ydoc, document.state);
const type = ydoc.get("default", Y.XmlFragment) as Y.XmlFragment;
if (!type.doc) {
throw new Error("type.doc not found");
}
// apply new document to existing ydoc
updateYFragment(type.doc, type, doc, {
mapping: new Map(),
isOMark: new Map(),
});
const state = Y.encodeStateAsUpdate(ydoc);
document.state = Buffer.from(state);
document.changed("state", true);
}
return document;
}
/**
* Attempt a surgical patch on a single affected top-level block. For
* textblocks this does an inline replacement. For container nodes (lists,
* blockquotes, etc.) it re-parses the container markdown with the
* modification and merges with the original to preserve rich content in
* unchanged children.
*
* @param existingDoc The full ProseMirror document.
* @param pmFrom Start of the affected block in the document content.
* @param pmTo End of the affected block in the document content.
* @param patch The patch context.
* @returns A new document Node on success, or undefined.
*/
private static trySurgicalPatch(
existingDoc: Node,
pmFrom: number,
pmTo: number,
patch: PatchContext
): Node | undefined {
const blockNode = existingDoc.nodeAt(pmFrom);
if (!blockNode) {
return undefined;
}
const patchedBlocks = DocumentHelper.patchNode(blockNode, patch);
if (!patchedBlocks) {
return undefined;
}
const before = existingDoc.content.cut(0, pmFrom);
const after = existingDoc.content.cut(pmTo);
return existingDoc.copy(before.append(patchedBlocks).append(after));
}
/**
* Recursively patch a single node. For textblocks, performs an inline
* replacement. For container nodes, re-parses the container markdown with
* the modification applied and preserves rich content in unchanged
* children. The replacement may split the container or introduce blocks
* that cannot live inside it, so the result is a fragment of one or more
* top-level blocks.
*
* @param node The node to patch.
* @param patch The patch context.
* @returns The blocks that replace the node, or undefined to fall back.
*/
private static patchNode(
node: Node,
patch: PatchContext
): Fragment | undefined {
if (node.isTextblock) {
const patched = DocumentHelper.tryInlinePatch(node, patch);
return patched ? Fragment.from(patched) : undefined;
}
const {
markdown,
matchIndex,
matchEnd,
nodeMdFrom,
nodeMdTo,
replacementText,
} = patch;
// Container node (list, blockquote, etc.): re-parse the container's
// markdown with the modification applied, then merge with the original
// to preserve rich content (comment marks, highlight colors, etc.) in
// children whose text content did not change.
const containerMd = markdown.slice(nodeMdFrom, nodeMdTo);
const localStart = matchIndex - nodeMdFrom;
const localEnd = matchEnd - nodeMdFrom;
const modifiedMd =
containerMd.slice(0, localStart) +
replacementText +
containerMd.slice(localEnd);
const parsed = DocumentHelper.joinAdjacentLists(
parser.parse(modifiedMd.replace(/^\n+/, ""))
);
const blocks = DocumentHelper.childrenOf(parsed);
const containerIndex = blocks.findIndex(
(child) => child.type === node.type
);
// The container itself is gone, there is no rich content to preserve so
// the plain region re-parse in the caller is sufficient.
if (containerIndex === -1) {
return undefined;
}
// Parse the original (unmodified) container markdown to get a round-trip
// baseline. This lets mergeNodes distinguish attrs that were intentionally
// changed by the modification from attrs lost during markdown round-trip.
const originalParsed = DocumentHelper.joinAdjacentLists(
parser.parse(containerMd.replace(/^\n+/, ""))
);
const roundTripped = DocumentHelper.findChildOfType(
originalParsed,
node.type
);
blocks[containerIndex] = DocumentHelper.mergeNodes(
node,
blocks[containerIndex],
roundTripped
);
return Fragment.from(blocks);
}
/**
* Join adjacent lists of the same kind into one, at every depth. Markdown
* starts a new list when the marker or delimiter changes, but the
* serializer normalizes both so such a change inside a patch must not split
* the list. The start number of a split fragment only continues the
* numbering, so it is ignored; lists that differ in any other attr, such
* as a numeric list next to an alpha list, are kept separate.
*
* @param node The parsed node.
* @returns The node with adjacent matching lists joined.
*/
private static joinAdjacentLists(node: Node): Node {
if (node.isTextblock || node.isLeaf) {
return node;
}
const isSameList = (a: Node, b: Node) =>
a.type === b.type &&
a.type.isInGroup("list") &&
isEqual(omit(a.attrs, ["order"]), omit(b.attrs, ["order"]));
const children = DocumentHelper.childrenOf(node).reduce<Node[]>(
(joined, child) => {
const current = DocumentHelper.joinAdjacentLists(child);
const previous = joined[joined.length - 1];
if (previous && isSameList(previous, current)) {
joined[joined.length - 1] = previous.copy(
previous.content.append(current.content)
);
} else {
joined.push(current);
}
return joined;
},
[]
);
return node.copy(Fragment.from(children));
}
/**
* Collect the direct children of a node into an array.
*
* @param node The parent node.
* @returns The child nodes in document order.
*/
private static childrenOf(node: Node): Node[] {
const children: Node[] = [];
node.forEach((child: Node) => children.push(child));
return children;
}
/**
* Find the first child of a parsed document that matches the given type.
*
* @param doc The parsed document to search.
* @param type The node type to find.
* @returns The first matching child, or undefined.
*/
private static findChildOfType(doc: Node, type: NodeType): Node | undefined {
return DocumentHelper.childrenOf(doc).find((child) => child.type === type);
}
/**
* Recursively merge two structurally similar nodes. Children whose text
* content is unchanged are kept from the original (preserving attributes
* that cannot be represented in markdown, such as comment marks or
* highlight colors). Children whose content changed use the updated version.
* Children may have been added or removed; the runs at the start and end
* that match the round-trip baseline anchor the merge so only the changed
* middle is compared pairwise.
*
* @param original The original node with rich content to preserve.
* @param updated The re-parsed node with the modification applied.
* @param roundTripped The original node after a markdown round-trip, used
* to distinguish intentional attr changes from round-trip losses.
* @returns The merged node.
*/
private static mergeNodes(
original: Node,
updated: Node,
roundTripped?: Node
): Node {
if (original.isTextblock || original.isLeaf) {
return updated;
}
const oldChildren = DocumentHelper.childrenOf(original);
const newChildren = DocumentHelper.childrenOf(updated);
const rtChildren = roundTripped
? DocumentHelper.childrenOf(roundTripped)
: [];
// Children that equal the round-trip baseline were not touched by the
// patch. Only align on them when the baseline mirrors the original.
const maxShared =
rtChildren.length === oldChildren.length
? Math.min(oldChildren.length, newChildren.length)
: 0;
let prefix = 0;
while (prefix < maxShared && newChildren[prefix].eq(rtChildren[prefix])) {
prefix++;
}
let suffix = 0;
while (
suffix < maxShared - prefix &&
newChildren[newChildren.length - 1 - suffix].eq(
rtChildren[rtChildren.length - 1 - suffix]
)
) {
suffix++;
}
const merged = [
...oldChildren.slice(0, prefix),
...DocumentHelper.mergeChildren(
oldChildren.slice(prefix, oldChildren.length - suffix),
newChildren.slice(prefix, newChildren.length - suffix),
rtChildren.slice(prefix, rtChildren.length - suffix)
),
...oldChildren.slice(oldChildren.length - suffix),
];
// Merge container attrs so markdown-driven changes (e.g. ordered list
// order/listStyle) are applied while preserving non-markdown attrs.
const mergedAttrs = DocumentHelper.mergeAttrs(
original,
updated,
roundTripped
);
return original.type.create(
mergedAttrs,
Fragment.from(merged),
original.marks
);
}
/**
* Merge two child lists pairwise. When the lists differ in length or a
* pair differs in type there is no positional correspondence, so the
* re-parsed children are used as-is.
*
* @param oldChildren The original children with rich content to preserve.
* @param newChildren The re-parsed children with the modification applied.
* @param rtChildren The original children after a markdown round-trip.
* @returns The merged children.
*/
private static mergeChildren(
oldChildren: Node[],
newChildren: Node[],
rtChildren: Node[]
): Node[] {
if (oldChildren.length !== newChildren.length) {
return newChildren;
}
const merged: Node[] = [];
for (let i = 0; i < oldChildren.length; i++) {
const oldChild = oldChildren[i];
const newChild = newChildren[i];
const rtChild = rtChildren[i];
if (oldChild.type !== newChild.type) {
return newChildren;
}
const textSame = oldChild.textContent === newChild.textContent;
if (textSame && oldChild.sameMarkup(newChild)) {
// Compare against the round-tripped baseline: when the
// updated child is identical to a plain round-trip of the original,
// the patch did not touch it
if (!rtChild || newChild.eq(rtChild)) {
merged.push(oldChild);
} else if (!oldChild.isTextblock && !oldChild.isLeaf) {
// Container child changed deeper down — recurse to preserve rich
// content in the parts that did not change.
merged.push(DocumentHelper.mergeNodes(oldChild, newChild, rtChild));
} else {
merged.push(newChild);
}
} else if (textSame) {
// Attrs changed (e.g. checked state) but content same — merge attrs
// so that non-markdown-representable values (colwidth, highlight
// colors, etc.) are preserved from the original while intentional
// changes from the re-parsed version are applied.
const mergedAttrs = DocumentHelper.mergeAttrs(
oldChild,
newChild,
rtChild
);
merged.push(
oldChild.type.create(mergedAttrs, oldChild.content, oldChild.marks)
);
} else if (!oldChild.isTextblock && !oldChild.isLeaf) {
// Both are containers — recurse to preserve rich content deeper
merged.push(DocumentHelper.mergeNodes(oldChild, newChild, rtChild));
} else {
merged.push(newChild);
}
}
return merged;
}
/**
* Merge attrs from an original and re-parsed node. When a round-tripped
* baseline is available, attrs whose updated value matches the round-trip
* value are considered unchanged (possibly lost in the round-trip) and the
* original is preserved. Attrs that differ from the round-trip baseline
* were intentionally changed and the updated value is used.
*
* @param original The original node with potentially rich attrs.
* @param updated The re-parsed node with the modification applied.
* @param roundTripped The original node after a markdown round-trip.
* @returns The merged attrs object.
*/
private static mergeAttrs(
original: Node,
updated: Node,
roundTripped?: Node
): Record<string, unknown> {
if (!roundTripped) {
return updated.attrs;
}
const result: Record<string, unknown> = {};
for (const key of Object.keys(original.attrs)) {
const newVal = updated.attrs[key];
const oldVal = original.attrs[key];
const rtVal = roundTripped.attrs[key];
// If the updated value matches what a round-trip of the original
// produces, the modification did not change this attr — preserve the
// original (which may have richer data lost in markdown round-trip).
if (JSON.stringify(newVal) === JSON.stringify(rtVal)) {
result[key] = oldVal;
} else {
result[key] = newVal;
}
}
return result;
}
/**
* Attempt an inline-level patch within a single textblock node. Returns the
* patched block node on success, or undefined if an inline patch is not
* possible and the caller should fall back to block-level replacement.
*
* @param blockNode The textblock node containing the match.
* @param patch The patch context.
* @returns The patched block node, or undefined.
*/
private static tryInlinePatch(
blockNode: Node,
patch: PatchContext
): Node | undefined {
const {
markdown,
matchIndex,
matchEnd,
nodeMdFrom,
nodeMdTo,
replacementText,
} = patch;
// Strip the leading block separator (newlines) to get the block's own
// markdown content and the offset of that content within the full string.
const blockMdRaw = markdown.slice(nodeMdFrom, nodeMdTo);
const separatorLen =
blockMdRaw.length - blockMdRaw.replace(/^\n+/, "").length;
const contentMdStart = nodeMdFrom + separatorLen;
// Positions of the match relative to the block's content markdown.
const localMdFrom = matchIndex - contentMdStart;
const localMdTo = matchEnd - contentMdStart;
if (localMdFrom < 0) {
return undefined;
}
// Build a map from text-content offset to PM Fragment offset by walking
// the block's inline children. For text nodes each character maps 1:1;
// for atom inline nodes (images, mentions) the nodeSize may differ from
// the text they contribute.
const blockText = blockNode.textContent;
const segments: InlineSegment[] = [];
let textOffset = 0;
blockNode.forEach((child: Node, offset: number) => {
const childTextLen = child.isText
? child.text!.length
: child.type.spec.leafText
? (child.type.spec.leafText as (n: Node) => string)(child).length
: 0;
segments.push({
textFrom: textOffset,
textTo: textOffset + childTextLen,
pmFrom: offset,
pmTo: offset + child.nodeSize,
isAtom: !child.isText && childTextLen !== child.nodeSize,
});
textOffset += childTextLen;
});
// Map the match to text-content positions. When the block's markdown
// equals its plain text, markdown offsets map 1:1. When they differ
// (atoms like mentions, or formatting marks), locate the match in the
// block's textContent directly.
let localTextFrom = localMdFrom;
let localTextTo = localMdTo;
const contentMd = markdown.slice(
contentMdStart,
contentMdStart + blockText.length
);
if (contentMd !== blockText) {
const findStr = markdown.slice(matchIndex, matchEnd);
const textIdx = blockText.indexOf(findStr);
if (textIdx < 0) {
return undefined;
}
localTextFrom = textIdx;
localTextTo = textIdx + findStr.length;
}
// Atom inline nodes (mentions, images) have text representations that
// don't map 1:1 to PM offsets. Only bail when atoms overlap the match
// range — atoms outside the range are safely preserved by the splice.
const hasOverlappingAtom = segments.some(
(seg) =>
seg.isAtom && seg.textTo > localTextFrom && seg.textFrom < localTextTo
);
if (hasOverlappingAtom) {
return undefined;
}
// Resolve text-content positions to PM Fragment positions.
const pmInlineFrom = DocumentHelper.textToPmOffset(segments, localTextFrom);
const pmInlineTo = DocumentHelper.textToPmOffset(segments, localTextTo);
if (pmInlineFrom < 0 || pmInlineTo < 0) {
return undefined;
}
// Parse the replacement markdown and extract inline content only when it
// resolves to a single textblock. Multi-block or non-textblock content
// should fall back to block-level replacement rather than being silently
// truncated during inline patching. Markdown parsing can trim whitespace,
// so when the parsed result is plain text we use the raw replacement
// string to preserve exact whitespace.
const parsed = parser.parse(replacementText);
const firstBlock = parsed.firstChild;
if (parsed.childCount !== 1 || !firstBlock?.isTextblock) {
return undefined;
}
let replacementContent: Fragment;
if (
firstBlock.content.childCount === 1 &&
firstBlock.firstChild?.isText &&
!firstBlock.firstChild.marks.length
) {
// Plain text replacement — use the raw string to avoid whitespace trimming
replacementContent = Fragment.from(schema.text(replacementText));
} else {
replacementContent = firstBlock.content;
}
// Splice: keep inline content before match + replacement + after match.
const inlineBefore = blockNode.content.cut(0, pmInlineFrom);
const inlineAfter = blockNode.content.cut(pmInlineTo);
return blockNode.copy(
inlineBefore.append(replacementContent).append(inlineAfter)
);
}
/**
* Convert a text-content offset to a ProseMirror Fragment offset using a
* pre-built segment map.
*
* @param segments The segment map from text offsets to PM offsets.
* @param textPos The text-content offset to convert.
* @returns The corresponding PM Fragment offset, or -1.
*/
private static textToPmOffset(
segments: InlineSegment[],
textPos: number
): number {
for (const seg of segments) {
if (textPos >= seg.textFrom && textPos <= seg.textTo) {
return seg.pmFrom + (textPos - seg.textFrom);
}
}
if (segments.length > 0) {
const last = segments[segments.length - 1];
if (textPos >= last.textTo) {
return last.pmTo;
}
}
return -1;
}
/**
* Compares two documents or revisions and returns whether the text differs by more than the threshold.
*
* @param document The document to compare
* @param other The other document to compare
* @param threshold The threshold for the change in characters
* @returns True if the text differs by more than the threshold
*/
public static isChangeOverThreshold(
before: Document | Revision | null,
after: Document | Revision | null,
threshold: number
) {
if (!before || !after) {
return false;
}
const first = before.title + this.toPlainText(before);
const second = after.title + this.toPlainText(after);
const distance = ukkonen(first, second, threshold + 1);
return distance > threshold;
}
/**
* Sorts an array of documents based on their order in the collection's document structure.
* Documents are ordered according to their position in the navigation structure, with
* documents not found in the structure placed at the end. The result is reversed to
* account for documents being added in reverse order during processing.
*
* @param documents - Array of Document objects to be sorted
* @param documentStructure - Array of NavigationNode objects representing the collection's document hierarchy
* @returns Sorted array of documents in the order they appear in the document structure
*
**/
public static sortDocumentsByStructure(
documents: Document[],
documentStructure: NavigationNode[]
): Document[] {
if (!documentStructure.length) {
return documents;
}
const orderMap = new Map<string, number>();
documentStructure.forEach((node, index) => {
orderMap.set(node.id, index);
});
return documents.sort((a, b) => {
const orderA = orderMap.get(a.id) ?? Number.MAX_SAFE_INTEGER;
const orderB = orderMap.get(b.id) ?? Number.MAX_SAFE_INTEGER;
return orderA - orderB;
});
}
/** Prosemirror nodes memoized against the content or state they were parsed from. */
private static prosemirrorCache = new WeakMap<object, Node>();
/** Comment marks memoized against the document body they were parsed from. */
private static commentMarksCache = new WeakMap<object, CommentMark[]>();
}