Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(richtext): import, edit, and export GFM tables (#6983)

Cindy Zhang1eee9557e335
diff --git a/packages/richtext/package.json b/packages/richtext/package.json
index 4501e3de59..15dc2cbc61 100644
--- a/packages/richtext/package.json
+++ b/packages/richtext/package.json
@@ -3,7 +3,7 @@
"displayName": "Rich Text",
"version": "0.1.9",
"private": true,
- "description": "Astryx rich text — a Lexical-based rich text editor and viewer. Published to npm only under the @canary dist-tag for early testing; never released as a stable (latest) version.",
+ "description": "Astryx rich text \u2014 a Lexical-based rich text editor and viewer. Published to npm only under the @canary dist-tag for early testing; never released as a stable (latest) version.",
"author": "Meta Open Source",
"license": "MIT",
"homepage": "https://github.com/facebook/astryx#readme",
@@ -25,7 +25,7 @@
],
"astryx": {
"canaryOnly": true,
- "_comment": "Published ONLY to the @canary dist-tag (see .github/workflows/release.yml). Never released as a stable `latest` release. `private: true` is intentional and must stay — it is npm\"s hard guarantee against an accidental stable publish."
+ "_comment": "Published ONLY to the @canary dist-tag (see .github/workflows/release.yml). Never released as a stable `latest` release. `private: true` is intentional and must stay \u2014 it is npm\"s hard guarantee against an accidental stable publish."
},
"type": "module",
"main": "./dist/index.js",
@@ -76,6 +76,7 @@
"@lexical/rich-text": "^0.46.0",
"@lexical/selection": "^0.46.0",
"@lexical/code": "^0.46.0",
+ "@lexical/table": "^0.46.0",
"@lexical/utils": "^0.46.0"
},
"peerDependenciesMeta": {
@@ -109,6 +110,9 @@
"@lexical/code": {
"optional": true
},
+ "@lexical/table": {
+ "optional": true
+ },
"@lexical/utils": {
"optional": true
}
@@ -129,6 +133,7 @@
"@lexical/react": "^0.46.0",
"@lexical/rich-text": "^0.46.0",
"@lexical/selection": "^0.46.0",
+ "@lexical/table": "^0.46.0",
"@lexical/utils": "^0.46.0",
"@stylexjs/babel-plugin": "catalog:",
"@testing-library/react": "catalog:",
diff --git a/packages/richtext/src/RichTextEditor.doc.mjs b/packages/richtext/src/RichTextEditor.doc.mjs
index d5207f2300..a2af3cd302 100644
--- a/packages/richtext/src/RichTextEditor.doc.mjs
+++ b/packages/richtext/src/RichTextEditor.doc.mjs
@@ -109,14 +109,14 @@ export const docs = {
name: 'hasMarkdownShortcuts',
type: 'boolean',
description:
- 'Enable Markdown shortcut typing (e.g. "# " for a heading). Uses the transformers prop (defaults to the standard @lexical/markdown transformers).',
+ 'Enable Markdown shortcut typing (e.g. "# " for a heading). Uses the transformers prop (defaults to the standard @lexical/markdown transformers plus GFM tables).',
default: 'true',
},
{
name: 'transformers',
type: 'ReadonlyArray<Transformer>',
description:
- 'Markdown transformers: the single source of truth for markdown behaviour. Defaults to the standard @lexical/markdown TRANSFORMERS. In Lexical the same array drives all three markdown operations (shortcut typing, markdown->state import, state->markdown export); this prop wires shortcut typing today and is the intended input for the serialization APIs added in later phases. Pass a custom array to support additional node types (e.g. transformers layered in via the nodes extension point) consistently across all three. Shortcut typing is only applied when hasMarkdownShortcuts is true.',
+ 'Markdown transformers: the single source of truth for markdown behaviour. Defaults to the standard @lexical/markdown TRANSFORMERS plus GFM tables; a custom array replaces the default, tables included. In Lexical the same array drives all three markdown operations (shortcut typing, markdown->state import, state->markdown export); this prop wires shortcut typing today and is the intended input for the serialization APIs added in later phases. Pass a custom array to support additional node types (e.g. transformers layered in via the nodes extension point) consistently across all three. Shortcut typing is only applied when hasMarkdownShortcuts is true.',
default: 'TRANSFORMERS',
},
{
@@ -185,6 +185,11 @@ export const docs = {
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.',
},
+ {
+ guidance: true,
+ description:
+ 'GFM pipe tables import, edit, and export by default. The first row renders as header cells, delimiter-row colons set each column alignment, rows shorter than the widest row gain empty cells, and a wide table scrolls inside its own wrapper. Arrow keys move between cells; Tab keeps its editor meaning, so Escape then Tab still leaves the editor. Tables export in the canonical form: outer pipes and three-dash delimiters. RichTextView renders the same tables. Install @lexical/table with the other lexical peers.',
+ },
{
guidance: true,
description:
diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsx
index f0d153f116..34005031bd 100644
--- a/packages/richtext/src/RichTextEditor.tsx
+++ b/packages/richtext/src/RichTextEditor.tsx
@@ -71,14 +71,12 @@ import {LinkPlugin} from '@lexical/react/LexicalLinkPlugin';
import {TabIndentationPlugin} from '@lexical/react/LexicalTabIndentationPlugin';
import {MarkdownShortcutPlugin} from '@lexical/react/LexicalMarkdownShortcutPlugin';
import {OnChangePlugin} from '@lexical/react/LexicalOnChangePlugin';
-import {
- TRANSFORMERS,
- $convertToMarkdownString,
- type Transformer,
-} from '@lexical/markdown';
+import {TablePlugin} from '@lexical/react/LexicalTablePlugin';
+import {$convertToMarkdownString, type Transformer} from '@lexical/markdown';
export type {Transformer} from '@lexical/markdown';
import {$generateHtmlFromNodes} from '@lexical/html';
import {DEFAULT_NODES} from './editorNodes';
+import {DEFAULT_TRANSFORMERS} from './markdownTable';
import {
BLUR_COMMAND,
COMMAND_PRIORITY_LOW,
@@ -399,13 +397,14 @@ export interface RichTextEditorProps extends Omit<
/**
* Whether to enable Markdown shortcut typing (e.g. `# ` for a heading,
* `- ` for a list). Uses the `transformers` prop (defaults to the standard
- * `@lexical/markdown` transformers).
+ * `@lexical/markdown` transformers plus GFM tables).
* @default true
*/
hasMarkdownShortcuts?: boolean;
/**
* Markdown transformers — the single source of truth for markdown behaviour.
- * Defaults to the standard `@lexical/markdown` `TRANSFORMERS`.
+ * Defaults to the standard `@lexical/markdown` `TRANSFORMERS` plus GFM
+ * tables. A custom array replaces the default, tables included.
*
* The same array drives all three markdown operations in Lexical (see the
* lexical-playground reference, where one `PLAYGROUND_TRANSFORMERS` array
@@ -497,7 +496,7 @@ export const RichTextEditor = forwardRef<
toolbar,
plugins,
hasMarkdownShortcuts = true,
- transformers = TRANSFORMERS,
+ transformers = DEFAULT_TRANSFORMERS,
hasAutoFocus = false,
tabEscapeHint = DEFAULT_TAB_ESCAPE_HINT,
maxLength,
@@ -671,6 +670,16 @@ export const RichTextEditor = forwardRef<
<HistoryPlugin />
<ListPlugin />
<LinkPlugin />
+ {/* Tab keeps its editor meaning inside a table (indent, and
+ Escape then Tab to leave the editor); arrow keys move
+ between cells. GFM tables have no merged cells or cell
+ colors, and a wide table scrolls inside its own wrapper. */}
+ <TablePlugin
+ hasCellMerge={false}
+ hasCellBackgroundColor={false}
+ hasTabHandler={false}
+ hasHorizontalScroll
+ />
<TabIndentationPlugin />
<TabFocusEscapePlugin />
{hasMarkdownShortcuts && (
diff --git a/packages/richtext/src/RichTextView.tsx b/packages/richtext/src/RichTextView.tsx
index b484382ca9..6138fb476a 100644
--- a/packages/richtext/src/RichTextView.tsx
+++ b/packages/richtext/src/RichTextView.tsx
@@ -27,10 +27,12 @@ import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
import {RichTextPlugin} from '@lexical/react/LexicalRichTextPlugin';
import {ContentEditable} from '@lexical/react/LexicalContentEditable';
import {LexicalErrorBoundary} from '@lexical/react/LexicalErrorBoundary';
+import {TablePlugin} from '@lexical/react/LexicalTablePlugin';
import {ListNode, ListItemNode} from '@lexical/list';
import {HeadingNode, QuoteNode} from '@lexical/rich-text';
import {LinkNode, AutoLinkNode} from '@lexical/link';
import {CodeNode, CodeHighlightNode} from '@lexical/code';
+import {TableNode, TableRowNode, TableCellNode} from '@lexical/table';
import type {
AnyLexicalExtension,
Klass,
@@ -54,6 +56,9 @@ const DEFAULT_NODES: ReadonlyArray<Klass<LexicalNode>> = [
AutoLinkNode,
CodeNode,
CodeHighlightNode,
+ TableNode,
+ TableRowNode,
+ TableCellNode,
];
/**
@@ -262,6 +267,14 @@ export function RichTextView({
extension={extensionRef.current}
contentEditable={null}>
<SyncValuePlugin value={value} />
+ {/* Same table configuration as the editor, so a wide table scrolls
+ inside its own wrapper instead of widening the page. */}
+ <TablePlugin
+ hasCellMerge={false}
+ hasCellBackgroundColor={false}
+ hasTabHandler={false}
+ hasHorizontalScroll
+ />
<RichTextPlugin
contentEditable={<ContentEditable {...VIEW_CONTENT_EDITABLE_PROPS} />}
placeholder={null}
diff --git a/packages/richtext/src/editorNodes.ts b/packages/richtext/src/editorNodes.ts
index 8a8a3256c0..c2a3649165 100644
--- a/packages/richtext/src/editorNodes.ts
+++ b/packages/richtext/src/editorNodes.ts
@@ -15,12 +15,13 @@ import {ListNode, ListItemNode} from '@lexical/list';
import {HeadingNode, QuoteNode} from '@lexical/rich-text';
import {LinkNode, AutoLinkNode} from '@lexical/link';
import {CodeNode, CodeHighlightNode} from '@lexical/code';
+import {TableNode, TableRowNode, TableCellNode} from '@lexical/table';
import type {Klass, LexicalNode} from 'lexical';
/**
* The default OSS node set registered with the editor: headings, quotes,
- * lists, links, and code. Extend via the `nodes` prop / option rather than
- * editing this list.
+ * lists, links, code, and tables. Extend via the `nodes` prop / option rather
+ * than editing this list.
*/
export const DEFAULT_NODES: ReadonlyArray<Klass<LexicalNode>> = [
HeadingNode,
@@ -31,4 +32,7 @@ export const DEFAULT_NODES: ReadonlyArray<Klass<LexicalNode>> = [
AutoLinkNode,
CodeNode,
CodeHighlightNode,
+ TableNode,
+ TableRowNode,
+ TableCellNode,
];
diff --git a/packages/richtext/src/editorTheme.ts b/packages/richtext/src/editorTheme.ts
index 884188f254..dabcb02299 100644
--- a/packages/richtext/src/editorTheme.ts
+++ b/packages/richtext/src/editorTheme.ts
@@ -120,6 +120,37 @@ const editorTheme = stylex.create({
borderRadius: radiusVars['--radius-inner'],
fontSize: '0.9em',
},
+ // GFM tables, styled like core Markdown's table: semibold secondary header
+ // text, a divider under every row but the last, and a wide table that
+ // scrolls inside its own wrapper instead of widening the editor.
+ tableScrollableWrapper: {
+ overflowX: 'auto',
+ maxWidth: '100%',
+ },
+ table: {
+ borderCollapse: 'collapse',
+ width: '100%',
+ marginBlock: spacingVars['--spacing-4'],
+ },
+ tableRow: {
+ borderBottomWidth: '1px',
+ borderBottomStyle: 'solid',
+ borderBottomColor: {
+ default: colorVars['--color-border'],
+ ':last-child': 'transparent',
+ },
+ },
+ tableCell: {
+ paddingBlock: spacingVars['--spacing-2'],
+ paddingInline: spacingVars['--spacing-2'],
+ textAlign: 'start',
+ verticalAlign: 'middle',
+ overflowWrap: 'break-word',
+ },
+ tableCellHeader: {
+ fontWeight: fontWeightVars['--font-weight-semibold'],
+ color: colorVars['--color-text-secondary'],
+ },
code: {
display: 'block',
fontFamily: typographyVars['--font-family-code'],
@@ -181,5 +212,11 @@ export function sharedEditorTheme(): EditorThemeClasses {
code: stylex.props(editorTheme.textCode).className,
},
code: stylex.props(editorTheme.code).className,
+ table: stylex.props(editorTheme.table).className,
+ tableRow: stylex.props(editorTheme.tableRow).className,
+ tableCell: stylex.props(editorTheme.tableCell).className,
+ tableCellHeader: stylex.props(editorTheme.tableCellHeader).className,
+ tableScrollableWrapper: stylex.props(editorTheme.tableScrollableWrapper)
+ .className,
};
}
diff --git a/packages/richtext/src/markdownSerializers.ts b/packages/richtext/src/markdownSerializers.ts
index d53eaa4a29..cc1753f34b 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), and the shared
- * DEFAULT_NODES set.
+ * ($convertFromMarkdownString / $convertToMarkdownString), the shared
+ * DEFAULT_NODES set, and DEFAULT_TRANSFORMERS.
* @output Standalone Markdown <-> serialized EditorState helpers:
* markdownToEditorStateJSON, editorStateJSONToMarkdown.
* @position Re-exported from RichTextEditor/index.ts and the @astryxdesign/richtext
@@ -24,20 +24,21 @@
import {createHeadlessEditor} from '@lexical/headless';
import {
- TRANSFORMERS,
$convertFromMarkdownString,
$convertToMarkdownString,
type Transformer,
} from '@lexical/markdown';
import {DEFAULT_NODES} from './editorNodes';
+import {DEFAULT_TRANSFORMERS} from './markdownTable';
import type {Klass, LexicalNode} from 'lexical';
/** Options shared by the Markdown serializer helpers. */
export interface MarkdownSerializerOptions {
/**
- * Markdown transformers to use. Defaults to the standard `@lexical/markdown`
- * `TRANSFORMERS`. Pass the same array you give `RichTextEditor`'s
- * `transformers` prop so content round-trips consistently.
+ * Markdown transformers to use. Defaults to the editor's default set: the
+ * standard `@lexical/markdown` `TRANSFORMERS` plus GFM tables. Pass the same
+ * array you give `RichTextEditor`'s `transformers` prop so content
+ * round-trips consistently.
*/
transformers?: ReadonlyArray<Transformer>;
/**
@@ -72,7 +73,7 @@ export function markdownToEditorStateJSON(
markdown: string,
options: MarkdownSerializerOptions = {},
): string {
- const {transformers = TRANSFORMERS, nodes} = options;
+ const {transformers = DEFAULT_TRANSFORMERS, nodes} = options;
const editor = createSerializerEditor(nodes);
editor.update(
() => {
@@ -97,7 +98,7 @@ export function editorStateJSONToMarkdown(
editorStateJSON: string,
options: MarkdownSerializerOptions = {},
): string {
- const {transformers = TRANSFORMERS, nodes} = options;
+ const {transformers = DEFAULT_TRANSFORMERS, nodes} = options;
const editor = createSerializerEditor(nodes);
const state = editor.parseEditorState(editorStateJSON);
return state.read(() => $convertToMarkdownString([...transformers]));
diff --git a/packages/richtext/src/markdownTable.test.tsx b/packages/richtext/src/markdownTable.test.tsx
new file mode 100644
index 0000000000..c921c843a1
--- /dev/null
+++ b/packages/richtext/src/markdownTable.test.tsx
@@ -0,0 +1,197 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect} from 'vitest';
+import {render, waitFor} from '@testing-library/react';
+import {TableCellHeaderStates} from '@lexical/table';
+import {RichTextEditor} from './RichTextEditor';
+import {RichTextView} from './RichTextView';
+import {
+ editorStateJSONToMarkdown,
+ markdownToEditorStateJSON,
+} from './markdownSerializers';
+
+interface SerializedNode {
+ type: string;
+ children?: Array<SerializedNode>;
+ text?: string;
+ format?: string | number;
+ headerState?: number;
+}
+
+function roundTrip(markdown: string): string {
+ return editorStateJSONToMarkdown(markdownToEditorStateJSON(markdown));
+}
+
+function topLevel(markdown: string): Array<SerializedNode> {
+ const state = JSON.parse(markdownToEditorStateJSON(markdown)) as {
+ root: SerializedNode;
+ };
+ return state.root.children ?? [];
+}
+
+function onlyTable(markdown: string): SerializedNode {
+ const tables = topLevel(markdown).filter(node => node.type === 'table');
+ expect(tables).toHaveLength(1);
+ return tables[0];
+}
+
+function rows(table: SerializedNode): Array<Array<SerializedNode>> {
+ return (table.children ?? []).map(row => row.children ?? []);
+}
+
+function textOf(node: SerializedNode): string {
+ if (node.text != null) {
+ return node.text;
+ }
+ return (node.children ?? []).map(textOf).join('');
+}
+
+describe('GFM tables', () => {
+ it('imports a pipe table with a header row', () => {
+ const table = onlyTable(
+ '| Name | Role |\n| --- | --- |\n| Ada | Engineer |',
+ );
+ const [header, body] = rows(table);
+ expect(header.map(textOf)).toEqual(['Name', 'Role']);
+ expect(body.map(textOf)).toEqual(['Ada', 'Engineer']);
+ expect(header.map(cell => cell.headerState)).toEqual([
+ TableCellHeaderStates.ROW,
+ TableCellHeaderStates.ROW,
+ ]);
+ expect(body.map(cell => cell.headerState)).toEqual([
+ TableCellHeaderStates.NO_STATUS,
+ TableCellHeaderStates.NO_STATUS,
+ ]);
+ });
+
+ it('exports the canonical form unchanged', () => {
+ const source = '| Name | Role |\n| --- | --- |\n| Ada | Engineer |';
+ expect(roundTrip(source)).toBe(source);
+ });
+
+ it('keeps each column alignment', () => {
+ const source =
+ '| Left | Center | Right | None |\n| :--- | :---: | ---: | --- |\n| a | b | c | d |';
+ const [header, body] = rows(onlyTable(source));
+ expect(header.map(cell => cell.format)).toEqual([
+ 'start',
+ 'center',
+ 'end',
+ '',
+ ]);
+ expect(body.map(cell => cell.format)).toEqual([
+ 'start',
+ 'center',
+ 'end',
+ '',
+ ]);
+ expect(roundTrip(source)).toBe(source);
+ });
+
+ it('keeps escaped pipes inside cells, including inline code', () => {
+ const source = '| a \\| b | c |\n| --- | --- |\n| `x \\| y` | d |';
+ const [header, body] = rows(onlyTable(source));
+ expect(textOf(header[0])).toBe('a | b');
+ expect(textOf(body[0])).toBe('x | y');
+ expect(roundTrip(source)).toBe(source);
+ });
+
+ it('keeps inline formatting and links inside cells', () => {
+ const source =
+ '| **Bold** | [Link](https://example.com) |\n| --- | --- |\n| `code` | *em* |';
+ expect(roundTrip(source)).toBe(source);
+ });
+
+ it('recognizes a table without outer pipes, as core Markdown does', () => {
+ const source = 'Name | Role\n--- | ---\nAda | Engineer';
+ expect(rows(onlyTable(source)).map(row => row.map(textOf))).toEqual([
+ ['Name', 'Role'],
+ ['Ada', 'Engineer'],
+ ]);
+ expect(roundTrip(source)).toBe(
+ '| Name | Role |\n| --- | --- |\n| Ada | Engineer |',
+ );
+ });
+
+ it('leaves a line with pipes but no delimiter row as text', () => {
+ const nodes = topLevel('a | b\n\nNext paragraph');
+ expect(nodes.map(node => node.type)).toEqual(['paragraph', 'paragraph']);
+ expect(textOf(nodes[0])).toBe('a | b');
+ });
+
+ it('pads short rows so every row has every column and no cell is dropped', () => {
+ const table = onlyTable(
+ '| A | B | C |\n| --- | --- | --- |\n| 1 |\n| 1 | 2 | 3 | 4 |',
+ );
+ expect(rows(table).map(row => row.map(textOf))).toEqual([
+ ['A', 'B', 'C', ''],
+ ['1', '', '', ''],
+ ['1', '2', '3', '4'],
+ ]);
+ });
+
+ it('ends a table at a blank line or at a line without a pipe', () => {
+ expect(
+ topLevel('| A |\n| --- |\n| 1 |\n\nAfter').map(node => node.type),
+ ).toEqual(['table', 'paragraph']);
+ const nodes = topLevel('| A |\n| --- |\n| 1 |\nAfter');
+ expect(nodes.map(node => node.type)).toEqual(['table', 'paragraph']);
+ expect(rows(nodes[0])).toHaveLength(2);
+ });
+
+ it('keeps the blocks around a table', () => {
+ const source = '# Title\n\n| A | B |\n| --- | --- |\n| 1 | 2 |\n\nAfter';
+ expect(topLevel(source).map(node => node.type)).toEqual([
+ 'heading',
+ 'table',
+ 'paragraph',
+ ]);
+ expect(roundTrip(source)).toBe(source);
+ });
+
+ it('renders header and body cells inside a scroll wrapper in the editor', async () => {
+ const {container} = render(
+ <RichTextEditor
+ label="Notes"
+ defaultValue={markdownToEditorStateJSON(
+ '| Name | Role |\n| --- | --- |\n| Ada | Engineer |',
+ )}
+ />,
+ );
+ expect(
+ [...container.querySelectorAll('th')].map(cell => cell.textContent),
+ ).toEqual(['Name', 'Role']);
+ expect(
+ [...container.querySelectorAll('td')].map(cell => cell.textContent),
+ ).toEqual(['Ada', 'Engineer']);
+ // A wide table scrolls inside its own wrapper rather than widening the
+ // editor. The table plugin re-renders existing tables into the wrapper
+ // after mount.
+ await waitFor(() => {
+ const wrapper = container.querySelector('table')?.parentElement;
+ expect(wrapper?.tagName).toBe('DIV');
+ expect(wrapper?.getAttribute('contenteditable')).toBeNull();
+ });
+ });
+
+ it('renders a table from the editor in RichTextView, inside a scroll wrapper', async () => {
+ const {container} = render(
+ <RichTextView
+ value={markdownToEditorStateJSON(
+ '| Name | Role |\n| --- | --- |\n| Ada | Engineer |',
+ )}
+ />,
+ );
+ expect(
+ [...container.querySelectorAll('th')].map(cell => cell.textContent),
+ ).toEqual(['Name', 'Role']);
+ expect(
+ [...container.querySelectorAll('td')].map(cell => cell.textContent),
+ ).toEqual(['Ada', 'Engineer']);
+ await waitFor(() => {
+ const wrapper = container.querySelector('table')?.parentElement;
+ expect(wrapper?.tagName).toBe('DIV');
+ expect(wrapper?.getAttribute('contenteditable')).toBeNull();
+ });
+ });
+});
diff --git a/packages/richtext/src/markdownTable.ts b/packages/richtext/src/markdownTable.ts
new file mode 100644
index 0000000000..983a22d6d8
--- /dev/null
+++ b/packages/richtext/src/markdownTable.ts
@@ -0,0 +1,243 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file markdownTable.ts
+ * @input Uses @lexical/markdown (multiline element transformer, inline text
+ * transformers) and the @lexical/table nodes.
+ * @output Exports TABLE, the GFM pipe-table transformer, and DEFAULT_TRANSFORMERS,
+ * the editor's default Markdown transformers (Lexical's standard set plus TABLE).
+ * @position Internal to @astryxdesign/richtext. RichTextEditor.tsx (shortcuts,
+ * getMarkdown) and markdownSerializers.ts (headless import/export) default to
+ * DEFAULT_TRANSFORMERS so tables import, edit, and export the same way.
+ *
+ * SYNC: Table recognition mirrors core Markdown's parser (a line with a pipe
+ * followed by a delimiter row; body rows continue while they contain a pipe),
+ * so the same source is a table on both surfaces. Keep the two in step.
+ */
+
+import {
+ $convertFromMarkdownString,
+ $convertToMarkdownString,
+ TEXT_FORMAT_TRANSFORMERS,
+ TEXT_MATCH_TRANSFORMERS,
+ TRANSFORMERS,
+ type MultilineElementTransformer,
+ type Transformer,
+} from '@lexical/markdown';
+import {
+ $createTableCellNode,
+ $createTableNode,
+ $createTableRowNode,
+ $isTableCellNode,
+ $isTableNode,
+ $isTableRowNode,
+ TableCellHeaderStates,
+ TableCellNode,
+ TableNode,
+ TableRowNode,
+} from '@lexical/table';
+import type {ElementFormatType} from 'lexical';
+
+/**
+ * Cells hold inline Markdown only, so they are imported and exported with the
+ * inline transformers.
+ */
+const CELL_TRANSFORMERS: Array<Transformer> = [
+ ...TEXT_FORMAT_TRANSFORMERS,
+ ...TEXT_MATCH_TRANSFORMERS,
+];
+
+type ColumnAlignment = 'left' | 'center' | 'right' | null;
+
+/**
+ * Splits a row into trimmed cell sources: one leading pipe, trailing spaces,
+ * and one trailing pipe are dropped, and the rest splits on unescaped pipes.
+ * An escaped pipe stays escaped for the cell's inline import.
+ */
+function splitTableRow(line: string): Array<string> {
+ let start = 0;
+ let end = line.length;
+ if (line.startsWith('|')) {
+ start = 1;
+ while (start < end && line[start] === ' ') {
+ start++;
+ }
+ }
+ while (end > start && line[end - 1] === ' ') {
+ end--;
+ }
+ if (end > start && line[end - 1] === '|') {
+ end--;
+ }
+ const content = line.slice(start, end);
+ const cells: Array<string> = [];
+ let current = '';
+ for (let index = 0; index < content.length; index++) {
+ const character = content[index];
+ if (character === '\\' && content[index + 1] === '|') {
+ current += '\\|';
+ index++;
+ } else if (character === '|') {
+ cells.push(current.trim());
+ current = '';
+ } else {
+ current += character;
+ }
+ }
+ cells.push(current.trim());
+ return cells;
+}
+
+/** A delimiter row: every non-empty cell is dashes with optional colons. */
+function isDelimiterRow(line: string | undefined): boolean {
+ if (line == null || !line.includes('|')) {
+ return false;
+ }
+ const cells = line
+ .split('|')
+ .map(cell => cell.trim())
+ .filter(cell => cell.length > 0);
+ return cells.length > 0 && cells.every(cell => /^:?-+:?$/.test(cell));
+}
+
+function columnAlignment(delimiterCell: string): ColumnAlignment {
+ const left = delimiterCell.startsWith(':');
+ const right = delimiterCell.endsWith(':');
+ if (left && right) {
+ return 'center';
+ }
+ return right ? 'right' : left ? 'left' : null;
+}
+
+/**
+ * Alignment is stored as the cell's element format. Left and right map to
+ * logical start and end, so an aligned column follows the reading direction
+ * the way core Markdown's table does.
+ */
+const ALIGNMENT_FORMAT: Record<
+ NonNullable<ColumnAlignment>,
+ ElementFormatType
+> = {left: 'start', center: 'center', right: 'end'};
+
+function delimiterFor(format: ElementFormatType): string {
+ switch (format) {
+ case 'left':
+ case 'start':
+ return ':---';
+ case 'center':
+ return ':---:';
+ case 'right':
+ case 'end':
+ return '---:';
+ default:
+ return '---';
+ }
+}
+
+function $createCell(
+ source: string,
+ isHeader: boolean,
+ alignment: ColumnAlignment,
+): TableCellNode {
+ const cell = $createTableCellNode(
+ isHeader ? TableCellHeaderStates.ROW : TableCellHeaderStates.NO_STATUS,
+ );
+ // The pipe was only escaped to keep it out of the row split.
+ $convertFromMarkdownString(
+ source.replace(/\\\|/g, '|'),
+ CELL_TRANSFORMERS,
+ cell,
+ );
+ if (alignment != null) {
+ cell.setFormat(ALIGNMENT_FORMAT[alignment]);
+ }
+ return cell;
+}
+
+function cellMarkdown(cell: TableCellNode): string {
+ // A cell is one line of Markdown, so paragraph breaks inside it become
+ // spaces, and literal pipes are escaped to stay inside the cell.
+ return $convertToMarkdownString(CELL_TRANSFORMERS, cell)
+ .replace(/\s*\n+\s*/g, ' ')
+ .replace(/\|/g, '\\|')
+ .trim();
+}
+
+/**
+ * GFM pipe tables. The header row is the first row and renders as header
+ * cells; delimiter-row colons set each column's alignment; rows shorter than
+ * the widest row gain empty cells, so no cell is dropped. Export writes the
+ * canonical form: outer pipes, one space of padding, and three-dash delimiters.
+ */
+export const TABLE: MultilineElementTransformer = {
+ dependencies: [TableNode, TableRowNode, TableCellNode],
+ export(node) {
+ if (!$isTableNode(node)) {
+ return null;
+ }
+ const rows = node.getChildren().filter($isTableRowNode);
+ const lines: Array<string> = [];
+ rows.forEach((row, rowIndex) => {
+ const cells = row.getChildren().filter($isTableCellNode);
+ lines.push(`| ${cells.map(cellMarkdown).join(' | ')} |`);
+ if (rowIndex === 0) {
+ lines.push(
+ `| ${cells.map(cell => delimiterFor(cell.getFormatType())).join(' | ')} |`,
+ );
+ }
+ });
+ return lines.join('\n');
+ },
+ regExpStart: /\|/,
+ handleImportAfterStartMatch({lines, rootNode, startLineIndex}) {
+ if (!isDelimiterRow(lines[startLineIndex + 1])) {
+ return null;
+ }
+ const alignments = splitTableRow(lines[startLineIndex + 1]).map(
+ columnAlignment,
+ );
+ const rowSources: Array<Array<string>> = [
+ splitTableRow(lines[startLineIndex]),
+ ];
+ let lastLineIndex = startLineIndex + 1;
+ while (
+ lastLineIndex + 1 < lines.length &&
+ lines[lastLineIndex + 1].includes('|') &&
+ lines[lastLineIndex + 1].trim() !== ''
+ ) {
+ lastLineIndex++;
+ rowSources.push(splitTableRow(lines[lastLineIndex]));
+ }
+ const columnCount = Math.max(...rowSources.map(cells => cells.length));
+ const table = $createTableNode();
+ rowSources.forEach((cells, rowIndex) => {
+ const row = $createTableRowNode();
+ for (let column = 0; column < columnCount; column++) {
+ row.append(
+ $createCell(
+ cells[column] ?? '',
+ rowIndex === 0,
+ alignments[column] ?? null,
+ ),
+ );
+ }
+ table.append(row);
+ });
+ rootNode.append(table);
+ return [true, lastLineIndex];
+ },
+ replace() {
+ // Every table imports through handleImportAfterStartMatch.
+ return false;
+ },
+ type: 'multiline-element',
+};
+
+/**
+ * The editor's default Markdown transformers: Lexical's standard set plus GFM
+ * tables.
+ */
+export const DEFAULT_TRANSFORMERS: ReadonlyArray<Transformer> = [
+ ...TRANSFORMERS,
+ TABLE,
+];
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index dc71f20082..201fd118f4 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1007,6 +1007,9 @@ importers:
'@lexical/selection':
specifier: ^0.46.0
version: 0.46.0([email protected])
+ '@lexical/table':
+ specifier: ^0.46.0
+ version: 0.46.0([email protected])
'@lexical/utils':
specifier: ^0.46.0
version: 0.46.0([email protected])