Skip to content

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

TypeScript

feat(richtext): import, draw, and export thematic breaks as horizontal rules (#6999)

Cindy Zhangc24598577a05
diff --git a/packages/richtext/package.json b/packages/richtext/package.json
index 15dc2cbc61..08e3566064 100644
--- a/packages/richtext/package.json
+++ b/packages/richtext/package.json
@@ -76,6 +76,7 @@
"@lexical/rich-text": "^0.46.0",
"@lexical/selection": "^0.46.0",
"@lexical/code": "^0.46.0",
+ "@lexical/extension": "^0.46.0",
"@lexical/table": "^0.46.0",
"@lexical/utils": "^0.46.0"
},
@@ -110,6 +111,9 @@
"@lexical/code": {
"optional": true
},
+ "@lexical/extension": {
+ "optional": true
+ },
"@lexical/table": {
"optional": true
},
@@ -125,6 +129,7 @@
"@babel/preset-react": "catalog:",
"@babel/preset-typescript": "catalog:",
"@lexical/code": "^0.46.0",
+ "@lexical/extension": "^0.46.0",
"@lexical/headless": "^0.46.0",
"@lexical/html": "^0.46.0",
"@lexical/link": "^0.46.0",
diff --git a/packages/richtext/src/RichTextEditor.doc.mjs b/packages/richtext/src/RichTextEditor.doc.mjs
index a10f5877d8..5d9088507a 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, hard line breaks, and GFM tables).',
+ 'Enable Markdown shortcut typing (e.g. "# " for a heading). Uses the transformers prop (defaults to thematic breaks, the standard @lexical/markdown transformers, hard line breaks, and 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, hard line breaks (a line break typed with Shift+Enter exports as a backslash before the line ending, so it reads back as a line break), and 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.',
+ 'Markdown transformers: the single source of truth for markdown behaviour. Defaults to thematic breaks, the standard @lexical/markdown TRANSFORMERS, hard line breaks (a line break typed with Shift+Enter exports as a backslash before the line ending, so it reads back as a line break), and GFM tables; a custom array replaces the default, thematic breaks and 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',
},
{
@@ -199,6 +199,11 @@ export const docs = {
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:
+ 'Thematic breaks (---, ***, ___, with or without spaces between) import as horizontal rules and export as ---. A dash line directly under a paragraph line stays with that paragraph, as in Markdown. Click a rule or arrow onto it to select it; Backspace removes it. RichTextView draws the same rules. Install @lexical/extension with the other lexical peers.',
+ },
{
guidance: true,
description:
diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsx
index f0912133a3..015d72b432 100644
--- a/packages/richtext/src/RichTextEditor.tsx
+++ b/packages/richtext/src/RichTextEditor.tsx
@@ -72,6 +72,7 @@ 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 {HorizontalRuleExtension} from '@lexical/extension';
import {type Transformer} from '@lexical/markdown';
export type {Transformer} from '@lexical/markdown';
import {$generateHtmlFromNodes} from '@lexical/html';
@@ -556,6 +557,8 @@ export const RichTextEditor = forwardRef<
theme: themeRef.current,
editable,
nodes: nodes ? [...DEFAULT_NODES, ...nodes] : [...DEFAULT_NODES],
+ // Horizontal rules select on click and show their selection.
+ dependencies: [HorizontalRuleExtension],
// `undefined` (not `null`) leaves Lexical's default initializer in place,
// which seeds the empty document with one paragraph — what
// LexicalComposer did when no `editorState` was given. `null` would mean
diff --git a/packages/richtext/src/RichTextView.tsx b/packages/richtext/src/RichTextView.tsx
index c7ed1cbe1a..f7d7fd3cec 100644
--- a/packages/richtext/src/RichTextView.tsx
+++ b/packages/richtext/src/RichTextView.tsx
@@ -30,11 +30,6 @@ 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 {TableScrollRegionPlugin} from './TableScrollRegionPlugin';
import type {
AnyLexicalExtension,
@@ -43,6 +38,8 @@ import type {
EditorThemeClasses,
} from 'lexical';
import {defineExtension} from 'lexical';
+// The same node set as the editor, so anything it writes renders here.
+import {DEFAULT_NODES} from './editorNodes';
const styles = stylex.create({
root: {
@@ -50,20 +47,6 @@ const styles = stylex.create({
},
});
-const DEFAULT_NODES: ReadonlyArray<Klass<LexicalNode>> = [
- HeadingNode,
- QuoteNode,
- ListNode,
- ListItemNode,
- LinkNode,
- AutoLinkNode,
- CodeNode,
- CodeHighlightNode,
- TableNode,
- TableRowNode,
- TableCellNode,
-];
-
/**
* Lexical's `ContentEditable` renders `role="textbox"` and widget-only ARIA
* (`aria-autocomplete`, `aria-readonly`) even when the editor is not editable.
diff --git a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
index f4ef948efb..e3ac1fde91 100644
--- a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
+++ b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
@@ -308,6 +308,40 @@ const tableSource = (columnCount: number) => {
].join('\n');
};
+// spec:AST-061 FR3: a rule at the start or end of a document adds no margin
+// at that edge, like every other block, in the editor and the view.
+test('a rule at either edge of the document adds no outer margin', async ({
+ page,
+}) => {
+ await page.setViewportSize(DESKTOP);
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=lab-richtexteditor--markdown-serializers&viewMode=story&globals=astryxTheme:neutral;colorMode:light;direction:ltr`,
+ {waitUntil: 'load'},
+ );
+ await page.locator('textarea').fill('---\n\nBetween the rules.\n\n---');
+ await expect(page.locator('hr:visible')).toHaveCount(4);
+ const margins = await page.evaluate(() =>
+ [...document.querySelectorAll('[data-lexical-editor]')]
+ .filter(root => root.querySelector('hr') != null)
+ .map(root => {
+ const rules = root.querySelectorAll('hr');
+ const first = getComputedStyle(rules[0]);
+ const last = getComputedStyle(rules[rules.length - 1]);
+ return [
+ first.marginTop,
+ first.marginBottom,
+ last.marginTop,
+ last.marginBottom,
+ ];
+ }),
+ );
+ // Editor and view: no margin at the outer edges, the full 24px inside.
+ expect(margins).toEqual([
+ ['0px', '24px', '24px', '0px'],
+ ['0px', '24px', '24px', '0px'],
+ ]);
+});
+
for (const viewport of [PHONE, {width: 1280, height: 900}] as const) {
for (const globals of [
'colorMode:light;direction:ltr',
@@ -488,6 +522,7 @@ test('side by side: shared blocks match core Markdown typography, spacing, and m
padding: getComputedStyle(rows[0]).paddingTop,
};
})(),
+ rule: styleOf(block('thematic-break', 'hr')),
// The text inside a header cell, where each surface draws it.
tableHeader: (() => {
const cell = block('table', 'table')?.querySelector('th');
@@ -523,6 +558,15 @@ test('side by side: shared blocks match core Markdown typography, spacing, and m
}
expect(richText.strong).toBe(markdown.strong);
expect(richText.listRows, 'list rows').toEqual(markdown.listRows);
+ for (const property of [
+ 'marginTop',
+ 'marginBottom',
+ 'borderLeftWidth',
+ ] as const) {
+ expect(richText.rule?.[property], `rule ${property}`).toBe(
+ markdown.rule?.[property],
+ );
+ }
expect(richText.tableHeader, 'table header text').toEqual(
markdown.tableHeader,
);
@@ -705,7 +749,8 @@ test('overlay: both layers start together and the drawn editor is inert', async
await expect(page.locator(RICH_TEXT)).toHaveAttribute('inert', '');
// An inert editor refuses focus, so neither keyboard nor pointer reach it.
const focusable = await page
- .locator(`${RICH_TEXT} [contenteditable]`)
+ // The editor root, not a horizontal rule's contenteditable="false".
+ .locator(`${RICH_TEXT} [data-lexical-editor]`)
.evaluate(editor => {
(editor as HTMLElement).focus();
return document.activeElement === editor;
diff --git a/packages/richtext/src/editorNodes.ts b/packages/richtext/src/editorNodes.ts
index c2a3649165..5b05550e4e 100644
--- a/packages/richtext/src/editorNodes.ts
+++ b/packages/richtext/src/editorNodes.ts
@@ -16,6 +16,7 @@ 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 {HorizontalRuleNode} from '@lexical/extension';
import type {Klass, LexicalNode} from 'lexical';
/**
@@ -35,4 +36,5 @@ export const DEFAULT_NODES: ReadonlyArray<Klass<LexicalNode>> = [
TableNode,
TableRowNode,
TableCellNode,
+ HorizontalRuleNode,
];
diff --git a/packages/richtext/src/editorTheme.ts b/packages/richtext/src/editorTheme.ts
index 57e6242d6b..11667c263a 100644
--- a/packages/richtext/src/editorTheme.ts
+++ b/packages/richtext/src/editorTheme.ts
@@ -20,6 +20,8 @@ import {
typographyVars,
typeScaleVars,
fontWeightVars,
+ borderVars,
+ focusVars,
} from '@astryxdesign/core/theme/tokens.stylex';
import type {EditorThemeClasses} from 'lexical';
@@ -43,6 +45,7 @@ const LIST_ITEM_SPACE = `calc(${spacingVars['--spacing-1']})`;
const LIST_ROW_GAP = `calc(${spacingVars['--spacing-0-5']})`;
const LIST_ROW_FLUSH = `calc(${spacingVars['--spacing-0']})`;
const NESTED_LIST_SPACE = `calc(${spacingVars['--spacing-2']})`;
+const RULE_SPACE = `calc(${spacingVars['--spacing-6']})`;
const editorTheme = stylex.create({
paragraph: {
@@ -314,6 +317,29 @@ const editorTheme = stylex.create({
fontWeight: fontWeightVars['--font-weight-semibold'],
color: colorVars['--color-text-secondary'],
},
+ // Thematic breaks, drawn like core Markdown's rule.
+ hr: {
+ borderWidth: 0,
+ borderTopWidth: borderVars['--border-width'],
+ borderTopStyle: 'solid',
+ borderTopColor: colorVars['--color-border'],
+ marginBlockStart: {
+ default: RULE_SPACE,
+ ':first-child': spacingVars['--spacing-0'],
+ },
+ marginBlockEnd: {
+ default: RULE_SPACE,
+ ':last-child': spacingVars['--spacing-0'],
+ },
+ },
+ // A selected rule (click, or arrow onto it) shows the focus ring, so
+ // keyboard users can see what Backspace will delete.
+ hrSelected: {
+ outlineWidth: focusVars['--focus-outline-width'],
+ outlineStyle: focusVars['--focus-outline-style'],
+ outlineColor: focusVars['--focus-outline-color'],
+ outlineOffset: focusVars['--focus-outline-offset'],
+ },
code: {
display: 'block',
fontFamily: typographyVars['--font-family-code'],
@@ -385,6 +411,8 @@ export function sharedEditorTheme(): EditorThemeClasses {
code: stylex.props(editorTheme.textCode).className,
},
code: stylex.props(editorTheme.code).className,
+ hr: stylex.props(editorTheme.hr).className,
+ hrSelected: stylex.props(editorTheme.hrSelected).className,
table: stylex.props(editorTheme.table).className,
tableRow: stylex.props(editorTheme.tableRow).className,
tableCell: stylex.props(editorTheme.tableCell).className,
diff --git a/packages/richtext/src/markdownTable.ts b/packages/richtext/src/markdownTable.ts
index c19842a3a4..f22b0b65bb 100644
--- a/packages/richtext/src/markdownTable.ts
+++ b/packages/richtext/src/markdownTable.ts
@@ -38,6 +38,7 @@ import {
} from '@lexical/table';
import type {ElementFormatType} from 'lexical';
import {HARD_LINE_BREAK} from './markdownHardLineBreak';
+import {THEMATIC_BREAK} from './markdownThematicBreak';
/**
* Cells hold inline Markdown only, so they are imported and exported with the
@@ -235,10 +236,13 @@ export const TABLE: MultilineElementTransformer = {
};
/**
- * The editor's default Markdown transformers: Lexical's standard set, hard
- * line breaks for breaks typed in the editor, and GFM tables.
+ * The editor's default Markdown transformers: thematic breaks, Lexical's
+ * standard set, 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.
*/
export const DEFAULT_TRANSFORMERS: ReadonlyArray<Transformer> = [
+ THEMATIC_BREAK,
...TRANSFORMERS,
HARD_LINE_BREAK,
TABLE,
diff --git a/packages/richtext/src/markdownThematicBreak.test.tsx b/packages/richtext/src/markdownThematicBreak.test.tsx
new file mode 100644
index 0000000000..8dda83f010
--- /dev/null
+++ b/packages/richtext/src/markdownThematicBreak.test.tsx
@@ -0,0 +1,185 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect} from 'vitest';
+import {render, waitFor} from '@testing-library/react';
+import {$createHorizontalRuleNode} from '@lexical/extension';
+import {createHeadlessEditor} from '@lexical/headless';
+import {$getRoot} from 'lexical';
+import {DEFAULT_NODES} from './editorNodes';
+import {RichTextEditor} from './RichTextEditor';
+import {RichTextView} from './RichTextView';
+import {
+ editorStateJSONToMarkdown,
+ markdownToEditorStateJSON,
+} from './markdownSerializers';
+
+interface SerializedNode {
+ type: string;
+ children?: Array<SerializedNode>;
+ text?: string;
+}
+
+function paragraphTexts(markdown: string): Array<string> {
+ const state = JSON.parse(markdownToEditorStateJSON(markdown)) as {
+ root: SerializedNode;
+ };
+ return (state.root.children ?? [])
+ .filter(node => node.type === 'paragraph')
+ .map(node => (node.children ?? []).map(child => child.text ?? '').join(''));
+}
+
+function blockTypes(markdown: string): Array<string> {
+ const state = JSON.parse(markdownToEditorStateJSON(markdown)) as {
+ root: SerializedNode;
+ };
+ return (state.root.children ?? []).map(node => node.type);
+}
+
+describe('thematic breaks (spec:AST-061 FR5)', () => {
+ it('imports every CommonMark thematic break as a horizontal rule', () => {
+ for (const line of [
+ '---',
+ '***',
+ '___',
+ '- - -',
+ '* * *',
+ '_ _ _',
+ ' ----',
+ '*** ',
+ ]) {
+ expect(blockTypes(`Before\n\n${line}\n\nAfter`), line).toEqual([
+ 'paragraph',
+ 'horizontalrule',
+ 'paragraph',
+ ]);
+ }
+ });
+
+ it('leaves lines that are not thematic breaks as text', () => {
+ for (const line of ['--', '-*-', '--- x', ' ---']) {
+ expect(blockTypes(`Before\n\n${line}\n\nAfter`), line).not.toContain(
+ 'horizontalrule',
+ );
+ }
+ });
+
+ it('keeps a dash line under a paragraph line as literal text in that paragraph', () => {
+ // CommonMark reads these as setext heading underlines, not breaks; the
+ // editor keeps the underline as text rather than dropping it.
+ for (const [markdown, text] of [
+ ['Title\n---\n\nAfter', 'Title ---'],
+ [' Title\n --- \n\nAfter', 'Title ---'],
+ ['Title\n===\n\nAfter', 'Title ==='],
+ ] as const) {
+ expect(blockTypes(markdown), markdown).toEqual([
+ 'paragraph',
+ 'paragraph',
+ ]);
+ // Lexical keeps a paragraph's indentation as text; the dashes survive.
+ expect(paragraphTexts(markdown)[0]?.trim(), markdown).toBe(text);
+ }
+ // Two underlined paragraphs keep both underlines.
+ expect(paragraphTexts('A\n---\n\nB\n---\n')).toEqual(['A ---', 'B ---']);
+ });
+
+ it('breaks after a blank line, a heading, a list, a quote, or with spaced dashes', () => {
+ for (const markdown of [
+ 'Title\n\n---\n\nAfter',
+ '# Heading\n---\n\nAfter',
+ '> Quote\n---\n\nAfter',
+ // `- - -` cannot underline a heading, so it breaks even under a line.
+ 'Title\n- - -\n\nAfter',
+ ]) {
+ expect(blockTypes(markdown), markdown).toContain('horizontalrule');
+ }
+ expect(blockTypes('- item\n---\n\nAfter')).toEqual([
+ 'list',
+ 'horizontalrule',
+ 'paragraph',
+ ]);
+ });
+
+ it('keeps an underlined paragraph exact, and keeps its dashes when edited (spec:AST-062)', () => {
+ const markdown = 'Title\n---\n\nAfter\n';
+ expect(editorStateJSONToMarkdown(markdownToEditorStateJSON(markdown))).toBe(
+ markdown,
+ );
+ const edit = (needle: string, suffix: string): string => {
+ const editor = createHeadlessEditor({
+ namespace: 'astryx-thematic-break-edit',
+ nodes: [...DEFAULT_NODES],
+ onError(error: Error) {
+ throw error;
+ },
+ });
+ editor.setEditorState(
+ editor.parseEditorState(markdownToEditorStateJSON(markdown)),
+ );
+ editor.update(
+ () => {
+ const node = $getRoot()
+ .getAllTextNodes()
+ .find(candidate => candidate.getTextContent().startsWith(needle));
+ node?.setTextContent(node.getTextContent() + suffix);
+ },
+ {discrete: true},
+ );
+ return editorStateJSONToMarkdown(
+ JSON.stringify(editor.getEditorState().toJSON()),
+ );
+ };
+ // Editing the next paragraph leaves the underlined one byte-identical.
+ expect(edit('After', ' more')).toBe('Title\n---\n\nAfter more\n');
+ // Editing the underlined paragraph keeps its dashes as text.
+ expect(edit('Title', '!')).toContain('---');
+ expect(blockTypes(edit('Title', '!'))).not.toContain('horizontalrule');
+ });
+
+ it('keeps an imported rule as written and writes a new rule as ---', () => {
+ // An untouched rule keeps its authored bytes (spec:AST-062).
+ expect(
+ editorStateJSONToMarkdown(
+ markdownToEditorStateJSON('Before\n\n* * *\n\nAfter'),
+ ),
+ ).toBe('Before\n\n* * *\n\nAfter');
+ const editor = createHeadlessEditor({
+ namespace: 'astryx-thematic-break-test',
+ nodes: [...DEFAULT_NODES],
+ onError(error: Error) {
+ throw error;
+ },
+ });
+ editor.setEditorState(
+ editor.parseEditorState(markdownToEditorStateJSON('Before\n\nAfter')),
+ );
+ editor.update(
+ () => {
+ $getRoot().getFirstChild()?.insertAfter($createHorizontalRuleNode());
+ },
+ {discrete: true},
+ );
+ const markdown = editorStateJSONToMarkdown(
+ JSON.stringify(editor.getEditorState().toJSON()),
+ );
+ expect(markdown).toBe('Before\n\n---\n\nAfter');
+ expect(blockTypes(markdown)).toEqual([
+ 'paragraph',
+ 'horizontalrule',
+ 'paragraph',
+ ]);
+ });
+
+ it('draws a rule in the editor and in RichTextView', async () => {
+ const value = markdownToEditorStateJSON('Before\n\n---\n\nAfter');
+ const {container} = render(
+ <>
+ <RichTextEditor label="Notes" defaultValue={value} />
+ <RichTextView value={value} />
+ </>,
+ );
+ await waitFor(() => {
+ expect(container.querySelectorAll('hr')).toHaveLength(2);
+ });
+ expect(container.textContent).not.toContain('---');
+ });
+});
diff --git a/packages/richtext/src/markdownThematicBreak.ts b/packages/richtext/src/markdownThematicBreak.ts
new file mode 100644
index 0000000000..23d4296384
--- /dev/null
+++ b/packages/richtext/src/markdownThematicBreak.ts
@@ -0,0 +1,66 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file markdownThematicBreak.ts
+ * @input Uses @lexical/extension (HorizontalRuleNode), @lexical/markdown
+ * (ElementTransformer), and lexical.
+ * @output Exports THEMATIC_BREAK, the Markdown transformer that turns a
+ * thematic break line into a horizontal rule and writes a rule back as `---`.
+ * @position Part of DEFAULT_TRANSFORMERS (markdownTable.ts), ahead of
+ * Lexical's list transformers so `* * *` and `- - -` are rules, as in
+ * CommonMark. Matches core Markdown's thematic breaks (spec:AST-061 FR5).
+ */
+
+import {
+ $createHorizontalRuleNode,
+ $isHorizontalRuleNode,
+ HorizontalRuleNode,
+} from '@lexical/extension';
+import type {ElementTransformer} from '@lexical/markdown';
+import {$isParagraphNode, $isTextNode} from 'lexical';
+
+/**
+ * Three or more `-`, `*`, or `_` of one kind, optionally spaced, indented at
+ * most three spaces (CommonMark 0.31, thematic breaks).
+ */
+const THEMATIC_BREAK_LINE = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/;
+
+/**
+ * A setext heading underline made of dashes: no spaces between them, so
+ * `- - -` under a paragraph is still a thematic break (CommonMark 0.31).
+ */
+const SETEXT_UNDERLINE = /^ {0,3}-+[ \t]*$/;
+
+export const THEMATIC_BREAK: ElementTransformer = {
+ dependencies: [HorizontalRuleNode],
+ export: node => ($isHorizontalRuleNode(node) ? '---' : null),
+ regExp: THEMATIC_BREAK_LINE,
+ replace: (parentNode, children, match, isImport) => {
+ // A dash line right under a paragraph line underlines it as a heading
+ // (setext) rather than breaking. Lexical has already cut the matched text
+ // out of the line; put it back and leave the line to the paragraph, which
+ // keeps it as literal text.
+ const previous = parentNode.getPreviousSibling();
+ if (
+ isImport &&
+ SETEXT_UNDERLINE.test(match[0]) &&
+ $isParagraphNode(previous) &&
+ previous.getTextContentSize() > 0
+ ) {
+ const [line] = children;
+ if ($isTextNode(line)) {
+ // The pattern is anchored to the whole line, so its match is the line.
+ line.setTextContent(match[0]);
+ }
+ return false;
+ }
+ const rule = $createHorizontalRuleNode();
+ if (isImport || parentNode.getNextSibling() != null) {
+ parentNode.replace(rule);
+ } else {
+ parentNode.insertBefore(rule);
+ }
+ rule.selectNext();
+ },
+ type: 'element',
+};
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 201fd118f4..ba8f65e78a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -983,6 +983,9 @@ importers:
'@lexical/code':
specifier: ^0.46.0
version: 0.46.0([email protected])
+ '@lexical/extension':
+ specifier: ^0.46.0
+ version: 0.46.0([email protected])
'@lexical/headless':
specifier: ^0.46.0
version: 0.46.0([email protected])