From 5ab9fc9aa7abd66d0aa5697bb46cc9529474643c Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sun, 29 Nov 2026 10:04:09 -0500 Subject: [PATCH] perf: Speed up Markdown serialization (#14801) * perf: Speed up Markdown serialization * Inline link bracket escaping into esc * Cache mark specs with a markSpec method --- shared/editor/lib/ExtensionManager.ts | 6 +- shared/editor/lib/markdown/serializer.ts | 92 +++++++++++++++++------- shared/editor/nodes/Paragraph.ts | 6 +- 3 files changed, 69 insertions(+), 35 deletions(-) diff --git a/shared/editor/lib/ExtensionManager.ts b/shared/editor/lib/ExtensionManager.ts index a06d8794fa..b9bccc5dea 100644 --- a/shared/editor/lib/ExtensionManager.ts +++ b/shared/editor/lib/ExtensionManager.ts @@ -114,8 +114,7 @@ export default class ExtensionManager { .filter((extension) => extension.type === "node") .map((extension: Node) => [ extension.name, - (...args: Parameters) => - extension.toMarkdown(...args), + extension.toMarkdown.bind(extension), ]) ); @@ -124,8 +123,7 @@ export default class ExtensionManager { .filter((extension) => extension.type === "mark") .map((extension: Mark) => [ extension.name, - (...args: Parameters) => - extension.toMarkdown(...args), + extension.toMarkdown.bind(extension), ]) ); diff --git a/shared/editor/lib/markdown/serializer.ts b/shared/editor/lib/markdown/serializer.ts index 57184f4039..6c216a1ed9 100644 --- a/shared/editor/lib/markdown/serializer.ts +++ b/shared/editor/lib/markdown/serializer.ts @@ -82,6 +82,12 @@ export class MarkdownSerializer { } } +// Matches strings that contain a character escaped anywhere in a line. +const escapeCharsTest = /[`*\\~]/; + +// Matches strings that begin with syntax only special at the start of a line. +const startOfLineTest = /^(?:[:#\-*+]|\d+\.(?=\s|$)|[a-z]\.(?=\s))/i; + // Tracks whether we have already warned about direct assignment to `out`, // so a hot loop cannot flood the console. let warnedDirectOutAssignment = false; @@ -111,6 +117,7 @@ export class MarkdownSerializerState { lastChar = ""; options: Options; blockMap = null; + markSpecs = new Map(); // The serialized output so far. Use `append` to add to it — direct // assignment still works but reads the last character back out of the @@ -235,6 +242,10 @@ export class MarkdownSerializerState { // Add the given text to the document. When escape is not `false`, // it will be escaped. text(text, escape) { + if (text.indexOf("\n") === -1) { + this.textLine(text, escape); + return; + } const lines = text.split("\n"); for (let i = 0; i < lines.length; i++) { // A
in a table cell becomes a new line when the cell is parsed. @@ -252,6 +263,16 @@ export class MarkdownSerializerState { } } + // Add a single line of text, see `text`. + textLine(line, escape) { + const startOfLine = + this.atBlank() || + this.closed || + (this.inTable && this.out.endsWith("
")); + this.write(); + this.append(escape !== false ? this.esc(line, startOfLine) : line); + } + // :: (Node) // Render the given node as a block. render(node, parent, index) { @@ -292,6 +313,12 @@ export class MarkdownSerializerState { const active = []; let trailing = ""; const progress = (node, _, index) => { + // Fast path for unmarked content between unmarked content. + if (node && !node.marks.length && !active.length && !trailing) { + this.render(node, parent, index); + return; + } + let marks = node ? node.marks : []; // Remove marks from `hard_break` that are the last node inside @@ -319,7 +346,7 @@ export class MarkdownSerializerState { node && node.isText && marks.some((mark) => { - const info = this.marks[mark.type.name](); + const info = this.markSpec(mark.type.name); return info && info.expelEnclosingWhitespace; }) ) { @@ -338,7 +365,7 @@ export class MarkdownSerializerState { } const inner = marks.length && marks[marks.length - 1], - noEsc = inner && this.marks[inner.type.name]().escape === false; + noEsc = inner && this.markSpec(inner.type.name).escape === false; const len = marks.length - (noEsc ? 1 : 0); // Try to reorder 'mixable' marks, such as em and strong, which @@ -347,12 +374,12 @@ export class MarkdownSerializerState { // active. outer: for (let i = 0; i < len; i++) { const mark = marks[i]; - if (!this.marks[mark.type.name]().mixable) { + if (!this.markSpec(mark.type.name).mixable) { break; } for (let j = 0; j < active.length; j++) { const other = active[j]; - if (!this.marks[other.type.name]().mixable) { + if (!this.markSpec(other.type.name).mixable) { break; } if (mark.eq(other)) { @@ -505,6 +532,7 @@ export class MarkdownSerializerState { this.options ); cellState.inTable = true; + cellState.markSpecs = this.markSpecs; cellState.inList = this.inList; cellState.inTightList = this.inTightList; @@ -514,20 +542,17 @@ export class MarkdownSerializerState { } if ( - !( - cellNode.textContent === "" && - cellNode.content.size === 0 && - cellNode.type.name === "paragraph" - ) + !(cellNode.content.size === 0 && cellNode.type.name === "paragraph") ) { cellState.closed = false; cellState.render(cellNode, row, j); } }); - const content = cellState.out - .replace(/^\n+|\n+$/g, "") - .replace(/\n/g, "
"); + const content = + cellState.out.indexOf("\n") === -1 + ? cellState.out + : cellState.out.replace(/^\n+|\n+$/g, "").replace(/\n/g, "
"); this.append(content); // Pad to column width @@ -564,27 +589,31 @@ export class MarkdownSerializerState { // content. If `startOfLine` is true, also escape characters that // has special meaning only at the start of the line. esc(str = "", startOfLine) { - str = str.replace(/[`*\\~]/g, "\\$&"); + if (escapeCharsTest.test(str)) { + str = str.replace(/[`*\\~]/g, "\\$&"); + } // Only escape an opening square bracket when the same line later contains a // `](`, meaning it could otherwise be parsed as an inline link or image - str = str - .split("\n") - .map((line) => { - const last = line.lastIndexOf("]("); - if (last === -1) { - return line; - } - return line.slice(0, last).replace(/\[/g, "\\$&") + line.slice(last); - }) - .join("\n"); - if (startOfLine) { + if (str.indexOf("](") !== -1) { + str = str + .split("\n") + .map((line) => { + const last = line.lastIndexOf("]("); + if (last === -1) { + return line; + } + return line.slice(0, last).replace(/\[/g, "\\$&") + line.slice(last); + }) + .join("\n"); + } + if (startOfLine && startOfLineTest.test(str)) { str = str .replace(/^[:#\-*+]/, "\\$&") .replace(/^(\d+)\.(?=\s|$)/, "$1\\.") .replace(/^([a-z])\.(?=\s)/i, "$1\\."); } - if (this.inTable) { + if (this.inTable && str.indexOf("|") !== -1) { str = str.replace(/\|/gi, "\\$&"); } @@ -607,10 +636,21 @@ export class MarkdownSerializerState { return out; } + // Get the serializer spec for a mark type. Specs are static, so each is + // built once per serialization rather than on every lookup. + markSpec(name) { + let spec = this.markSpecs.get(name); + if (!spec) { + spec = this.marks[name](); + this.markSpecs.set(name, spec); + } + return spec; + } + // : (Mark, bool, string?) → string // Get the markdown string for a given opening or closing mark. markString(mark, open, parent, index) { - const info = this.marks[mark.type.name](); + const info = this.markSpec(mark.type.name); const value = open ? info.open : info.close; return typeof value === "string" ? value : value(this, mark, parent, index); } diff --git a/shared/editor/nodes/Paragraph.ts b/shared/editor/nodes/Paragraph.ts index 6b91cee92d..ebda0cb316 100644 --- a/shared/editor/nodes/Paragraph.ts +++ b/shared/editor/nodes/Paragraph.ts @@ -53,11 +53,7 @@ export default class Paragraph extends Node { toMarkdown(state: MarkdownSerializerState, node: ProsemirrorNode) { // render empty paragraphs as hard breaks to ensure that newlines are // persisted between reloads (this breaks from markdown tradition) - if ( - node.textContent.trim() === "" && - node.childCount === 0 && - !state.inTable - ) { + if (node.childCount === 0 && !state.inTable) { state.write(state.options.commonMark ? "\n" : "\\\n"); } else { state.renderInline(node);