Skip to content

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

TypeScript

fix(richtext): render bold italic text inside an <em>, so it is emphasis as well as strong (#7034)

Cindy Zhang671eb9437499
diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsx
index 629c09e931..ec85a67aae 100644
--- a/packages/richtext/src/RichTextEditor.tsx
+++ b/packages/richtext/src/RichTextEditor.tsx
@@ -73,7 +73,7 @@ import {MarkdownShortcutPlugin} from '@lexical/react/LexicalMarkdownShortcutPlug
import {OnChangePlugin} from '@lexical/react/LexicalOnChangePlugin';
import {TablePlugin} from '@lexical/react/LexicalTablePlugin';
import {HorizontalRuleExtension} from '@lexical/extension';
-import {StrikethroughDeletionExtension} from './strikethroughDeletion';
+import {TextSemanticsExtension} from './textSemantics';
import {TableColumnFloorPlugin} from './TableColumnFloorPlugin';
import {CodeBlockHeaderPlugin} from './CodeBlockHeaderPlugin';
import {CodeSyntaxPlugin} from './CodeSyntaxPlugin';
@@ -564,7 +564,7 @@ export const RichTextEditor = forwardRef<
nodes: nodes ? [...DEFAULT_NODES, ...nodes] : [...DEFAULT_NODES],
// Horizontal rules select on click and show their selection; struck
// text is a deletion.
- dependencies: [HorizontalRuleExtension, StrikethroughDeletionExtension],
+ dependencies: [HorizontalRuleExtension, TextSemanticsExtension],
// `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 db3f6b3b0f..953adea722 100644
--- a/packages/richtext/src/RichTextView.tsx
+++ b/packages/richtext/src/RichTextView.tsx
@@ -42,7 +42,7 @@ import type {
EditorThemeClasses,
} from 'lexical';
import {defineExtension} from 'lexical';
-import {StrikethroughDeletionExtension} from './strikethroughDeletion';
+import {TextSemanticsExtension} from './textSemantics';
// The same node set as the editor, so anything it writes renders here.
import {DEFAULT_NODES} from './editorNodes';
@@ -263,7 +263,7 @@ export function RichTextView({
editable: false,
nodes: nodes ? [...DEFAULT_NODES, ...nodes] : [...DEFAULT_NODES],
// Struck text is a deletion.
- dependencies: [StrikethroughDeletionExtension],
+ dependencies: [TextSemanticsExtension],
$initialEditorState: value,
// A read-only view renders persisted content; a bad node/schema should not
// crash the host. Surface it via onParseError + fallback instead of re-throwing.
diff --git a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
index 48d944ff35..3449d1e007 100644
--- a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
+++ b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts
@@ -955,6 +955,7 @@ test('struck text is a deletion around its other marks, and stays one while edit
await expect(deletions.nth(1).getByRole('strong')).toHaveText('bold');
await expect(deletions.nth(2).getByRole('emphasis')).toHaveText('italic');
await expect(deletions.nth(3).getByRole('strong')).toHaveText('both');
+ await expect(deletions.nth(3).getByRole('emphasis')).toHaveText('both');
await expect(
surface.getByRole('link', {name: 'link'}).getByRole('deletion'),
).toHaveText('link');
@@ -1192,6 +1193,27 @@ test('edited code is colored again as it changes', async ({page}) => {
expect(await editorTokens()).toContain('astryx-keyword:let');
});
+// spec:AST-061 FR7: bold italic text is emphasis and strong in the editor
+// and the view, as core Markdown's `<strong><em>` is.
+test('bold italic text is emphasis and strong in the editor and the view', 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('Keep ***both*** and **bold** here.');
+ const surfaces = page.locator('[data-lexical-editor]:visible');
+ await expect(surfaces).toHaveCount(2);
+ for (const surface of [surfaces.nth(0), surfaces.nth(1)]) {
+ const emphasis = surface.getByRole('emphasis');
+ await expect(emphasis).toHaveText(['both']);
+ await expect(emphasis.getByRole('strong')).toHaveText('both');
+ await expect(surface.getByRole('strong')).toHaveText(['both', 'bold']);
+ }
+});
+
for (const viewport of [PHONE, {width: 1280, height: 900}] as const) {
for (const globals of [
'colorMode:light;direction:ltr',
diff --git a/packages/richtext/src/strikethroughDeletion.test.tsx b/packages/richtext/src/strikethroughDeletion.test.tsx
deleted file mode 100644
index ed444becb1..0000000000
--- a/packages/richtext/src/strikethroughDeletion.test.tsx
+++ /dev/null
@@ -1,135 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-import {describe, it, expect} from 'vitest';
-import {createRef} from 'react';
-import {act, render, waitFor} from '@testing-library/react';
-import {$getRoot, $isTextNode} from 'lexical';
-import {RichTextEditor, type RichTextEditorRef} from './RichTextEditor';
-import {RichTextView} from './RichTextView';
-import {markdownToEditorStateJSON} from './markdownSerializers';
-
-/** Each deletion's text and the tags inside it, outermost first. */
-function deletions(root: Element): Array<{text: string; tags: string}> {
- return [...root.querySelectorAll('del')].map(deletion => {
- const tags: Array<string> = [];
- for (
- let element = deletion.firstElementChild;
- element != null;
- element = element.firstElementChild
- ) {
- tags.push(element.tagName.toLowerCase());
- }
- return {text: deletion.textContent ?? '', tags: tags.join('>')};
- });
-}
-
-describe('struck-through text (spec:AST-061 FR7)', () => {
- it('is a deletion around the strong, emphasis, and link text Lexical draws', async () => {
- const value = markdownToEditorStateJSON(
- 'Keep ~~plain~~, **~~bold~~**, *~~italic~~*, [~~link~~](https://example.com), and `~~literal~~`.\n',
- );
- const {container} = render(
- <>
- <div data-surface="editor">
- <RichTextEditor label="Notes" defaultValue={value} />
- </div>
- <div data-surface="view">
- <RichTextView value={value} />
- </div>
- </>,
- );
- for (const surface of ['editor', 'view']) {
- const root = container.querySelector(`[data-surface="${surface}"]`);
- if (root == null) {
- throw new Error(`No ${surface}`);
- }
- await waitFor(() =>
- expect(deletions(root)).toEqual([
- {text: 'plain', tags: 'span'},
- {text: 'bold', tags: 'strong'},
- {text: 'italic', tags: 'em'},
- {text: 'link', tags: 'span'},
- ]),
- );
- // The link keeps its deletion inside it; text that only looks struck
- // inside code is code.
- expect(root.querySelector('a del')?.textContent).toBe('link');
- expect(root.querySelector('del a')).toBeNull();
- expect(
- [...root.querySelectorAll('code')].some(
- code =>
- code.textContent === '~~literal~~' && code.closest('del') == null,
- ),
- ).toBe(true);
- // No element gives up its own role for the deletion.
- expect(root.querySelector('[role="deletion"]')).toBeNull();
- }
- });
-
- it('adds and removes the deletion as the mark changes, and keeps updating the text', async () => {
- const ref = createRef<RichTextEditorRef>();
- const {container} = render(
- <RichTextEditor
- label="Notes"
- ref={ref}
- defaultValue={markdownToEditorStateJSON('**plain**\n')}
- />,
- );
- const editor = await waitFor(() => {
- const instance = ref.current?.getEditor();
- expect(instance).toBeTruthy();
- return instance;
- });
- const update = async (change: () => void) => {
- await act(async () => {
- editor?.update(change, {discrete: true});
- });
- };
- const text = () => $getRoot().getAllTextNodes()[0];
- await update(() => {
- const node = text();
- if ($isTextNode(node)) {
- node.toggleFormat('strikethrough');
- }
- });
- await waitFor(() =>
- expect(deletions(container)).toEqual([{text: 'plain', tags: 'strong'}]),
- );
- // Lexical keeps updating its own element inside the deletion.
- await update(() => {
- const node = text();
- if ($isTextNode(node)) {
- node.setTextContent('plain and more');
- }
- });
- await waitFor(() =>
- expect(deletions(container)).toEqual([
- {text: 'plain and more', tags: 'strong'},
- ]),
- );
- expect(ref.current?.getMarkdown()).toBe('**~~plain and more~~**\n');
- await update(() => {
- const node = text();
- if ($isTextNode(node)) {
- node.toggleFormat('strikethrough');
- }
- });
- await waitFor(() => expect(deletions(container)).toEqual([]));
- expect(container.querySelector('strong')?.textContent).toBe(
- 'plain and more',
- );
- // Struck code is a deletion around Lexical's code element.
- await update(() => {
- const node = text();
- if ($isTextNode(node)) {
- node.setFormat('code');
- node.toggleFormat('strikethrough');
- }
- });
- await waitFor(() =>
- expect(deletions(container)).toEqual([
- {text: 'plain and more', tags: 'code>span'},
- ]),
- );
- });
-});
diff --git a/packages/richtext/src/strikethroughDeletion.ts b/packages/richtext/src/strikethroughDeletion.ts
deleted file mode 100644
index d5fd7b47b0..0000000000
--- a/packages/richtext/src/strikethroughDeletion.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file strikethroughDeletion.ts
- * @input Uses lexical (TextNode, configExtension) and @lexical/html
- * (DOMRenderExtension, domOverride).
- * @output Exports StrikethroughDeletionExtension, which renders struck-through
- * text inside a `<del>`, the deletion core Markdown renders.
- * @position A dependency of the RichTextEditor and RichTextView extensions.
- * Lexical draws struck text as a styled `<span>`, or as the `<strong>`,
- * `<em>`, or `<code>` its other marks call for, so assistive technology hears
- * no deletion where core Markdown exposes one (spec:AST-061 FR7). Giving that
- * element a deletion role would replace the strong or emphasis role it
- * already has; instead each struck text node's element, exactly as Lexical
- * builds it, sits inside a `<del>`, so the deletion and every other mark are
- * exposed together. Struck text inside a link is a deletion inside the link.
- * The document, its Markdown, and the selection model are unchanged: the
- * text node's element is still the one Lexical created and updates, and
- * Lexical finds its text by walking down from the `<del>`.
- */
-
-import {DOMRenderExtension, domOverride} from '@lexical/html';
-import {
- configExtension,
- TEXT_TYPE_TO_FORMAT,
- TextNode,
- type AnyLexicalExtensionArgument,
-} from 'lexical';
-
-const DELETION_TAG = 'del';
-
-/**
- * Whether this version of `node` is struck. Reads the version's own field:
- * Lexical's getters read the latest version, so `prevNode.hasFormat()` would
- * answer for the next one.
- */
-function isStruck(node: TextNode): boolean {
- return (node.__format & TEXT_TYPE_TO_FORMAT.strikethrough) !== 0;
-}
-
-// Typed as an extension argument: its inferred type names Lexical types the
-// package's declarations cannot (TS4023).
-export const StrikethroughDeletionExtension: AnyLexicalExtensionArgument =
- configExtension(DOMRenderExtension, {
- overrides: [
- domOverride([TextNode], {
- $createDOM(node, $next) {
- const element = $next();
- if (!isStruck(node)) {
- return element;
- }
- const deletion = document.createElement(DELETION_TAG);
- deletion.append(element);
- return deletion;
- },
- $updateDOM(nextNode, prevNode, dom, $next, editor) {
- const struck = isStruck(nextNode);
- if (struck !== isStruck(prevNode)) {
- // Adding or removing the deletion recreates the element.
- return true;
- }
- if (!struck) {
- return $next();
- }
- // Lexical updates its own element, inside the deletion.
- const element = dom.firstElementChild;
- if (dom.tagName.toLowerCase() !== DELETION_TAG || element == null) {
- return true;
- }
- return nextNode.updateDOM(
- prevNode,
- element as HTMLElement,
- editor._config,
- );
- },
- }),
- ],
- });
diff --git a/packages/richtext/src/textSemantics.test.tsx b/packages/richtext/src/textSemantics.test.tsx
new file mode 100644
index 0000000000..dcd26d2a8d
--- /dev/null
+++ b/packages/richtext/src/textSemantics.test.tsx
@@ -0,0 +1,368 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect} from 'vitest';
+import {createRef} from 'react';
+import {act, render, waitFor} from '@testing-library/react';
+import {
+ $getRoot,
+ $isTextNode,
+ REDO_COMMAND,
+ UNDO_COMMAND,
+ type TextFormatType,
+} from 'lexical';
+import {RichTextEditor, type RichTextEditorRef} from './RichTextEditor';
+import {RichTextView} from './RichTextView';
+import {markdownToEditorStateJSON} from './markdownSerializers';
+
+/** Each deletion's text and the tags inside it, outermost first. */
+function deletions(root: Element): Array<{text: string; tags: string}> {
+ return [...root.querySelectorAll('del')].map(deletion => {
+ const tags: Array<string> = [];
+ for (
+ let element = deletion.firstElementChild;
+ element != null;
+ element = element.firstElementChild
+ ) {
+ tags.push(element.tagName.toLowerCase());
+ }
+ return {text: deletion.textContent ?? '', tags: tags.join('>')};
+ });
+}
+
+/** Each emphasis's text and the tags inside it, outermost first. */
+function emphases(root: Element): Array<{text: string; tags: string}> {
+ return [...root.querySelectorAll('em')].map(emphasis => {
+ const tags: Array<string> = [];
+ for (
+ let element = emphasis.firstElementChild;
+ element != null;
+ element = element.firstElementChild
+ ) {
+ tags.push(element.tagName.toLowerCase());
+ }
+ return {text: emphasis.textContent ?? '', tags: tags.join('>')};
+ });
+}
+
+describe('struck-through text (spec:AST-061 FR7)', () => {
+ it('is a deletion around the strong, emphasis, and link text Lexical draws', async () => {
+ const value = markdownToEditorStateJSON(
+ 'Keep ~~plain~~, **~~bold~~**, *~~italic~~*, [~~link~~](https://example.com), and `~~literal~~`.\n',
+ );
+ const {container} = render(
+ <>
+ <div data-surface="editor">
+ <RichTextEditor label="Notes" defaultValue={value} />
+ </div>
+ <div data-surface="view">
+ <RichTextView value={value} />
+ </div>
+ </>,
+ );
+ for (const surface of ['editor', 'view']) {
+ const root = container.querySelector(`[data-surface="${surface}"]`);
+ if (root == null) {
+ throw new Error(`No ${surface}`);
+ }
+ await waitFor(() =>
+ expect(deletions(root)).toEqual([
+ {text: 'plain', tags: 'span'},
+ {text: 'bold', tags: 'strong'},
+ {text: 'italic', tags: 'em'},
+ {text: 'link', tags: 'span'},
+ ]),
+ );
+ // The link keeps its deletion inside it; text that only looks struck
+ // inside code is code.
+ expect(root.querySelector('a del')?.textContent).toBe('link');
+ expect(root.querySelector('del a')).toBeNull();
+ expect(
+ [...root.querySelectorAll('code')].some(
+ code =>
+ code.textContent === '~~literal~~' && code.closest('del') == null,
+ ),
+ ).toBe(true);
+ // No element gives up its own role for the deletion.
+ expect(root.querySelector('[role="deletion"]')).toBeNull();
+ }
+ });
+
+ it('adds and removes the deletion as the mark changes, and keeps updating the text', async () => {
+ const ref = createRef<RichTextEditorRef>();
+ const {container} = render(
+ <RichTextEditor
+ label="Notes"
+ ref={ref}
+ defaultValue={markdownToEditorStateJSON('**plain**\n')}
+ />,
+ );
+ const editor = await waitFor(() => {
+ const instance = ref.current?.getEditor();
+ expect(instance).toBeTruthy();
+ return instance;
+ });
+ const update = async (change: () => void) => {
+ await act(async () => {
+ editor?.update(change, {discrete: true});
+ });
+ };
+ const text = () => $getRoot().getAllTextNodes()[0];
+ await update(() => {
+ const node = text();
+ if ($isTextNode(node)) {
+ node.toggleFormat('strikethrough');
+ }
+ });
+ await waitFor(() =>
+ expect(deletions(container)).toEqual([{text: 'plain', tags: 'strong'}]),
+ );
+ // Lexical keeps updating its own element inside the deletion.
+ await update(() => {
+ const node = text();
+ if ($isTextNode(node)) {
+ node.setTextContent('plain and more');
+ }
+ });
+ await waitFor(() =>
+ expect(deletions(container)).toEqual([
+ {text: 'plain and more', tags: 'strong'},
+ ]),
+ );
+ expect(ref.current?.getMarkdown()).toBe('**~~plain and more~~**\n');
+ await update(() => {
+ const node = text();
+ if ($isTextNode(node)) {
+ node.toggleFormat('strikethrough');
+ }
+ });
+ await waitFor(() => expect(deletions(container)).toEqual([]));
+ expect(container.querySelector('strong')?.textContent).toBe(
+ 'plain and more',
+ );
+ // Struck code is a deletion around Lexical's code element.
+ await update(() => {
+ const node = text();
+ if ($isTextNode(node)) {
+ node.setFormat('code');
+ node.toggleFormat('strikethrough');
+ }
+ });
+ await waitFor(() =>
+ expect(deletions(container)).toEqual([
+ {text: 'plain and more', tags: 'code>span'},
+ ]),
+ );
+ });
+});
+
+describe('bold italic text (spec:AST-061 FR7)', () => {
+ it('is emphasis around the strong Lexical draws, struck or not', async () => {
+ const value = markdownToEditorStateJSON(
+ 'Keep ***both***, ~~***struck***~~, *italic*, and **bold**.\n',
+ );
+ const {container} = render(
+ <>
+ <div data-surface="editor">
+ <RichTextEditor label="Notes" defaultValue={value} />
+ </div>
+ <div data-surface="view">
+ <RichTextView value={value} />
+ </div>
+ </>,
+ );
+ for (const surface of ['editor', 'view']) {
+ const root = container.querySelector(`[data-surface="${surface}"]`);
+ if (root == null) {
+ throw new Error(`No ${surface}`);
+ }
+ // Italic alone is Lexical's own `<em>`; bold italic gains one around
+ // its `<strong>`, inside the deletion when struck.
+ await waitFor(() =>
+ expect(emphases(root)).toEqual([
+ {text: 'both', tags: 'strong'},
+ {text: 'struck', tags: 'strong'},
+ {text: 'italic', tags: ''},
+ ]),
+ );
+ expect(deletions(root)).toEqual([{text: 'struck', tags: 'em>strong'}]);
+ expect(
+ [...root.querySelectorAll('strong')].map(strong => strong.textContent),
+ ).toEqual(['both', 'struck', 'bold']);
+ expect(root.querySelector('[role]:not([role="textbox"])')).toBeNull();
+ }
+ });
+
+ it('adds and removes the emphasis as italic changes on bold text, and keeps updating the text', async () => {
+ const ref = createRef<RichTextEditorRef>();
+ const {container} = render(
+ <RichTextEditor
+ label="Notes"
+ ref={ref}
+ defaultValue={markdownToEditorStateJSON('**plain**\n')}
+ />,
+ );
+ const editor = await waitFor(() => {
+ const instance = ref.current?.getEditor();
+ expect(instance).toBeTruthy();
+ return instance;
+ });
+ const update = async (change: () => void) => {
+ await act(async () => {
+ editor?.update(change, {discrete: true});
+ });
+ };
+ const text = () => $getRoot().getAllTextNodes()[0];
+ await update(() => {
+ const node = text();
+ if ($isTextNode(node)) {
+ node.toggleFormat('italic');
+ }
+ });
+ await waitFor(() =>
+ expect(emphases(container)).toEqual([{text: 'plain', tags: 'strong'}]),
+ );
+ await update(() => {
+ const node = text();
+ if ($isTextNode(node)) {
+ node.setTextContent('plain and more');
+ }
+ });
+ await waitFor(() =>
+ expect(emphases(container)).toEqual([
+ {text: 'plain and more', tags: 'strong'},
+ ]),
+ );
+ expect(ref.current?.getMarkdown()).toBe('***plain and more***\n');
+ // Striking it puts the deletion outside the emphasis.
+ await update(() => {
+ const node = text();
+ if ($isTextNode(node)) {
+ node.toggleFormat('strikethrough');
+ }
+ });
+ await waitFor(() =>
+ expect(deletions(container)).toEqual([
+ {text: 'plain and more', tags: 'em>strong'},
+ ]),
+ );
+ await update(() => {
+ const node = text();
+ if ($isTextNode(node)) {
+ node.toggleFormat('strikethrough');
+ node.toggleFormat('italic');
+ }
+ });
+ await waitFor(() => expect(emphases(container)).toEqual([]));
+ expect(deletions(container)).toEqual([]);
+ expect(container.querySelector('strong')?.textContent).toBe(
+ 'plain and more',
+ );
+ });
+ it("wraps Lexical's code, highlight, subscript, and superscript elements, and leaves single marks alone", async () => {
+ const ref = createRef<RichTextEditorRef>();
+ const {container} = render(
+ <RichTextEditor
+ label="Notes"
+ ref={ref}
+ defaultValue={markdownToEditorStateJSON(
+ 'one two three four five six seven eight\n',
+ )}
+ />,
+ );
+ const editor = await waitFor(() => {
+ const instance = ref.current?.getEditor();
+ expect(instance).toBeTruthy();
+ return instance;
+ });
+ await act(async () => {
+ editor?.update(
+ () => {
+ const [node] = $getRoot().getAllTextNodes();
+ if (!$isTextNode(node)) {
+ return;
+ }
+ const words = node.splitText(4, 8, 14, 19, 24, 28, 34);
+ const formats: Array<ReadonlyArray<TextFormatType>> = [
+ ['bold', 'italic', 'code'],
+ ['bold', 'italic', 'highlight'],
+ ['bold', 'italic', 'subscript'],
+ ['bold', 'italic', 'superscript'],
+ ['bold', 'italic', 'strikethrough', 'code'],
+ ['italic'],
+ ['bold'],
+ ['code'],
+ ];
+ words.forEach((word, index) => {
+ for (const format of formats[index] ?? []) {
+ word.toggleFormat(format);
+ }
+ });
+ },
+ {discrete: true},
+ );
+ });
+ // Each bold italic word is emphasis around exactly the element Lexical
+ // draws for it; a single mark keeps Lexical's own element and no other.
+ await waitFor(() =>
+ expect(emphases(container)).toEqual([
+ {text: 'one ', tags: 'code>strong'},
+ {text: 'two ', tags: 'mark>strong'},
+ {text: 'three ', tags: 'sub>strong'},
+ {text: 'four ', tags: 'sup>strong'},
+ {text: 'five ', tags: 'code>strong'},
+ {text: 'six ', tags: ''},
+ ]),
+ );
+ expect(deletions(container)).toEqual([
+ {text: 'five ', tags: 'em>code>strong'},
+ ]);
+ const paragraph = container.querySelector('[data-lexical-editor] p');
+ expect(
+ [...(paragraph?.children ?? [])].map(child =>
+ child.tagName.toLowerCase(),
+ ),
+ ).toEqual(['em', 'em', 'em', 'em', 'del', 'em', 'strong', 'code']);
+ });
+
+ it('puts the emphasis back on undo and takes it away on redo', async () => {
+ const ref = createRef<RichTextEditorRef>();
+ const {container} = render(
+ <RichTextEditor
+ label="Notes"
+ ref={ref}
+ defaultValue={markdownToEditorStateJSON('***both***\n')}
+ />,
+ );
+ const editor = await waitFor(() => {
+ const instance = ref.current?.getEditor();
+ expect(instance).toBeTruthy();
+ return instance;
+ });
+ await waitFor(() =>
+ expect(emphases(container)).toEqual([{text: 'both', tags: 'strong'}]),
+ );
+ await act(async () => {
+ editor?.update(
+ () => {
+ const [node] = $getRoot().getAllTextNodes();
+ if ($isTextNode(node)) {
+ node.toggleFormat('italic');
+ }
+ },
+ {discrete: true},
+ );
+ });
+ await waitFor(() => expect(emphases(container)).toEqual([]));
+ await act(async () => {
+ editor?.dispatchCommand(UNDO_COMMAND, undefined);
+ });
+ await waitFor(() =>
+ expect(emphases(container)).toEqual([{text: 'both', tags: 'strong'}]),
+ );
+ await act(async () => {
+ editor?.dispatchCommand(REDO_COMMAND, undefined);
+ });
+ await waitFor(() => expect(emphases(container)).toEqual([]));
+ expect(ref.current?.getMarkdown()).toBe('**both**\n');
+ });
+});
diff --git a/packages/richtext/src/textSemantics.ts b/packages/richtext/src/textSemantics.ts
new file mode 100644
index 0000000000..691107bec0
--- /dev/null
+++ b/packages/richtext/src/textSemantics.ts
@@ -0,0 +1,104 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file textSemantics.ts
+ * @input Uses lexical (TextNode, configExtension) and @lexical/html
+ * (DOMRenderExtension, domOverride).
+ * @output Exports TextSemanticsExtension, which renders struck-through text
+ * inside a `<del>` and bold italic text inside an `<em>`, the elements core
+ * Markdown renders for them.
+ * @position A dependency of the RichTextEditor and RichTextView extensions.
+ * Lexical draws struck text as a styled `<span>`, or as the `<strong>`,
+ * `<em>`, or `<code>` its other marks call for, and draws bold italic text
+ * as a `<strong>` alone, so assistive technology hears no deletion, and no
+ * emphasis on bold italic text, where core Markdown exposes them
+ * (spec:AST-061 FR7). Giving Lexical's element another role would replace
+ * the one it already has; instead each text node's element, exactly as
+ * Lexical builds it, sits inside the elements it is missing — a `<del>`,
+ * then an `<em>` — so every mark is exposed together. Struck text inside a
+ * link is a deletion inside the link. The document, its Markdown, and the
+ * selection model are unchanged: the text node's element is still the one
+ * Lexical created and updates, and Lexical finds its text by walking down
+ * from the outermost element.
+ */
+
+import {DOMRenderExtension, domOverride} from '@lexical/html';
+import {
+ configExtension,
+ TEXT_TYPE_TO_FORMAT,
+ TextNode,
+ type AnyLexicalExtensionArgument,
+} from 'lexical';
+
+const STRIKETHROUGH = TEXT_TYPE_TO_FORMAT.strikethrough;
+const BOLD_ITALIC = TEXT_TYPE_TO_FORMAT.bold | TEXT_TYPE_TO_FORMAT.italic;
+
+/**
+ * The elements this version of `node` sits inside, outermost first. Reads the
+ * version's own field: Lexical's getters read the latest version, so
+ * `prevNode.hasFormat()` would answer for the next one.
+ */
+function wrappersOf(node: TextNode): ReadonlyArray<'del' | 'em'> {
+ const format = node.__format;
+ const wrappers: Array<'del' | 'em'> = [];
+ if ((format & STRIKETHROUGH) !== 0) {
+ wrappers.push('del');
+ }
+ // Lexical draws bold italic text as a `<strong>` with an italic class.
+ if ((format & BOLD_ITALIC) === BOLD_ITALIC) {
+ wrappers.push('em');
+ }
+ return wrappers;
+}
+
+function sameWrappers(
+ a: ReadonlyArray<string>,
+ b: ReadonlyArray<string>,
+): boolean {
+ return a.length === b.length && a.every((tag, index) => tag === b[index]);
+}
+
+// Typed as an extension argument: its inferred type names Lexical types the
+// package's declarations cannot (TS4023).
+export const TextSemanticsExtension: AnyLexicalExtensionArgument =
+ configExtension(DOMRenderExtension, {
+ overrides: [
+ domOverride([TextNode], {
+ $createDOM(node, $next) {
+ let element = $next();
+ for (const tag of [...wrappersOf(node)].reverse()) {
+ const wrapper = document.createElement(tag);
+ wrapper.append(element);
+ element = wrapper;
+ }
+ return element;
+ },
+ $updateDOM(nextNode, prevNode, dom, $next, editor) {
+ const wrappers = wrappersOf(nextNode);
+ if (!sameWrappers(wrappers, wrappersOf(prevNode))) {
+ // Adding or removing a wrapper recreates the element.
+ return true;
+ }
+ if (wrappers.length === 0) {
+ return $next();
+ }
+ // Lexical updates its own element, inside the wrappers.
+ let element: Element | null = dom;
+ for (const tag of wrappers) {
+ if (element?.tagName.toLowerCase() !== tag) {
+ return true;
+ }
+ element = element.firstElementChild;
+ }
+ if (element == null) {
+ return true;
+ }
+ return nextNode.updateDOM(
+ prevNode,
+ element as HTMLElement,
+ editor._config,
+ );
+ },
+ }),
+ ],
+ });