An open source design system that's fully customizable and agent ready
TypeScript
fix(richtext): render struck-through text inside a <del>, so it is a deletion and keeps its other marks (#7019)
Cindy Zhangb8e30f368272
diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsxindex 7e1a1fdb2f..ecc61ac7a9 100644--- a/packages/richtext/src/RichTextEditor.tsx+++ b/packages/richtext/src/RichTextEditor.tsx@@ -73,6 +73,7 @@ import {MarkdownShortcutPlugin} from '@lexical/react/LexicalMarkdownShortcutPlugimport {OnChangePlugin} from '@lexical/react/LexicalOnChangePlugin';import {TablePlugin} from '@lexical/react/LexicalTablePlugin';import {HorizontalRuleExtension} from '@lexical/extension';+import {StrikethroughDeletionExtension} from './strikethroughDeletion';import {TableColumnFloorPlugin} from './TableColumnFloorPlugin';import {CodeBlockHeaderPlugin} from './CodeBlockHeaderPlugin';import {TaskCheckboxPlugin} from './TaskCheckboxPlugin';@@ -560,8 +561,9 @@ 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],+ // Horizontal rules select on click and show their selection; struck+ // text is a deletion.+ dependencies: [HorizontalRuleExtension, StrikethroughDeletionExtension],// `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 meandiff --git a/packages/richtext/src/RichTextView.tsx b/packages/richtext/src/RichTextView.tsxindex c53ae1e137..9587323179 100644--- a/packages/richtext/src/RichTextView.tsx+++ b/packages/richtext/src/RichTextView.tsx@@ -41,6 +41,7 @@ import type {EditorThemeClasses,} from 'lexical';import {defineExtension} from 'lexical';+import {StrikethroughDeletionExtension} from './strikethroughDeletion';// The same node set as the editor, so anything it writes renders here.import {DEFAULT_NODES} from './editorNodes';@@ -260,6 +261,8 @@ export function RichTextView({theme: themeRef.current,editable: false,nodes: nodes ? [...DEFAULT_NODES, ...nodes] : [...DEFAULT_NODES],+ // Struck text is a deletion.+ dependencies: [StrikethroughDeletionExtension],$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.tsindex d3e199d22a..2244b1bd13 100644--- a/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts+++ b/packages/richtext/src/__tests__/MarkdownParitySandbox.a11y.chromium.spec.ts@@ -907,6 +907,88 @@ for (const globals of [}});}+// spec:AST-061 FR7: struck-through text is a deletion on both surfaces, as+// core Markdown's <del> is, and nothing else is.+test('side by side: strikethrough is a deletion on both surfaces', async ({+ page,+}) => {+ const errors = await openStory(page, STORY.sideBySide, DESKTOP);+ await waitForDocument(page, MARKDOWN);+ await waitForDocument(page, RICH_TEXT);+ const markdown = page.locator(MARKDOWN).getByRole('deletion');+ const richText = page.locator(RICH_TEXT).getByRole('deletion');+ await expect(markdown).toHaveCount(1);+ await expect(richText).toHaveCount(1);+ expect(await richText.textContent()).toBe(await markdown.textContent());+ expect(errors).toEqual([]);+});++// spec:AST-061 FR7: struck text is a deletion around the strong, emphasis,+// or link text it also is, in the editor and the view, and stays one as it+// is edited.+test('struck text is a deletion around its other marks, and stays one while edited', 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 ~~plain~~, **~~bold~~**, *~~italic~~*, ***~~both~~***, and [~~link~~](https://example.com).',+ );+ const surfaces = page.locator('[data-lexical-editor]:visible');+ await expect(surfaces).toHaveCount(2);+ for (const surface of [surfaces.nth(0), surfaces.nth(1)]) {+ const deletions = surface.getByRole('deletion');+ await expect(deletions).toHaveCount(5);+ await expect(deletions).toHaveText([+ 'plain',+ 'bold',+ 'italic',+ 'both',+ 'link',+ ]);+ // Each deletion keeps the role of what is inside it.+ 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(+ surface.getByRole('link', {name: 'link'}).getByRole('deletion'),+ ).toHaveText('link');+ // Nothing is a deletion by role in place of its own role.+ await expect(surface.locator('[role="deletion"]')).toHaveCount(0);+ }+ // Typing in struck text, at its end or inside it, stays struck; undo+ // takes it back.+ const editor = page.locator('[data-lexical-editor][contenteditable="true"]');+ // The caret, at the end of the struck word; Lexical reads the selection+ // when the browser reports it changed, so wait for the browser to have it.+ const caret = () =>+ page.evaluate(() => {+ const selection = getSelection();+ return `${selection?.anchorNode?.textContent}@${selection?.anchorOffset}`;+ });+ await editor.getByText('plain', {exact: true}).dblclick();+ await expect(editor).toBeFocused();+ await page.keyboard.press('ArrowRight');+ await expect.poll(caret).toBe('plain@5');+ await page.waitForTimeout(50);+ await page.keyboard.type('er');+ await expect(editor.getByRole('deletion').first()).toHaveText('plainer');+ await page.keyboard.press('ControlOrMeta+z');+ await expect(editor.getByRole('deletion').first()).toHaveText('plain');+ await editor.getByText('plain', {exact: true}).dblclick();+ await page.keyboard.press('ArrowLeft');+ await page.keyboard.press('ArrowRight');+ await page.keyboard.press('ArrowRight');+ await expect.poll(caret).toBe('plain@2');+ await page.waitForTimeout(50);+ await page.keyboard.type('XY');+ await expect(editor.getByRole('deletion').first()).toHaveText('plXYain');+});// spec:AST-061 DEC-6 in core Markdown: each level draws the marker for its// depth modulo 3, counting lists of either kind; numbering keeps its start.diff --git a/packages/richtext/src/strikethroughDeletion.test.tsx b/packages/richtext/src/strikethroughDeletion.test.tsxnew file mode 100644index 0000000000..ed444becb1--- /dev/null+++ b/packages/richtext/src/strikethroughDeletion.test.tsx@@ -0,0 +1,135 @@+// 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.tsnew file mode 100644index 0000000000..d5fd7b47b0--- /dev/null+++ b/packages/richtext/src/strikethroughDeletion.ts@@ -0,0 +1,78 @@+// 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,+ );+ },+ }),+ ],+ });