An open source design system that's fully customizable and agent ready
TypeScript
fix(richtext): escape a block marker after any leading spaces on export, so text stays text (#7118)
Cindy Zhang63db442c5a37
diff --git a/packages/richtext/src/markdownSource.ts b/packages/richtext/src/markdownSource.tsindex c5a293250e..4b3997ac2b 100644--- a/packages/richtext/src/markdownSource.ts+++ b/packages/richtext/src/markdownSource.ts@@ -675,21 +675,24 @@ function $canonicalMarkdown(return entry;}-/** Line starts that would turn literal text into a block structure. */+/**+ * Line starts that would turn literal text into a block structure. Each match+ * is the spaces before the marker, where the escape goes: block markers may+ * follow up to three spaces (CommonMark 0.31), and a list item's continuation+ * line adds its own indentation, so any spaces count.+ */const LINE_START_SYNTAX: ReadonlyArray<RegExp> = [+ // Block quote or ATX heading marker.+ /^ *(?=>|#{1,6}(?:[ \t]|$))/,// Bullet list item.- /^[-+](?=[ \t]|$)/,+ /^ *(?=[-+](?:[ \t]|$))/,// Setext underline or thematic break made of `=` or `-`.- /^[=-](?=[=\- \t]*$)/,+ /^ *(?=[=-][=\- \t]*$)/,// Table delimiter row.- /^[|:](?=[|:\- \t]*-[|:\- \t]*$)/,+ /^ *(?=[|:][|:\- \t]*-[|:\- \t]*$)/,];// An ordered list item escapes its delimiter, not its first character.-const ORDERED_LIST_START = /^(\d{1,9})([.)])(?=[ \t]|$)/;-// A block quote marker or an ATX heading marker may follow up to three spaces-// (CommonMark 0.31 §5.1, §4.2), and a list item's continuation line adds its-// own indentation, so the escape goes before the marker after any spaces.-const SPACED_MARKER_START = /^( *)(?=>|#{1,6}(?:[ \t]|$))/;+const ORDERED_LIST_START = /^( *\d{1,9})(?=[.)](?:[ \t]|$))/;// Inline syntax Lexical's export leaves unescaped: link and image brackets and// character references.@@ -759,13 +762,12 @@ function markedView(const previous = node.getPreviousSibling();if (previous == null || $isLineBreakNode(previous)) {const ordered = ORDERED_LIST_START.exec(text);- const marker = SPACED_MARKER_START.exec(text);- if (ordered != null) {- text = ordered[1] + token + text.slice(ordered[1].length);- } else if (marker != null) {- text = marker[1] + token + text.slice(marker[1].length);- } else if (LINE_START_SYNTAX.some(pattern => pattern.test(text))) {- text = token + text;+ const start = LINE_START_SYNTAX.map(pattern => pattern.exec(text)).find(+ match => match != null,+ );+ const before = ordered?.[1] ?? start?.[0];+ if (before != null) {+ text = before + token + text.slice(before.length);}}const view = Object.create(node) as typeof node;diff --git a/packages/richtext/src/markdownSpacedBlockStarts.test.ts b/packages/richtext/src/markdownSpacedBlockStarts.test.tsnew file mode 100644index 0000000000..d5ad8badbd--- /dev/null+++ b/packages/richtext/src/markdownSpacedBlockStarts.test.ts@@ -0,0 +1,96 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {createHeadlessEditor} from '@lexical/headless';+import {+ $createLineBreakNode,+ $createParagraphNode,+ $createTextNode,+ $getRoot,+} from 'lexical';+import {parseMarkdownAst} from '@astryxdesign/core/Markdown/parser';+import {DEFAULT_NODES} from './editorNodes';+import {DEFAULT_TRANSFORMERS} from './markdownTable';+import {$exportMarkdownKeepingSource} from './markdownSource';+import {markdownToEditorStateJSON} from './markdownSerializers';++type Json = {type: string; text?: string; value?: string; children?: Json[]};++const textOf = (node: Json): string =>+ node.type === 'linebreak' || node.type === 'break'+ ? '\n'+ : (node.text ?? node.value ?? (node.children ?? []).map(textOf).join(''));++/** The editor's top-level blocks: their types and text. */+function richBlocks(markdown: string): string[] {+ return (+ JSON.parse(markdownToEditorStateJSON(markdown)) as {root: Json}+ ).root.children!.map(node => `${node.type}:${textOf(node)}`);+}++/** Core's top-level block types. */+function coreTypes(markdown: string): string[] {+ return (parseMarkdownAst(markdown).children as unknown as Json[]).map(+ node => node.type,+ );+}++/** A one-paragraph document of `lines`, written by the editor. */+function exportParagraph(lines: ReadonlyArray<string>): string {+ const editor = createHeadlessEditor({+ nodes: [...DEFAULT_NODES],+ onError(error) {+ throw error;+ },+ });+ editor.update(+ () => {+ const paragraph = $createParagraphNode();+ lines.forEach((line, index) => {+ if (index > 0) {+ paragraph.append($createLineBreakNode());+ }+ paragraph.append($createTextNode(line));+ });+ $getRoot().clear().append(paragraph);+ },+ {discrete: true},+ );+ return editor+ .getEditorState()+ .read(() => $exportMarkdownKeepingSource([...DEFAULT_TRANSFORMERS]))+ .trimEnd();+}++describe('paragraph text that starts like a block marker after spaces stays text', () => {+ it.each([+ ['a bullet after spaces', ' - a', ' \\- a'],+ ['a plus bullet after spaces', ' + a', ' \\+ a'],+ ['a bullet deeper than a list continuation', ' - a', ' \\- a'],+ ['a number after spaces', ' 1. step', ' 1\\. step'],+ ['a parenthesis number after spaces', ' 2) step', ' 2\\) step'],+ ['a break line after spaces', ' ---', ' \\---'],+ ['an underline after spaces', ' ===', ' \\==='],+ ['a bullet at the margin, as before', '- a', '\\- a'],+ ['a number at the margin, as before', '1. step', '1\\. step'],+ ])(+ 'writes %s escaped, and both surfaces read it back as text',+ (_, text, written) => {+ const exported = exportParagraph([text]);+ expect(exported).toBe(written);+ expect(richBlocks(exported)).toEqual([`paragraph:${text}`]);+ expect(coreTypes(exported)).toEqual(['paragraph']);+ },+ );++ it('escapes a spaced marker on the line after a line break', () => {+ const exported = exportParagraph(['intro', ' - a']);+ expect(exported).toBe('intro\\\n \\- a');+ expect(richBlocks(exported)).toEqual(['paragraph:intro\n - a']);+ expect(coreTypes(exported)).toEqual(['paragraph']);+ });++ it('leaves a dash inside a line alone', () => {+ expect(exportParagraph(['a - b'])).toBe('a - b');+ });+});