An open source design system that's fully customizable and agent ready
TypeScript
fix(richtext): read backslash escapes as core Markdown does, and keep backslashes in code (#7048)
Cindy Zhangf6c5c7c90641
diff --git a/packages/richtext/src/markdownCharacterReferences.ts b/packages/richtext/src/markdownCharacterReferences.tsindex 2ff4f18815..c58792d241 100644--- a/packages/richtext/src/markdownCharacterReferences.ts+++ b/packages/richtext/src/markdownCharacterReferences.ts@@ -4,10 +4,12 @@* @file markdownCharacterReferences.ts* @input Uses lexical, @lexical/link, @lexical/code, and core Markdown's* decodeMarkdownCharacterReferences.- * @output Exports protectCharacterReferences, which swaps every character- * reference in Markdown source for a private-use stand-in before Lexical- * imports it, and $restoreCharacterReferences, which puts the decoded text- * in place of the stand-ins afterwards.+ * @output Exports protectBackslashEscapes, protectLinkDestinationParentheses,+ * and protectCharacterReferences, which swap every backslash escape, every+ * parenthesis inside a link destination, and every character reference in+ * Markdown source for a private-use stand-in before Lexical imports it, and+ * $restoreCharacterReferences, which puts the literal or decoded text in+ * place of the stand-ins afterwards.* @position Used by importMarkdownKeepingSource (markdownSource.ts), so every* block — paragraphs, headings, lists, quotes, table cells, link text and* destinations — decodes references with the one decoder core Markdown@@ -16,6 +18,12 @@* Markdown import, so a decoded `*` never starts emphasis, and no `&#digits;`* reaches Lexical's own decoding, which ignores escapes and throws on a* number past Unicode. Code keeps references as written.+ * Backslash escapes go through the same way, so an escaped character is+ * literal text wherever it is — `\[x](y)` is text, not a link, as in core+ * Markdown (spec:AST-061 FR7, spec:AST-062 FR3) — and code keeps its+ * backslashes. Parentheses inside a link destination go through the same+ * way, so Lexical, which reads none in a destination, reads balanced ones+ * as core does.*/import {$isCodeNode} from '@lexical/code';@@ -28,10 +36,15 @@ import {} from 'lexical';import {decodeMarkdownCharacterReferences} from '@astryxdesign/core/Markdown/parser';-/** What a stand-in replaced: a reference as written, or an escaped `&`. */+/**+ * What a stand-in replaced: a reference as written, an escaped `&`, or a+ * backslash-escaped character.+ */type StandIn =| {readonly kind: 'reference'; readonly source: string}- | {readonly kind: 'ampersand'};+ | {readonly kind: 'ampersand'}+ | {readonly kind: 'escape'; readonly character: string}+ | {readonly kind: 'backslash'};export interface ProtectedMarkdown {/** The source with stand-ins in place of references. */@@ -175,6 +188,165 @@ function codeRanges(text: string): Array<readonly [number, number]> {return ranges.sort((a, b) => a[0] - b[0]);}+/** The characters a backslash escapes (CommonMark 0.31 §2.4). */+const ESCAPABLE = new Set('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~');++/**+ * Returns `markdown` with every backslash escape outside code — a backslash+ * before ASCII punctuation — replaced by a private-use stand-in for the+ * escaped character, and every backslash in code by a stand-in for itself,+ * which Lexical would otherwise drop from a code span — except before `|`,+ * which a table reads before its code. A backslash before anything else+ * outside code stays as written. One pass over the source.+ */+export function protectBackslashEscapes(markdown: string): ProtectedMarkdown {+ const standIns = new Map<string, StandIn>();+ if (!markdown.includes('\\')) {+ return {markdown, standIns};+ }+ const available = absentCharacters(markdown);+ const byKey = new Map<string, string>();+ const standInFor = (key: string, value: StandIn): string | null => {+ const existing = byKey.get(key);+ if (existing != null) {+ return existing;+ }+ const next = available.next();+ if (next.done === true) {+ // Every private-use character is in the text: leave the rest as+ // written.+ return null;+ }+ byKey.set(key, next.value);+ standIns.set(next.value, value);+ return next.value;+ };+ const code = codeRanges(markdown);+ let output = '';+ let copied = 0;+ let codeIndex = 0;+ let index = markdown.indexOf('\\');+ while (index !== -1) {+ while (code[codeIndex] != null && code[codeIndex][1] <= index) {+ codeIndex++;+ }+ const range = code[codeIndex];+ const character = markdown[index + 1];+ const inCode = range != null && range[0] <= index;+ // A table splits its cells before it reads code, so `\|` in code is the+ // table's to read.+ if (inCode && character === '|') {+ index = markdown.indexOf('\\', index + 2);+ continue;+ }+ const isEscape = !inCode && character != null && ESCAPABLE.has(character);+ if (inCode || isEscape) {+ const standIn = inCode+ ? standInFor('code', {kind: 'backslash'})+ : standInFor(`escape:${character}`, {+ kind: 'escape',+ character: character ?? '',+ });+ if (standIn == null) {+ break;+ }+ output += markdown.slice(copied, index) + standIn;+ copied = index + (inCode ? 1 : 2);+ index = markdown.indexOf('\\', copied);+ continue;+ }+ index = markdown.indexOf('\\', index + 1);+ }+ return {markdown: output + markdown.slice(copied), standIns};+}++/**+ * Returns `markdown` with every parenthesis inside an inline link+ * destination — between the destination's own parentheses, balanced, as core+ * Markdown and CommonMark read them — replaced by a private-use stand-in for+ * itself, outside code. Run after protectBackslashEscapes, so an escaped+ * parenthesis is already a stand-in and never counts toward the balance.+ */+export function protectLinkDestinationParentheses(+ markdown: string,+): ProtectedMarkdown {+ const standIns = new Map<string, StandIn>();+ if (!markdown.includes('](')) {+ return {markdown, standIns};+ }+ const available = absentCharacters(markdown);+ const byCharacter = new Map<string, string>();+ const standInFor = (character: '(' | ')'): string | null => {+ const existing = byCharacter.get(character);+ if (existing != null) {+ return existing;+ }+ const next = available.next();+ if (next.done === true) {+ return null;+ }+ byCharacter.set(character, next.value);+ standIns.set(next.value, {kind: 'escape', character});+ return next.value;+ };+ const code = codeRanges(markdown);+ const inner: Array<number> = [];+ let codeIndex = 0;+ let index = markdown.indexOf('](');+ while (index !== -1) {+ while (code[codeIndex] != null && code[codeIndex][1] <= index) {+ codeIndex++;+ }+ const range = code[codeIndex];+ if (range != null && range[0] <= index) {+ index = markdown.indexOf('](', range[1]);+ continue;+ }+ // The destination's own parentheses are depth one; any inside it are+ // deeper. A space at depth one ends the destination (a title follows);+ // a space deeper, or no closing parenthesis, means no link.+ const parentheses: Array<number> = [];+ let depth = 1;+ let position = index + 2;+ let isLink = markdown[position] !== '<';+ for (; isLink && position < markdown.length; position++) {+ const character = markdown[position];+ if (/\s/.test(character)) {+ isLink = depth === 1;+ break;+ }+ if (character === '(') {+ depth++;+ parentheses.push(position);+ } else if (character === ')') {+ depth--;+ if (depth === 0) {+ break;+ }+ parentheses.push(position);+ }+ }+ if (isLink && depth <= 1) {+ inner.push(...parentheses);+ }+ index = markdown.indexOf('](', position + 1);+ }+ if (inner.length === 0) {+ return {markdown, standIns};+ }+ let output = '';+ let copied = 0;+ for (const position of inner) {+ const standIn = standInFor(markdown[position] as '(' | ')');+ if (standIn == null) {+ break;+ }+ output += markdown.slice(copied, position) + standIn;+ copied = position + 1;+ }+ return {markdown: output + markdown.slice(copied), standIns};+}+/*** Returns `markdown` with every character reference outside code replaced by* a private-use stand-in that occurs nowhere else in it, and the escaped `&`@@ -283,17 +455,36 @@ function restored(return changed ? output : text;}-const decoded = (standIn: StandIn): string =>- standIn.kind === 'ampersand'- ? '&'- : decodeMarkdownCharacterReferences(standIn.source);-const asWritten = (standIn: StandIn): string =>- standIn.kind === 'ampersand' ? '&' : standIn.source;+const decoded = (standIn: StandIn): string => {+ switch (standIn.kind) {+ case 'ampersand':+ return '&';+ case 'backslash':+ return '\\';+ case 'escape':+ return standIn.character;+ case 'reference':+ return decodeMarkdownCharacterReferences(standIn.source);+ }+};+const asWritten = (standIn: StandIn): string => {+ switch (standIn.kind) {+ case 'ampersand':+ return '&';+ case 'backslash':+ return '\\';+ case 'escape':+ return `\\${standIn.character}`;+ case 'reference':+ return standIn.source;+ }+};/*** Replaces the stand-ins under `node` with the characters their references- * name — or, in code Lexical read as code, with the references as written —- * in text, link destinations, and link titles. One pass over the text.+ * name or their escapes stand for — or, in code Lexical read as code, with+ * the references and escapes as written — in text, link destinations, and+ * link titles. One pass over the text.*/export function $restoreCharacterReferences(node: ElementNode,diff --git a/packages/richtext/src/markdownEscapes.test.ts b/packages/richtext/src/markdownEscapes.test.tsnew file mode 100644index 0000000000..f7f9a2f4ad--- /dev/null+++ b/packages/richtext/src/markdownEscapes.test.ts@@ -0,0 +1,234 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {createHeadlessEditor} from '@lexical/headless';+import {$createLinkNode} from '@lexical/link';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $isTextNode,+} from 'lexical';+import {parseMarkdownAst} from '@astryxdesign/core/Markdown/parser';+import {DEFAULT_NODES} from './editorNodes';+import {DEFAULT_TRANSFORMERS} from './markdownTable';+import {+ $exportMarkdownKeepingSource,+ importMarkdownKeepingSource,+} from './markdownSource';+import {+ editorStateJSONToMarkdown,+ markdownToEditorStateJSON,+} from './markdownSerializers';++type Json = Record<string, unknown>;++/** Inline content as one line: text, `code`, and <url|text> for links. */+function coreLine(markdown: string): Array<string> {+ const flat = (node: Json): string => {+ switch (node.type) {+ case 'text':+ return node.value as string;+ case 'inlineCode':+ return `\`${node.value as string}\``;+ case 'link':+ return `<${node.url as string}|${((node.children as Array<Json>) ?? []).map(flat).join('')}>`;+ default:+ return ((node.children as Array<Json>) ?? []).map(flat).join('');+ }+ };+ return (parseMarkdownAst(markdown).children as unknown as Array<Json>).map(+ flat,+ );+}++function richTextLine(markdown: string): Array<string> {+ const flat = (node: Json): string => {+ if (node.type === 'text') {+ const text = node.text as string;+ // Format bit 16 is inline code.+ return ((node.format as number) & 16) !== 0 ? `\`${text}\`` : text;+ }+ if (node.type === 'link' || node.type === 'autolink') {+ return `<${node.url as string}|${((node.children as Array<Json>) ?? []).map(flat).join('')}>`;+ }+ return ((node.children as Array<Json>) ?? []).map(flat).join('');+ };+ const root = (JSON.parse(markdownToEditorStateJSON(markdown)) as {root: Json})+ .root;+ return (root.children as Array<Json>).map(flat);+}++const ESCAPED = [+ // Escaped link syntax is text, not a link.+ '\\[x](y) text\n',+ '[x]\\(y) text\n',+ '\\[x\\](y) text\n',+ 'See \\[docs](https://example.com) here\n',+ // Escaped emphasis, heading, image, and code markers stay literal.+ 'a \\* b \\_ c \\# d \\! e \\` f \\~ g\n',+ '\\# not a heading\n',+ '1\\. not a list\n',+ // An escaped backslash before a real link: a backslash, then the link.+ '\\\\[x](https://example.com)\n',+ // Code keeps its backslashes.+ '`\\[x\\]` and \\[y\\]\n',+];++describe('backslash escapes (spec:AST-061 FR7)', () => {+ it.each(ESCAPED)('read as core reads them in %j', markdown => {+ expect(richTextLine(markdown)).toEqual(coreLine(markdown));+ });++ it.each(ESCAPED)('round-trip %j byte for byte', markdown => {+ expect(editorStateJSONToMarkdown(markdownToEditorStateJSON(markdown))).toBe(+ markdown,+ );+ });++ it('keep code fences as written', () => {+ const markdown = '```\n\\[x\\](y) \\*\n```\n';+ expect(richTextLine(markdown)).toEqual(['\\[x\\](y) \\*']);+ });++ it('keep a table cell pipe escaped', () => {+ const json = markdownToEditorStateJSON('| a \\| b | c |\n| --- | --- |\n');+ expect(JSON.stringify(JSON.parse(json))).toContain('"text":"a | b"');+ });+});++describe('an edited block with escaped syntax (spec:AST-062 FR3)', () => {+ it.each([+ ['\\[x](y) text\n', 'text', 'text!', '\\[x\\](y) text!\n'],+ ['See \\[docs](https://example.com) here\n', 'here', 'there', null],+ ['\\[x\\](y) text\n', 'text', 'text!', '\\[x\\](y) text!\n'],+ ] as const)(+ 'exports %j edited so it reads back as the same text',+ (markdown, find, replace, expected) => {+ const editor = createHeadlessEditor({+ nodes: [...DEFAULT_NODES],+ onError(error) {+ throw error;+ },+ });+ importMarkdownKeepingSource(editor, markdown, [...DEFAULT_TRANSFORMERS]);+ editor.update(+ () => {+ const target = $getRoot()+ .getAllTextNodes()+ .find(node => node.getTextContent().includes(find));+ if (!$isTextNode(target)) {+ throw new Error(`No text holds ${find}`);+ }+ target.setTextContent(target.getTextContent().replace(find, replace));+ },+ {discrete: true},+ );+ const exported = editor+ .getEditorState()+ .read(() => $exportMarkdownKeepingSource([...DEFAULT_TRANSFORMERS]));+ if (expected != null) {+ expect(exported).toBe(expected);+ }+ // No link appears, and the text is the edited text.+ expect(richTextLine(exported)).toEqual(+ richTextLine(markdown).map(line => line.replace(find, replace)),+ );+ },+ );+});++/** Each link's destination and text, in order. */+function linksOf(markdown: string): Array<[string, string]> {+ const found: Array<[string, string]> = [];+ const visit = (node: Json) => {+ if (node.type === 'link') {+ found.push([+ node.url as string,+ ((node.children as Array<Json>) ?? [])+ .map(child => child.text as string)+ .join(''),+ ]);+ }+ ((node.children as Array<Json>) ?? []).forEach(visit);+ };+ visit((JSON.parse(markdownToEditorStateJSON(markdown)) as {root: Json}).root);+ return found;+}++/** Imports `markdown`, appends `!` to its last text, and exports it. */+function editedExport(markdown: string): string {+ const editor = createHeadlessEditor({+ nodes: [...DEFAULT_NODES],+ onError(error) {+ throw error;+ },+ });+ importMarkdownKeepingSource(editor, markdown, [...DEFAULT_TRANSFORMERS]);+ editor.update(+ () => {+ const last = $getRoot().getAllTextNodes().at(-1);+ if (!$isTextNode(last)) {+ throw new Error('No text');+ }+ last.setTextContent(`${last.getTextContent()}!`);+ },+ {discrete: true},+ );+ return editor+ .getEditorState()+ .read(() => $exportMarkdownKeepingSource([...DEFAULT_TRANSFORMERS]));+}++describe('parentheses in link destinations (spec:AST-062 FR3)', () => {+ it.each([+ ['[x](https://e.com/\\(bar\\)) text\n', 'https://e.com/(bar)'],+ ['[x](a\\)b) text\n', 'a)b'],+ ['[x](a\\(b) text\n', 'a(b'],+ ['[x](https://e.com/foo(bar)) text\n', 'https://e.com/foo(bar)'],+ ['[x](https://e.com/foo(bar) "Title") text\n', 'https://e.com/foo(bar)'],+ ] as const)(+ 'reads %j as one link, round-trips it, and keeps it through an edit',+ (markdown, url) => {+ expect(linksOf(markdown)).toEqual([[url, 'x']]);+ expect(+ editorStateJSONToMarkdown(markdownToEditorStateJSON(markdown)),+ ).toBe(markdown);+ const edited = editedExport(markdown);+ expect(linksOf(edited)).toEqual([[url, 'x']]);+ expect(edited).toContain('text!');+ },+ );++ it('reads balanced parentheses in a destination as core does', () => {+ const markdown = '[x](https://e.com/foo(bar)) text\n';+ expect(richTextLine(markdown)).toEqual(coreLine(markdown));+ });++ it('writes a link made in the editor so it reads back as the same link', () => {+ const editor = createHeadlessEditor({+ nodes: [...DEFAULT_NODES],+ onError(error) {+ throw error;+ },+ });+ for (const url of [+ 'https://e.com/a(b',+ 'https://e.com/a)b',+ 'https://e.com/(ok)',+ ]) {+ editor.update(+ () => {+ const link = $createLinkNode(url);+ link.append($createTextNode('x'));+ $getRoot().clear().append($createParagraphNode().append(link));+ },+ {discrete: true},+ );+ const exported = editor+ .getEditorState()+ .read(() => $exportMarkdownKeepingSource([...DEFAULT_TRANSFORMERS]));+ expect(linksOf(exported)).toEqual([[url, 'x']]);+ }+ });+});diff --git a/packages/richtext/src/markdownLink.ts b/packages/richtext/src/markdownLink.tsnew file mode 100644index 0000000000..bb940ae489--- /dev/null+++ b/packages/richtext/src/markdownLink.ts@@ -0,0 +1,59 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file markdownLink.ts+ * @input Uses @lexical/link and @lexical/markdown (LINK).+ * @output Exports LINK_KEEPING_DESTINATIONS, Lexical's link transformer with+ * one change: a destination whose parentheses do not balance is written+ * with each parenthesis escaped.+ * @position Replaces Lexical's LINK in DEFAULT_TRANSFORMERS and in table+ * cells (markdownTable.ts). Import reads balanced parentheses in a+ * destination and backslash escapes (markdownCharacterReferences.ts), so a+ * destination written this way — `https://e.com/a(b` as+ * `https://e.com/a\(b` — reads back as the same link, whether it was+ * imported or made in the editor (spec:AST-062 FR3). A balanced+ * destination is written as it is.+ */++import {$isAutoLinkNode, $isLinkNode} from '@lexical/link';+import {LINK, type TextMatchTransformer} from '@lexical/markdown';++/** Whether every `)` in `url` closes an earlier `(` and every `(` closes. */+function isBalanced(url: string): boolean {+ let depth = 0;+ for (const character of url) {+ if (character === '(') {+ depth++;+ } else if (character === ')') {+ depth--;+ if (depth < 0) {+ return false;+ }+ }+ }+ return depth === 0;+}++/** `url` as a Markdown destination that reads back as `url`. */+export function markdownDestination(url: string): string {+ return isBalanced(url) ? url : url.replace(/[()]/g, '\\$&');+}++export const LINK_KEEPING_DESTINATIONS: TextMatchTransformer = {+ ...LINK,+ export: (node, exportChildren, exportFormat) => {+ if (!$isLinkNode(node) || $isAutoLinkNode(node)) {+ return null;+ }+ const url = node.getURL();+ const destination = markdownDestination(url);+ if (destination === url) {+ return LINK.export?.(node, exportChildren, exportFormat) ?? null;+ }+ const text = exportChildren(node);+ const title = node.getTitle();+ return title == null || title === ''+ ? `[${text}](${destination})`+ : `[${text}](${destination} "${title.replace(/([\\"])/g, '\\$1')}")`;+ },+};diff --git a/packages/richtext/src/markdownSource.ts b/packages/richtext/src/markdownSource.tsindex ab0b7aeb1a..6ab5e3509d 100644--- a/packages/richtext/src/markdownSource.ts+++ b/packages/richtext/src/markdownSource.ts@@ -53,7 +53,9 @@ import {isMarkedHardLineBreak} from './markdownHardLineBreak';import {normalizeListIndentation} from './markdownListIndentation';import {$restoreCharacterReferences,+ protectBackslashEscapes,protectCharacterReferences,+ protectLinkDestinationParentheses,} from './markdownCharacterReferences';import {$restoreExtensionSources,@@ -361,18 +363,29 @@ export function importMarkdownKeepingSource(const holder = $createParagraphNode();root.append(holder);// Lexical imports LF lines; the record keeps the authored endings.- // Adopted plugins' nodes, and then character references, go through- // as stand-ins: plugin nodes come back as extension nodes holding- // their source, references come back decoded.+ // Adopted plugins' nodes, then backslash escapes and parentheses in+ // link destinations, then character references go through as+ // stand-ins: plugin nodes come back as extension nodes holding their+ // source, escapes and parentheses as the literal characters,+ // references decoded.const shielded = shieldExtensionSources(withoutCarriageReturns(importChunks[index]?.content ?? chunk.content),plugins,);- const {markdown: chunkMarkdown, standIns} = protectCharacterReferences(- shielded.markdown,+ const escaped = protectBackslashEscapes(shielded.markdown);+ const destinations = protectLinkDestinationParentheses(+ escaped.markdown,+ );+ const referenced = protectCharacterReferences(destinations.markdown);+ $convertFromMarkdownString(referenced.markdown, transformers, holder);+ $restoreCharacterReferences(+ holder,+ new Map([+ ...escaped.standIns,+ ...destinations.standIns,+ ...referenced.standIns,+ ]),);- $convertFromMarkdownString(chunkMarkdown, transformers, holder);- $restoreCharacterReferences(holder, standIns);$restoreExtensionSources(holder, shielded.standIns);$joinSoftLineBreaks(holder);for (const node of holder.getChildren()) {diff --git a/packages/richtext/src/markdownTable.ts b/packages/richtext/src/markdownTable.tsindex 9b4614aaca..30a0ad894a 100644--- a/packages/richtext/src/markdownTable.ts+++ b/packages/richtext/src/markdownTable.ts@@ -20,6 +20,7 @@ import {$convertToMarkdownString,TEXT_FORMAT_TRANSFORMERS,TEXT_MATCH_TRANSFORMERS,+ LINK,ORDERED_LIST,TRANSFORMERS,type MultilineElementTransformer,@@ -43,6 +44,7 @@ import {THEMATIC_BREAK} from './markdownThematicBreak';import {LIST_EXPORT} from './markdownListExport';import {TASK_LIST} from './markdownTaskList';import {ORDERED_LIST_KEEPING_START} from './markdownOrderedList';+import {LINK_KEEPING_DESTINATIONS} from './markdownLink';/*** Cells hold inline Markdown only, so they are imported and exported with the@@ -50,7 +52,9 @@ import {ORDERED_LIST_KEEPING_START} from './markdownOrderedList';*/const CELL_TRANSFORMERS: Array<Transformer> = [...TEXT_FORMAT_TRANSFORMERS,- ...TEXT_MATCH_TRANSFORMERS,+ ...TEXT_MATCH_TRANSFORMERS.map(transformer =>+ transformer === LINK ? LINK_KEEPING_DESTINATIONS : transformer,+ ),];type ColumnAlignment = 'left' | 'center' | 'right' | null;@@ -242,7 +246,8 @@ export const TABLE: MultilineElementTransformer = {/*** The editor's default Markdown transformers: thematic breaks, list export* that nests to each parent's content column, GFM task list items, Lexical's- * standard set (its ordered list keeping each nested list's start), hard line+ * standard set (its ordered list keeping each nested list's start, and its+ * link writing an unbalanced destination's parentheses escaped), hard line* breaks for breaks typed in the editor, and GFM tables. Thematic breaks come first so a line such as `* * *` is a rule* rather than a list item, and task items before bullets so `- [ ] text` is a* task rather than a bullet that starts with `[ ]`.@@ -252,7 +257,11 @@ export const DEFAULT_TRANSFORMERS: ReadonlyArray<Transformer> = [LIST_EXPORT,TASK_LIST,...TRANSFORMERS.map(transformer =>- transformer === ORDERED_LIST ? ORDERED_LIST_KEEPING_START : transformer,+ transformer === ORDERED_LIST+ ? ORDERED_LIST_KEEPING_START+ : transformer === LINK+ ? LINK_KEEPING_DESTINATIONS+ : transformer,),HARD_LINE_BREAK,TABLE,