An open source design system that's fully customizable and agent ready
TypeScript
feat(richtext): keep authored Markdown through import and export (#6989)
Cindy Zhang7a6a63785d5e
diff --git a/packages/richtext/src/RichTextEditor.doc.mjs b/packages/richtext/src/RichTextEditor.doc.mjsindex 3508dd504d..3d24a5c244 100644--- a/packages/richtext/src/RichTextEditor.doc.mjs+++ b/packages/richtext/src/RichTextEditor.doc.mjs@@ -192,7 +192,7 @@ export const docs = {{guidance: true,description:- 'Use a ref (RichTextEditorRef) to imperatively focus(), clear(), read the state via getEditorState(), serialize to Markdown via getMarkdown() or HTML via getHTML(), or reach the LexicalEditor via getEditor(). The handle is available after mount. getMarkdown() uses the same transformers prop the editor is configured with. focus() and clear() are no-ops when the editor is read-only or disabled, and clear() resets to a single empty paragraph.',+ 'Use a ref (RichTextEditorRef) to imperatively focus(), clear(), read the state via getEditorState(), serialize to Markdown via getMarkdown() or HTML via getHTML(), or reach the LexicalEditor via getEditor(). The handle is available after mount. getMarkdown() uses the same transformers prop the editor is configured with, and returns imported content as it was written: blocks nobody changed come back byte for byte, and only blocks that were edited or added are written in canonical Markdown. focus() and clear() are no-ops when the editor is read-only or disabled, and clear() resets to a single empty paragraph.',},{guidance: true,@@ -202,7 +202,7 @@ export const docs = {{guidance: true,description:- 'To produce a defaultValue from Markdown without mounting an editor (e.g. on the server), use markdownToEditorStateJSON(markdown). Convert the other way with editorStateJSONToMarkdown(json). Both run headless via @lexical/headless and accept the same transformers/nodes options as the editor.',+ 'To produce a defaultValue from Markdown without mounting an editor (e.g. on the server), use markdownToEditorStateJSON(markdown). Convert the other way with editorStateJSONToMarkdown(json). Both run headless via @lexical/headless and accept the same transformers/nodes options as the editor. The round trip keeps the Markdown as written: exporting unchanged content returns the input exactly, including indentation, escapes, character references, fence metadata, and constructs the editor shows as plain text, and an edit regenerates only the blocks it changed.',},{guidance: true,diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsxindex 34005031bd..f0912133a3 100644--- a/packages/richtext/src/RichTextEditor.tsx+++ b/packages/richtext/src/RichTextEditor.tsx@@ -72,10 +72,11 @@ import {TabIndentationPlugin} from '@lexical/react/LexicalTabIndentationPlugin';import {MarkdownShortcutPlugin} from '@lexical/react/LexicalMarkdownShortcutPlugin';import {OnChangePlugin} from '@lexical/react/LexicalOnChangePlugin';import {TablePlugin} from '@lexical/react/LexicalTablePlugin';-import {$convertToMarkdownString, type Transformer} from '@lexical/markdown';+import {type Transformer} from '@lexical/markdown';export type {Transformer} from '@lexical/markdown';import {$generateHtmlFromNodes} from '@lexical/html';import {DEFAULT_NODES} from './editorNodes';+import {$exportMarkdownKeepingSource} from './markdownSource';import {DEFAULT_TRANSFORMERS} from './markdownTable';import {BLUR_COMMAND,@@ -274,8 +275,10 @@ export interface RichTextEditorRef {/*** Serialize the current content to a Markdown string, using the same* `transformers` the editor is configured with (so custom transformers- * layered in via the `transformers` prop are honored). Equivalent to- * `$convertToMarkdownString` run in a read context.+ * layered in via the `transformers` prop are honored). Content imported+ * with `markdownToEditorStateJSON` comes back as written: blocks nobody+ * changed byte for byte, and only edited or added blocks in canonical+ * Markdown.*/getMarkdown: () => string;/**@@ -891,13 +894,13 @@ function EditorRefBridge({},getEditorState: () => editor.getEditorState(),getMarkdown: () =>- // $convertToMarkdownString must run inside a read context. Honors the- // same transformers the editor uses for shortcuts, so custom- // transformers round-trip to Markdown. `@lexical/markdown` is a- // subpackage (built dist) — safe, unlike a top-level `lexical` import.+ // Untouched blocks export exactly as imported and changed blocks in+ // canonical form (spec:AST-062). Honors the same transformers the+ // editor uses for shortcuts, so custom transformers round-trip. Reads+ // the state without changing it.editor.getEditorState()- .read(() => $convertToMarkdownString(transformers)),+ .read(() => $exportMarkdownKeepingSource(transformers)),getHTML: () =>// $generateHtmlFromNodes serializes the whole document (null selection)// to HTML; must run in a read context and requires a DOM.diff --git a/packages/richtext/src/markdownSerializers.ts b/packages/richtext/src/markdownSerializers.tsindex cc1753f34b..9ad8e32496 100644--- a/packages/richtext/src/markdownSerializers.ts+++ b/packages/richtext/src/markdownSerializers.ts@@ -3,8 +3,8 @@/*** @file markdownSerializers.ts* @input Uses @lexical/headless (createHeadlessEditor), @lexical/markdown- * ($convertFromMarkdownString / $convertToMarkdownString), the shared- * DEFAULT_NODES set, and DEFAULT_TRANSFORMERS.+ * (transformer types), the shared DEFAULT_NODES set, DEFAULT_TRANSFORMERS,+ * and the source-preserving import and export in markdownSource.ts.* @output Standalone Markdown <-> serialized EditorState helpers:* markdownToEditorStateJSON, editorStateJSONToMarkdown.* @position Re-exported from RichTextEditor/index.ts and the @astryxdesign/richtext@@ -23,12 +23,12 @@*/import {createHeadlessEditor} from '@lexical/headless';-import {- $convertFromMarkdownString,- $convertToMarkdownString,- type Transformer,-} from '@lexical/markdown';+import {type Transformer} from '@lexical/markdown';import {DEFAULT_NODES} from './editorNodes';+import {+ $exportMarkdownKeepingSource,+ importMarkdownKeepingSource,+} from './markdownSource';import {DEFAULT_TRANSFORMERS} from './markdownTable';import type {Klass, LexicalNode} from 'lexical';@@ -75,12 +75,7 @@ export function markdownToEditorStateJSON(): string {const {transformers = DEFAULT_TRANSFORMERS, nodes} = options;const editor = createSerializerEditor(nodes);- editor.update(- () => {- $convertFromMarkdownString(markdown, [...transformers]);- },- {discrete: true},- );+ importMarkdownKeepingSource(editor, markdown, [...transformers]);return JSON.stringify(editor.getEditorState().toJSON());}@@ -101,5 +96,5 @@ export function editorStateJSONToMarkdown(const {transformers = DEFAULT_TRANSFORMERS, nodes} = options;const editor = createSerializerEditor(nodes);const state = editor.parseEditorState(editorStateJSON);- return state.read(() => $convertToMarkdownString([...transformers]));+ return state.read(() => $exportMarkdownKeepingSource([...transformers]));}diff --git a/packages/richtext/src/markdownSource.test.tsx b/packages/richtext/src/markdownSource.test.tsxnew file mode 100644index 0000000000..814f4e7d48--- /dev/null+++ b/packages/richtext/src/markdownSource.test.tsx@@ -0,0 +1,487 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect} from 'vitest';+import {render, waitFor} from '@testing-library/react';+import {createRef} from 'react';+import {createHeadlessEditor} from '@lexical/headless';+import {+ $convertFromMarkdownString,+ BOLD_STAR,+ ITALIC_STAR,+ UNORDERED_LIST,+ type Transformer,+} from '@lexical/markdown';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $isElementNode,+ $parseSerializedNode,+ REDO_COMMAND,+ UNDO_COMMAND,+ type SerializedLexicalNode,+} from 'lexical';+import {DEFAULT_NODES} from './editorNodes';+import {DEFAULT_TRANSFORMERS} from './markdownTable';+import {+ editorStateJSONToMarkdown,+ markdownToEditorStateJSON,+} from './markdownSerializers';+import {absentToken, splitMarkdownChunks} from './markdownSource';+import {RichTextEditor, type RichTextEditorRef} from './RichTextEditor';+import {RichTextEditorAutoLinkPlugin} from './RichTextEditorAutoLinkPlugin';++/**+ * The conformance corpus for spec:AST-062. Each document must come back byte+ * for byte from a no-op round trip, whatever RichText makes of it.+ */+const CORPUS: Record<string, string> = {+ empty: '',+ whitespaceOnly: ' \n\n\t\n',+ singleParagraphNoNewline: 'Plain paragraph',+ singleParagraphNewline: 'Plain paragraph\n',+ extraTrailingNewlines: 'Paragraph\n\n\n',+ leadingBlankLines: '\n\n# Title\n\nBody\n',+ trailingSpacesOnLines: 'Line with trailing spaces \n\nNext \n',+ crlf: '# Title\r\n\r\nFirst paragraph\r\nsoft break\r\n',+ byteOrderMark: '\uFEFF# Title\n\nBody\n',+ atxClosingHashes: '# Title #\n\n## Section ##\n',+ setextHeadings: 'Title\n=====\n\nSection\n-------\n',+ emphasisVariants:+ '*em* and _em_, **strong** and __strong__, ***both*** and ~~struck~~\n',+ inlineCodeBackticks: 'Use `code` and `` a`b `` here\n',+ links:+ '[inline](https://example.com) and [titled](https://example.com "Title") and <https://example.com/auto>\n',+ referenceLinks:+ 'See [the docs][docs] and [docs].\n\n[docs]: https://example.com/docs "Docs"\n',+ bareUrl: 'Visit https://example.com/status today\n',+ hardBreaks: 'Two spaces \nand a backslash\\\nend\n',+ softBreaks: 'One line\nsame paragraph\nstill same\n',+ blockquote: '> Quote line one\nlazy continuation\n>\n> > nested quote\n',+ nestedListsTwoSpace: '- Parent\n - Child\n - Grandchild\n- Sibling\n',+ nestedListsThreeSpace: '1. First\n 1. Nested\n2. Second\n',+ nestedListsFourSpace: '- Parent\n - Child\n',+ listMarkers: '* star\n+ plus\n- dash\n',+ orderedStartAndParen: '3. three\n4. four\n\n1) paren\n2) paren\n',+ looseList: '- loose one\n\n- loose two\n',+ taskList: '- [ ] open\n- [x] done\n',+ fenceInfoAndMeta:+ '```ts title="retry.ts" {2}\nconst x = 1;\n\nconst y = 2;\n```\n',+ tildeFence: '~~~python\nprint("hi")\n~~~\n',+ longerFence: '````md\n```js\nnested();\n```\n````\n',+ unclosedFence: '```\nnever closed\n\nstill code',+ indentedCode: 'Paragraph\n\n indented code\n more\n',+ thematicBreaks: 'Above\n\n***\n\n___\n\n- - -\n\nBelow\n',+ escapes:+ '\\# not a heading\n\n\\*not italic\\* and \\_not\\_ and \\\\ backslash\n',+ characterReferences: 'Entities: & © © 😀 \n',+ htmlBlock: '<div align="center">\n <b>HTML</b>\n</div>\n\nAfter\n',+ htmlInlineAndComment: 'Inline <kbd>Ctrl</kbd> and <!-- comment -->\n',+ footnote: 'Claim.[^1]\n\n[^1]: The footnote.\n',+ frontMatterLike: '---\ntitle: Notes\n---\n\nBody\n',+ unicodeAndRtl: 'Emoji 🎉 and עברית mixed with English\n',+ malformedEmphasis: '**unclosed strong and *unclosed em\n',+ malformedLink: '[no destination] and [broken](\n',+ tabsAndMixedIndent: '\t- tab list\n \t- mixed\n',+ tableCanonical: '| Name | Role |\n| --- | --- |\n| Ada | Engineer |\n',+ tableNonCanonical:+ 'Area|Owner |Status\n:-|:-:|-:\n`a \\| b`|**Ada**| done \n\nAfter\n',+ tableRaggedAndEscaped:+ '| A | B \\| C |\n|---|---|\n| only one |\n| 1 | 2 | 3 |\n',+ mixedDocument:+ '# Release notes\n\nIntro with **bold** and a [link](https://example.com).\n\n- One\n - Two\n\n```ts\nconst a = 1;\n```\n\n> Quote\n\nEnd\n',+};++function roundTrip(+ markdown: string,+ transformers?: Array<Transformer>,+): string {+ return editorStateJSONToMarkdown(+ markdownToEditorStateJSON(markdown, {transformers}),+ {transformers},+ );+}++/** Applies an edit to the imported state and exports it again. */+function editAndExport(+ markdown: string,+ edit: () => void,+ transformers?: Array<Transformer>,+): string {+ const editor = createHeadlessEditor({+ namespace: 'astryx-markdown-source-test',+ nodes: [...DEFAULT_NODES],+ onError(error: Error) {+ throw error;+ },+ });+ editor.setEditorState(+ editor.parseEditorState(+ markdownToEditorStateJSON(markdown, {transformers}),+ ),+ );+ editor.update(edit, {discrete: true});+ return editorStateJSONToMarkdown(+ JSON.stringify(editor.getEditorState().toJSON()),+ {transformers},+ );+}++function $appendToBlock(index: number, text: string): void {+ const block = $getRoot().getChildren()[index];+ if (!$isElementNode(block)) {+ throw new Error(`block ${index} is not an element`);+ }+ const textNode = block.getAllTextNodes()[0];+ textNode.setTextContent(textNode.getTextContent() + text);+}++function $appendToTextContaining(needle: string, text: string): void {+ const node = $getRoot()+ .getAllTextNodes()+ .find(candidate => candidate.getTextContent().includes(needle));+ node?.setTextContent(node.getTextContent() + text);+}++function $appendToBlockContaining(needle: string, text: string): void {+ const index = $getRoot()+ .getChildren()+ .findIndex(block => block.getTextContent().includes(needle));+ $appendToBlock(index, text);+}++describe('Markdown source preservation (spec:AST-062)', () => {+ it('has at least 30 corpus documents', () => {+ expect(Object.keys(CORPUS).length).toBeGreaterThanOrEqual(30);+ });++ it.each(Object.entries(CORPUS))(+ 'splits %s into chunks that join back to the input',+ (_name, markdown) => {+ const chunks = splitMarkdownChunks(markdown);+ const joined = chunks+ .map(chunk => chunk.leading + chunk.content + chunk.trailing)+ .join('');+ expect(chunks.length === 0 ? markdown.trim() : joined).toBe(+ chunks.length === 0 ? '' : markdown,+ );+ },+ );++ it.each(Object.entries(CORPUS))(+ 'returns %s byte for byte from a no-op round trip (FR1)',+ (_name, markdown) => {+ expect(roundTrip(markdown)).toBe(markdown);+ },+ );++ it('keeps every untouched block when the first, a middle, or the last block changes (FR2)', () => {+ const source =+ '# Title\n\nFirst paragraph\n\n- One\n - Two\n\n\\# escaped\n\nLast ©\n';+ expect(editAndExport(source, () => $appendToBlock(0, ' edited'))).toBe(+ '# Title edited\n\nFirst paragraph\n\n- One\n - Two\n\n\\# escaped\n\nLast ©\n',+ );+ const middle = editAndExport(source, () => $appendToBlock(1, ' edited'));+ expect(middle.startsWith('# Title\n\n')).toBe(true);+ expect(+ middle.endsWith('\n\n- One\n - Two\n\n\\# escaped\n\nLast ©\n'),+ ).toBe(true);+ expect(middle).toContain('edited');+ const last = editAndExport(source, () => {+ const block = $getRoot().getLastChild();+ if ($isElementNode(block)) {+ block.clear();+ block.append($createTextNode('Changed last'));+ }+ });+ expect(last).toBe(+ '# Title\n\nFirst paragraph\n\n- One\n - Two\n\n\\# escaped\n\nChanged last\n',+ );+ });++ it('keeps every untouched block when a block is inserted or deleted (FR2)', () => {+ const source = 'Alpha \n\n\\# Beta\n\nGamma ©\n';+ expect(+ editAndExport(source, () => {+ const paragraph = $createParagraphNode();+ paragraph.append($createTextNode('Inserted'));+ $getRoot().getChildren()[0].insertAfter(paragraph);+ }),+ ).toBe('Alpha \n\nInserted\n\n\\# Beta\n\nGamma ©\n');+ expect(+ editAndExport(source, () => {+ $getRoot().getChildren()[1].remove();+ }),+ ).toBe('Alpha \n\nGamma ©\n');+ expect(+ editAndExport(source, () => {+ const paragraph = $createParagraphNode();+ paragraph.append($createTextNode('Appended'));+ $getRoot().append(paragraph);+ }),+ ).toBe('Alpha \n\n\\# Beta\n\nGamma ©\n\nAppended\n');+ });++ it('keeps unsupported source when other blocks change, and keeps its characters when it changes (FR5)', () => {+ const source =+ '<div align="center">\n <b>HTML</b>\n</div>\n\n[docs]: https://example.com/docs\n\nEdit me\n';+ expect(+ editAndExport(source, () => $appendToBlockContaining('Edit me', ' now')),+ ).toBe(+ '<div align="center">\n <b>HTML</b>\n</div>\n\n[docs]: https://example.com/docs\n\nEdit me now\n',+ );+ const editedHtml = editAndExport(source, () =>+ $appendToBlockContaining('HTML', ' x'),+ );+ for (const fragment of ['<div align="center">', '<b>HTML</b>', '</div>']) {+ expect(editedHtml).toContain(fragment);+ }+ expect(+ editedHtml.endsWith('\n\n[docs]: https://example.com/docs\n\nEdit me\n'),+ ).toBe(true);+ });++ it('writes a regenerated block so it imports again as what the editor showed (FR3)', () => {+ const source = '\\# not a heading\n\nKeep\n';+ const edited = editAndExport(source, () =>+ $appendToBlockContaining('not a heading', ' [x] 1. *y* ©'),+ );+ expect(edited).toBe(+ '\\# not a heading \\[x\\] 1. \\*y\\* \\©\n\nKeep\n',+ );+ // Importing the regenerated Markdown shows the same literal text again.+ const reloaded = JSON.parse(markdownToEditorStateJSON(edited)) as {+ root: {children: Array<{type: string}>};+ };+ expect(reloaded.root.children.map(node => node.type)).toEqual([+ 'paragraph',+ 'paragraph',+ ]);+ expect(+ editAndExport('Lead\n', () => {+ const paragraph = $createParagraphNode();+ paragraph.append($createTextNode('1. not a list'));+ $getRoot().append(paragraph);+ }),+ ).toBe('Lead\n\n1\\. not a list\n');+ });++ it('keeps the byte order mark, leading bytes, and line endings (FR4)', () => {+ const crlf =+ '\uFEFF\r\n# Title\r\n\r\nFirst\r\nsecond line\r\n\r\nLast\r\n';+ expect(roundTrip(crlf)).toBe(crlf);+ expect(+ editAndExport(crlf, () => $appendToBlockContaining('Title', '!')),+ ).toBe('\uFEFF\r\n# Title!\r\n\r\nFirst\r\nsecond line\r\n\r\nLast\r\n');+ // The editor shows the two lines as two paragraphs, so the regenerated+ // group writes two paragraphs, in the group's CRLF style.+ expect(+ editAndExport(crlf, () => $appendToBlockContaining('First', ' one')),+ ).toBe('\uFEFF\r\n# Title\r\n\r\nFirst one\r\nsecond line\r\n\r\nLast\r\n');+ expect(+ editAndExport(crlf, () => {+ const paragraph = $createParagraphNode();+ paragraph.append($createTextNode('Added'));+ $getRoot().append(paragraph);+ }),+ ).toBe(+ '\uFEFF\r\n# Title\r\n\r\nFirst\r\nsecond line\r\n\r\nLast\r\n\r\nAdded\r\n',+ );+ expect(+ editAndExport(crlf, () => {+ $getRoot().getChildren()[0].remove();+ }).startsWith('\uFEFF'),+ ).toBe(true);+ });++ it('keeps a bare URL as written when the autolink plugin links it on load (FR1, FR6)', async () => {+ const markdown = 'Status at https://example.com/status today.\n\n- item\n';+ const ref = createRef<RichTextEditorRef>();+ render(+ <RichTextEditor+ label="Notes"+ ref={ref}+ defaultValue={markdownToEditorStateJSON(markdown)}+ plugins={<RichTextEditorAutoLinkPlugin />}+ />,+ );+ await waitFor(() =>+ expect(+ document.querySelector('a[href="https://example.com/status"]'),+ ).not.toBeNull(),+ );+ expect(ref.current?.getMarkdown()).toBe(markdown);+ });++ it('regenerates only an edited table, in canonical form, and keeps the rest (FR2, FR6)', () => {+ const source = 'Intro \n\nArea|Owner\n:-|-:\nSearch|Ada\n\n\\# Outro\n';+ expect(+ editAndExport(source, () => $appendToTextContaining('Search', ' 2')),+ ).toBe(+ 'Intro \n\n| Area | Owner |\n| :--- | ---: |\n| Search 2 | Ada |\n\n\\# Outro\n',+ );+ });++ it('imports the same structure as importing the whole document at once', () => {+ // Node state aside, chunked import must build exactly the tree Lexical's+ // own import builds: soft breaks, lazy continuation lines, loose lists.+ const structureOf = (json: string): unknown =>+ JSON.parse(json, (key, value: unknown) =>+ key === '$' ? undefined : value,+ );+ const wholeDocument = (markdown: string): string => {+ const editor = createHeadlessEditor({+ namespace: 'astryx-markdown-source-whole',+ nodes: [...DEFAULT_NODES],+ onError(error: Error) {+ throw error;+ },+ });+ editor.update(+ () => {+ $convertFromMarkdownString(+ markdown.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n'),+ [...DEFAULT_TRANSFORMERS],+ );+ },+ {discrete: true},+ );+ return JSON.stringify(editor.getEditorState().toJSON());+ };+ for (const [name, markdown] of Object.entries(CORPUS)) {+ expect(structureOf(markdownToEditorStateJSON(markdown)), name).toEqual(+ structureOf(wholeDocument(markdown)),+ );+ }+ });++ it('keeps document facts at the document when blocks move, repeat, or go (FR4)', () => {+ const source = '\uFEFF\n\nAlpha\n\n\\# Beta\n\nGamma\n\n';+ // Moving the first block to the end keeps the envelope at the edges.+ expect(+ editAndExport(source, () => {+ const [alpha] = $getRoot().getChildren();+ $getRoot().append(alpha);+ }),+ ).toBe('\uFEFF\n\n\\# Beta\n\nGamma\n\nAlpha\n\n');+ // Repeating a block does not repeat the envelope.+ expect(+ editAndExport(source, () => {+ const [alpha] = $getRoot().getChildren();+ const copy = $parseSerializedNode(+ alpha.exportJSON() as SerializedLexicalNode,+ );+ if ($isElementNode(alpha) && $isElementNode(copy)) {+ copy.append($createTextNode(alpha.getTextContent()));+ }+ $getRoot().getLastChild()?.insertAfter(copy);+ }),+ ).toBe('\uFEFF\n\nAlpha\n\n\\# Beta\n\nGamma\n\nAlpha\n\n');+ // Deleting the first block keeps the byte order mark and leading lines.+ expect(+ editAndExport(source, () => {+ $getRoot().getFirstChild()?.remove();+ }),+ ).toBe('\uFEFF\n\n\\# Beta\n\nGamma\n\n');+ });++ it('writes a block taken from another document in the line endings of the one it joins (FR4)', () => {+ const lf = 'One\n\nTwo\n';+ const crlf = 'Uno\r\n\r\nDos\r\nmismo\r\n';+ const moveFirstBlock = (from: string, to: string): string => {+ const source = createHeadlessEditor({+ namespace: 'astryx-markdown-source-from',+ nodes: [...DEFAULT_NODES],+ onError(error: Error) {+ throw error;+ },+ });+ source.setEditorState(+ source.parseEditorState(markdownToEditorStateJSON(from)),+ );+ const block = JSON.parse(JSON.stringify(source.getEditorState().toJSON()))+ .root.children[0] as SerializedLexicalNode;+ return editAndExport(to, () => {+ $getRoot().append($parseSerializedNode(block));+ });+ };+ expect(moveFirstBlock(crlf, lf)).toBe('One\n\nTwo\n\nUno\n');+ expect(moveFirstBlock(lf, crlf)).toBe(+ 'Uno\r\n\r\nDos\r\nmismo\r\n\r\nOne\r\n',+ );+ });++ it('never mistakes text for an escape token, whatever it contains (FR3)', () => {+ const tricky = 'Keeps \uFDD0 and \uE000 and \u{F0000} as written';+ expect(+ editAndExport(`${tricky}\n\nNext\n`, () =>+ $appendToTextContaining('Keeps', ' [x]'),+ ),+ ).toBe(`${tricky} \\[x\\]\n\nNext\n`);+ expect(absentToken('')).toBe('\uE000');+ expect(absentToken('\uE000')).toBe('\uE001');+ const everySingle = Array.from({length: 0xf8ff - 0xe000 + 1}, (_, index) =>+ String.fromCodePoint(0xe000 + index),+ ).join('');+ expect(absentToken(everySingle)).toBe('\u{F0000}');+ });++ it('follows edits, undo, and redo in a mounted editor (FR1, FR2)', async () => {+ const markdown = '# Title\n\n- One\n - Two\n\nLast ©\n';+ const ref = createRef<RichTextEditorRef>();+ render(+ <RichTextEditor+ label="Notes"+ ref={ref}+ defaultValue={markdownToEditorStateJSON(markdown)}+ />,+ );+ await waitFor(() => expect(ref.current).not.toBeNull());+ const editor = ref.current?.getEditor();+ expect(ref.current?.getMarkdown()).toBe(markdown);+ editor?.update(() => $appendToTextContaining('Last', ' edited'), {+ discrete: true,+ });+ expect(ref.current?.getMarkdown()).toBe(+ '# Title\n\n- One\n - Two\n\nLast \u00a9 edited\n',+ );+ editor?.dispatchCommand(UNDO_COMMAND, undefined);+ await waitFor(() => expect(ref.current?.getMarkdown()).toBe(markdown));+ editor?.dispatchCommand(REDO_COMMAND, undefined);+ await waitFor(() =>+ expect(ref.current?.getMarkdown()).toBe(+ '# Title\n\n- One\n - Two\n\nLast \u00a9 edited\n',+ ),+ );+ });++ it('gives a custom transformer array the same preservation (FR6)', () => {+ const custom = [BOLD_STAR, ITALIC_STAR, UNORDERED_LIST];+ const source = '# Not a heading here\n\n- **bold** item\n - nested\n';+ expect(roundTrip(source, custom)).toBe(source);+ });++ it('returns the authored bytes from getMarkdown() after loading imported content (FR1)', async () => {+ for (const name of [+ 'mixedDocument',+ 'nestedListsThreeSpace',+ 'fenceInfoAndMeta',+ 'escapes',+ 'characterReferences',+ 'crlf',+ ]) {+ const markdown = CORPUS[name];+ const ref = createRef<RichTextEditorRef>();+ const {unmount} = render(+ <RichTextEditor+ label="Notes"+ ref={ref}+ defaultValue={markdownToEditorStateJSON(markdown)}+ />,+ );+ await waitFor(() => expect(ref.current).not.toBeNull());+ expect(ref.current?.getMarkdown(), name).toBe(markdown);+ unmount();+ }+ });+});diff --git a/packages/richtext/src/markdownSource.ts b/packages/richtext/src/markdownSource.tsnew file mode 100644index 0000000000..041828d3b7--- /dev/null+++ b/packages/richtext/src/markdownSource.ts@@ -0,0 +1,669 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file markdownSource.ts+ * @input Uses lexical (node state, root, node classes), @lexical/markdown+ * ($convertFromMarkdownString / $convertToMarkdownString), and @lexical/code.+ * @output Exports importMarkdownKeepingSource and $exportMarkdownKeepingSource,+ * the source-preserving Markdown import and export behind+ * markdownToEditorStateJSON, editorStateJSONToMarkdown, and getMarkdown().+ * @position Internal to @astryxdesign/richtext. Implements spec:AST-062: an+ * untouched top-level block exports exactly as authored, and an edit+ * regenerates only the blocks it changed.+ *+ * Import splits the source into chunks (runs of non-blank lines; a fenced code+ * block is one chunk even across blank lines) and imports each chunk on its+ * own. Once node transforms settle the tree, the top-level nodes from one or+ * more consecutive chunks form a group, and the group's first node records the+ * exact bytes it came from and its canonical Markdown at import. Facts about+ * the whole document — its byte order mark, the bytes before the first block+ * and after the last, its line ending — live on the root, so moving, copying,+ * or deleting blocks never moves or duplicates them.+ *+ * Export reads the tree without changing it. Each group's canonical Markdown+ * is regenerated (and cached per node, so an unchanged tree costs a lookup per+ * group); when it still matches the recorded one, the recorded bytes are+ * written instead.+ */++import {+ $convertFromMarkdownString,+ $convertToMarkdownString,+ type Transformer,+} from '@lexical/markdown';+import {$isCodeNode} from '@lexical/code';+import {+ $createParagraphNode,+ $getRoot,+ $getState,+ $isElementNode,+ $isLineBreakNode,+ $isTextNode,+ $setState,+ createState,+ type ElementNode,+ type LexicalEditor,+ type LexicalNode,+} from 'lexical';++/** The whitespace and content one chunk of Markdown source was split into. */+export interface MarkdownChunk {+ /** Blank lines before the chunk; only the first chunk has any. */+ readonly leading: string;+ /** The chunk's lines, without the line ending that ends the last one. */+ readonly content: string;+ /** Everything after the content up to the next chunk, or to the end. */+ readonly trailing: string;+}++/** What a group of top-level nodes was imported from. */+interface GroupRecord {+ /** The import and chunk this group came from; unique across documents. */+ readonly group: string;+ /** The rest is recorded on the group's first node only. */+ readonly size?: number;+ readonly content?: string;+ /** The bytes between this group and the next one. */+ readonly trailing?: string;+ /** A hash of the group's canonical Markdown at import. */+ readonly canonicalHash?: string;+ /** The line ending the group's source uses. */+ readonly lineEnding?: string;+}++/**+ * The serialized form of a group record: short keys, and defaults left out,+ * because every imported group carries one.+ */+interface SerializedGroupRecord {+ g: string;+ n?: number;+ s?: string;+ t?: string;+ h?: string;+ e?: string;+}++/** Facts about the whole imported document, kept on the root. */+interface DocumentRecord {+ readonly importId: string;+ readonly byteOrderMark: boolean;+ /** The bytes before the first block, without the byte order mark. */+ readonly leading: string;+ /** The bytes after the last block. */+ readonly trailing: string;+ /** The document's first line ending, or LF when it has none. */+ readonly lineEnding: string;+}++function parseGroupRecord(value: unknown): GroupRecord | null {+ if (typeof value !== 'object' || value === null) {+ return null;+ }+ const serialized = value as Partial<SerializedGroupRecord>;+ if (typeof serialized.g !== 'string') {+ return null;+ }+ if (typeof serialized.s !== 'string') {+ return {group: serialized.g};+ }+ return {+ group: serialized.g,+ size: typeof serialized.n === 'number' ? serialized.n : 1,+ content: serialized.s,+ trailing: typeof serialized.t === 'string' ? serialized.t : '\n\n',+ canonicalHash: typeof serialized.h === 'string' ? serialized.h : '',+ lineEnding: typeof serialized.e === 'string' ? serialized.e : '\n',+ };+}++function unparseGroupRecord(+ record: GroupRecord | null,+): SerializedGroupRecord | null {+ if (record == null) {+ return null;+ }+ const serialized: SerializedGroupRecord = {g: record.group};+ if (record.content != null) {+ serialized.s = record.content;+ if (record.size !== 1) {+ serialized.n = record.size;+ }+ if (record.trailing !== '\n\n') {+ serialized.t = record.trailing;+ }+ serialized.h = record.canonicalHash;+ if (record.lineEnding !== '\n') {+ serialized.e = record.lineEnding;+ }+ }+ return serialized;+}++function isDocumentRecord(value: unknown): value is DocumentRecord {+ return (+ typeof value === 'object' &&+ value !== null &&+ typeof (value as {importId?: unknown}).importId === 'string'+ );+}++const groupState = createState('astryxMd', {+ parse: parseGroupRecord,+ unparse: unparseGroupRecord,+});++const documentState = createState('astryxMdDocument', {+ parse: (value: unknown): DocumentRecord | null =>+ isDocumentRecord(value) ? value : null,+});++const BLANK_LINE = /^[ \t]*\r?$/;+const FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})/;++/**+ * Splits Markdown into chunks: runs of non-blank lines, with a fenced code+ * block kept whole across blank lines. Joining every chunk's leading, content,+ * and trailing text gives back the input exactly.+ */+export function splitMarkdownChunks(markdown: string): Array<MarkdownChunk> {+ const lines = markdown.split('\n');+ const chunks: Array<MarkdownChunk> = [];+ let leading = '';+ let index = 0;+ // Blank lines before the first chunk.+ while (index < lines.length && BLANK_LINE.test(lines[index])) {+ if (index === lines.length - 1) {+ // Whitespace with no content at all.+ return [];+ }+ leading += `${lines[index]}\n`;+ index++;+ }+ while (index < lines.length) {+ const start = index;+ let fence: string | null = null;+ while (index < lines.length) {+ const line = lines[index];+ if (fence != null) {+ index++;+ const close = new RegExp(+ `^ {0,3}${fence[0]}{${fence.length},}[ \\t]*\\r?$`,+ );+ if (close.test(line)) {+ fence = null;+ }+ continue;+ }+ if (BLANK_LINE.test(line)) {+ break;+ }+ const open = FENCE_OPEN.exec(line);+ if (open != null) {+ fence = open[1];+ }+ index++;+ }+ let content = lines.slice(start, index).join('\n');+ let trailing = '';+ // A CRLF line ending belongs to the trailing text, not the content.+ if (content.endsWith('\r')) {+ content = content.slice(0, -1);+ trailing = '\r';+ }+ while (index < lines.length && BLANK_LINE.test(lines[index])) {+ trailing += `\n${lines[index]}`;+ index++;+ }+ if (index < lines.length) {+ // The line ending before the next chunk's first line.+ trailing += '\n';+ }+ chunks.push({+ leading: chunks.length === 0 ? leading : '',+ content,+ trailing,+ });+ }+ return chunks;+}++/** Lines without the carriage return before each line feed. */+function withoutCarriageReturns(text: string): string {+ return text.replace(/\r(?=\n|$)/g, '');+}++/** The first line ending in `text`, or `fallback` when it has none. */+function lineEndingOf(text: string, fallback: string): string {+ const index = text.indexOf('\n');+ if (index === -1) {+ return fallback;+ }+ return index > 0 && text[index - 1] === '\r' ? '\r\n' : '\n';+}++/** Rewrites every line ending in `text` as `lineEnding`. */+function withLineEnding(text: string, lineEnding: string): string {+ const lf = text.replace(/\r\n/g, '\n');+ return lineEnding === '\n' ? lf : lf.replace(/\n/g, lineEnding);+}++/**+ * A 64-bit hash of `text`, from two independent 32-bit FNV-1a passes. Only+ * equality matters: it tells an unchanged group from a changed one without+ * storing the canonical Markdown itself.+ */+function hashOf(text: string): string {+ let first = 0x811c9dc5;+ let second = 0x01000193 ^ text.length;+ for (let index = 0; index < text.length; index++) {+ const code = text.charCodeAt(index);+ first = Math.imul(first ^ code, 0x01000193) >>> 0;+ second = Math.imul(second ^ code, 0x5bd1e995) >>> 0;+ }+ return first.toString(36) + second.toString(36).padStart(7, '0');+}++let importCount = 0;++/** An id no other import in this or any other document shares. */+function nextImportId(): string {+ importCount++;+ return `${Math.random().toString(36).slice(2, 8)}${importCount.toString(36)}`;+}++/**+ * Imports Markdown into the editor's root and records its authored bytes. Runs+ * two discrete updates: the first imports every chunk and stamps its nodes+ * with the chunk's group id; the second runs after node transforms have+ * settled the tree (adjacent lists merge, for example), so each group covers+ * exactly the chunks that ended up in its nodes.+ */+export function importMarkdownKeepingSource(+ editor: LexicalEditor,+ markdown: string,+ transformers: Array<Transformer>,+): void {+ const importId = nextImportId();+ const byteOrderMark = markdown.startsWith('\uFEFF');+ const body = byteOrderMark ? markdown.slice(1) : markdown;+ const chunks = splitMarkdownChunks(body);+ const lineEnding = lineEndingOf(body, '\n');+ editor.update(+ () => {+ const root = $getRoot();+ root.clear();+ chunks.forEach((chunk, index) => {+ // The holder is attached while Lexical imports into it: Lexical only+ // continues a paragraph, list item, or quote onto the next line+ // inside an attached tree, and would otherwise start a new paragraph+ // at every line ending.+ const holder = $createParagraphNode();+ root.append(holder);+ // Lexical imports LF lines; the record keeps the authored endings.+ $convertFromMarkdownString(+ withoutCarriageReturns(chunk.content),+ transformers,+ holder,+ );+ for (const node of holder.getChildren()) {+ $setState(node, groupState, {group: `${importId}:${index}`});+ }+ for (const node of holder.getChildren()) {+ holder.insertBefore(node);+ }+ holder.remove();+ });+ if (root.getChildrenSize() === 0) {+ // Nothing to import: keep one empty paragraph, as Lexical does.+ root.append($createParagraphNode());+ }+ },+ {discrete: true},+ );+ editor.update(+ () => {+ $recordGroups(chunks, importId, transformers);+ const root = $getRoot();+ const hasGroups = root+ .getChildren()+ .some(node => $getState(node, groupState)?.content != null);+ $setState(root, documentState, {+ importId,+ byteOrderMark,+ leading: hasGroups ? (chunks[0]?.leading ?? '') : '',+ trailing: hasGroups+ ? (chunks[chunks.length - 1]?.trailing ?? '')+ : body,+ lineEnding,+ });+ },+ {discrete: true},+ );+}++/**+ * Turns the first pass's chunk stamps into groups. Consecutive nodes stamped+ * with one chunk form a group, and the group also covers every later chunk up+ * to the next group's: those chunks merged into its nodes or imported to+ * nothing. Chunks before the first group become part of it.+ */+function $recordGroups(+ chunks: ReadonlyArray<MarkdownChunk>,+ importId: string,+ transformers: Array<Transformer>,+): void {+ const children = $getRoot().getChildren();+ const chunkOf = (node: LexicalNode): number | null => {+ const group = $getState(node, groupState)?.group;+ if (group == null || !group.startsWith(`${importId}:`)) {+ return null;+ }+ return Number(group.slice(importId.length + 1));+ };+ let index = 0;+ let isFirstGroup = true;+ while (index < children.length) {+ const firstChunk = chunkOf(children[index]);+ if (firstChunk == null) {+ index++;+ continue;+ }+ const group: Array<LexicalNode> = [];+ while (index < children.length && chunkOf(children[index]) === firstChunk) {+ group.push(children[index]);+ index++;+ }+ const nextChunk =+ index === children.length+ ? chunks.length+ : (chunkOf(children[index]) ?? chunks.length);+ const startChunk = isFirstGroup ? 0 : firstChunk;+ isFirstGroup = false;+ const covered = chunks.slice(startChunk, nextChunk);+ const content = covered+ .map(+ (chunk, position) =>+ (position === 0 ? '' : chunk.leading) ++ (position === covered.length - 1+ ? chunk.content+ : chunk.content + chunk.trailing),+ )+ .join('');+ const isLastGroup = index === children.length;+ const trailing = isLastGroup+ ? ''+ : (covered[covered.length - 1]?.trailing ?? '');+ const record: GroupRecord = {+ group: `${importId}:${firstChunk}`,+ size: group.length,+ content,+ trailing,+ canonicalHash: $canonicalMarkdown(group, transformers).hash,+ lineEnding: lineEndingOf(+ content + (covered[covered.length - 1]?.trailing ?? ''),+ '\n',+ ),+ };+ group.forEach((node, position) => {+ $setState(+ node,+ groupState,+ position === 0 ? record : {group: record.group},+ );+ });+ }+}++/**+ * An element that lists `nodes` as its children without adopting them, so+ * Lexical's exporter can read a run of top-level nodes on its own. The+ * exporter only ever asks the root it is given for its children.+ */+function childrenOf(nodes: ReadonlyArray<LexicalNode>): ElementNode {+ return {getChildren: () => [...nodes]} as unknown as ElementNode;+}++/** Every node in the runs' subtrees, in document order. */+function descendantsOf(nodes: ReadonlyArray<LexicalNode>): Array<LexicalNode> {+ const out: Array<LexicalNode> = [];+ const visit = (node: LexicalNode) => {+ out.push(node);+ if ($isElementNode(node)) {+ node.getChildren().forEach(visit);+ }+ };+ nodes.forEach(visit);+ return out;+}++/**+ * Canonical Markdown per run of nodes, keyed by the run's first node. Lexical+ * keeps a node's object across editor states until that node itself changes,+ * so a run whose every descendant is the same object as last time is+ * unchanged and costs a walk instead of an export.+ */+const canonicalCache = new WeakMap<+ LexicalNode,+ {+ readonly descendants: ReadonlyArray<LexicalNode>;+ readonly transformers: ReadonlyArray<Transformer>;+ readonly markdown: string;+ readonly hash: string;+ }+>();++function $canonicalMarkdown(+ nodes: ReadonlyArray<LexicalNode>,+ transformers: Array<Transformer>,+): {readonly markdown: string; readonly hash: string} {+ const descendants = descendantsOf(nodes);+ const cached = canonicalCache.get(nodes[0]);+ if (+ cached != null &&+ cached.transformers === transformers &&+ cached.descendants.length === descendants.length &&+ cached.descendants.every((node, index) => node === descendants[index])+ ) {+ return cached;+ }+ const markdown = $convertToMarkdownString(transformers, childrenOf(nodes));+ const entry = {descendants, transformers, markdown, hash: hashOf(markdown)};+ canonicalCache.set(nodes[0], entry);+ return entry;+}++/** Line starts that would turn literal text into a block structure. */+const LINE_START_SYNTAX: ReadonlyArray<RegExp> = [+ // ATX heading, block quote, bullet list item.+ /^#{1,6}(?=[ \t]|$)/,+ /^>/,+ /^[-+](?=[ \t]|$)/,+ // Setext underline or thematic break made of `=` or `-`.+ /^[=-](?=[=\- \t]*$)/,+ // Table delimiter row.+ /^[|:](?=[|:\- \t]*-[|:\- \t]*$)/,+];+// An ordered list item escapes its delimiter, not its first character.+const ORDERED_LIST_START = /^(\d{1,9})([.)])(?=[ \t]|$)/;++// Inline syntax Lexical's export leaves unescaped: link and image brackets and+// character references.+const INLINE_SYNTAX =+ /[[\]]|&(?=#[0-9]{1,7};|#[xX][0-9a-fA-F]{1,6};|[A-Za-z][A-Za-z0-9]*;)/g;++const PRIVATE_USE_RANGES: ReadonlyArray<readonly [number, number]> = [+ [0xe000, 0xf8ff],+ [0xf0000, 0xffffd],+ [0x100000, 0x10fffd],+];++/**+ * A token that appears nowhere in `text`. There are 137,468 private-use code+ * points, so a text shorter than that always misses one of them; a longer+ * text cannot contain every one of the 137,468² ordered pairs.+ */+export function absentToken(text: string): string {+ const present = new Set(text);+ for (const [first, last] of PRIVATE_USE_RANGES) {+ for (let codePoint = first; codePoint <= last; codePoint++) {+ const candidate = String.fromCodePoint(codePoint);+ if (!present.has(candidate)) {+ return candidate;+ }+ }+ }+ for (const [first, last] of PRIVATE_USE_RANGES) {+ for (let a = first; a <= last; a++) {+ for (let b = first; b <= last; b++) {+ const candidate = String.fromCodePoint(a, b);+ if (!text.includes(candidate)) {+ return candidate;+ }+ }+ }+ }+ throw new Error('No escape token is absent from the text');+}++/**+ * A view of `node` whose text marks every character that needs a backslash+ * with `token`. Views delegate everything else to the node they wrap, so+ * Lexical's exporter reads them like the real tree without changing it.+ */+function markedView(node: LexicalNode, token: string): LexicalNode {+ if ($isTextNode(node)) {+ if (node.hasFormat('code') || $isCodeNode(node.getParent())) {+ return node;+ }+ let text = node+ .getTextContent()+ .replace(INLINE_SYNTAX, match => token + match);+ const previous = node.getPreviousSibling();+ if (previous == null || $isLineBreakNode(previous)) {+ const ordered = ORDERED_LIST_START.exec(text);+ if (ordered != null) {+ text = ordered[1] + token + text.slice(ordered[1].length);+ } else if (LINE_START_SYNTAX.some(pattern => pattern.test(text))) {+ text = token + text;+ }+ }+ const view = Object.create(node) as typeof node;+ view.getTextContent = () => text;+ return view;+ }+ if ($isElementNode(node) && !$isCodeNode(node)) {+ const children = node.getChildren().map(child => markedView(child, token));+ const view = Object.create(node) as typeof node;+ view.getChildren = <T extends LexicalNode>() => children as Array<T>;+ return view;+ }+ return node;+}++/**+ * The canonical Markdown of a changed group, with literal text escaped so it+ * imports again as the structure the editor showed (spec:AST-062 FR3).+ */+function $regeneratedMarkdown(+ nodes: ReadonlyArray<LexicalNode>,+ canonical: string,+ transformers: Array<Transformer>,+): string {+ // The token is absent from the plain export and from every text the views+ // mark, so each token in the marked export is one of the marks.+ const token = absentToken(+ canonical + nodes.map(node => node.getTextContent()).join(''),+ );+ const marked = $convertToMarkdownString(+ transformers,+ childrenOf(nodes.map(node => markedView(node, token))),+ );+ return marked.split(token).join('\\');+}++interface ExportPiece {+ readonly text: string;+ /** Recorded bytes after the piece, when they belong to this document. */+ readonly trailing: string | null;+}++const ENDS_WITH_BLANK_LINE = /\n[ \t]*\r?\n[ \t\r]*$/;++/**+ * Exports the root per spec:AST-062: unchanged groups as authored, changed and+ * new blocks in canonical form, all in the document's envelope. Reads the tree+ * without changing it, so it runs in a read of the live editor state.+ */+export function $exportMarkdownKeepingSource(+ transformers: ReadonlyArray<Transformer>,+): string {+ const transformerList = transformers as Array<Transformer>;+ const root = $getRoot();+ const document = $getState(root, documentState);+ const lineEnding = document?.lineEnding ?? '\n';+ const children = root.getChildren();+ const pieces: Array<ExportPiece> = [];+ let index = 0;+ while (index < children.length) {+ const first = children[index];+ const record = $getState(first, groupState);+ const group: Array<LexicalNode> = [first];+ index++;+ if (record?.content != null) {+ while (+ index < children.length &&+ $getState(children[index], groupState)?.group === record.group &&+ $getState(children[index], groupState)?.content == null+ ) {+ group.push(children[index]);+ index++;+ }+ }+ const canonical = $canonicalMarkdown(group, transformerList);+ // A group imported into another document keeps its content but takes this+ // document's line ending and separators.+ const isOwn =+ document != null &&+ record?.group.startsWith(`${document.importId}:`) === true;+ if (+ record?.content != null &&+ group.length === record.size &&+ canonical.hash === record.canonicalHash+ ) {+ pieces.push({+ text: isOwn+ ? record.content+ : withLineEnding(record.content, lineEnding),+ trailing: isOwn ? (record.trailing ?? null) : null,+ });+ continue;+ }+ const regenerated = $regeneratedMarkdown(+ group,+ canonical.markdown,+ transformerList,+ );+ pieces.push({+ text: withLineEnding(+ regenerated,+ isOwn && record?.lineEnding != null ? record.lineEnding : lineEnding,+ ),+ trailing: isOwn ? (record?.trailing ?? null) : null,+ });+ }+ const separator = lineEnding + lineEnding;+ let output =+ (document?.byteOrderMark === true ? '\uFEFF' : '') ++ (document?.leading ?? '');+ pieces.forEach((piece, position) => {+ output += piece.text;+ if (position < pieces.length - 1) {+ output +=+ piece.trailing != null && ENDS_WITH_BLANK_LINE.test(piece.trailing)+ ? piece.trailing+ : separator;+ }+ });+ return output + (document?.trailing ?? '');+}diff --git a/packages/richtext/src/markdownTable.test.tsx b/packages/richtext/src/markdownTable.test.tsxindex b347951a88..dac7f49d4e 100644--- a/packages/richtext/src/markdownTable.test.tsx+++ b/packages/richtext/src/markdownTable.test.tsx@@ -108,9 +108,8 @@ describe('GFM tables', () => {['Name', 'Role'],['Ada', 'Engineer'],]);- expect(roundTrip(source)).toBe(- '| Name | Role |\n| --- | --- |\n| Ada | Engineer |',- );+ // Imported tables come back exactly as written (spec:AST-062).+ expect(roundTrip(source)).toBe(source);});it('leaves a line with pipes but no delimiter row as text', () => {