Skip to content

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

TypeScript

fix(richtext): paste rich content into a code block as plain text (#8580)

Ernest47cad741218a
diff --git a/.changeset/richtext-code-paste.md b/.changeset/richtext-code-paste.md
new file mode 100644
index 0000000000..73fad7d49a
--- /dev/null
+++ b/.changeset/richtext-code-paste.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/richtext': patch
+---
+
+[fix] In `RichTextEditor`, pasting rich content into a code block inserts plain text: the plain text on the clipboard, or, when there is none, each pasted block as one line of its text. Headings, lists, tables, and formatting used to land inside the code block, where the Markdown export wrote them as plain lines of the fence, so the document read back differently from what the editor showed.
+@emilyhorsman @ernestt
diff --git a/packages/richtext/README.md b/packages/richtext/README.md
index 5ab8aeb207..248633c173 100644
--- a/packages/richtext/README.md
+++ b/packages/richtext/README.md
@@ -74,6 +74,9 @@ if your app has its own reset) loads first.
Backspace at the very start of a code block turns it into a paragraph of its
lines, instead of merging the code into the block above.
+Pasting rich content into a code block inserts its plain text, one line per
+block: headings, lists, tables, and formatting never land inside the code.
+
## Examples
Interactive examples live in Storybook under **RichText/RichTextEditor**
diff --git a/packages/richtext/src/CodePastePlugin.test.tsx b/packages/richtext/src/CodePastePlugin.test.tsx
new file mode 100644
index 0000000000..33f5ccef8b
--- /dev/null
+++ b/packages/richtext/src/CodePastePlugin.test.tsx
@@ -0,0 +1,369 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest';
+import {act, render, screen, waitFor} from '@testing-library/react';
+import {useEffect} from 'react';
+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
+import {$isCodeNode, type CodeNode} from '@lexical/code';
+import {$createLinkNode} from '@lexical/link';
+import {
+ $createTextNode,
+ $getRoot,
+ $isLineBreakNode,
+ $isTextNode,
+ PASTE_COMMAND,
+ type LexicalEditor,
+} from 'lexical';
+import {
+ createMarkdownPlugin,
+ type MarkdownExtensionNode,
+} from '@astryxdesign/core/Markdown/plugins';
+import {RichTextEditor} from './RichTextEditor';
+import {createRichTextExtension, markdownToEditorStateJSON} from './markdown';
+
+// jsdom has no clipboard or drag events; Lexical tells a paste from a drop
+// by these classes.
+beforeAll(() => {
+ if (typeof ClipboardEvent === 'undefined') {
+ vi.stubGlobal('ClipboardEvent', class ClipboardEvent extends Event {});
+ }
+ if (typeof DragEvent === 'undefined') {
+ vi.stubGlobal('DragEvent', class DragEvent extends Event {});
+ }
+});
+afterAll(() => {
+ vi.unstubAllGlobals();
+});
+
+/** A paragraph, a code block ending in an empty line, and a paragraph. */
+const DOCUMENT = 'Run it:\n\n```ts\nconst x = 1;\n\n```\n\nDone.\n';
+
+type MentionNode = MarkdownExtensionNode<
+ 'test-mentions',
+ 'mention',
+ {readonly label: string},
+ 'inline'
+>;
+
+/** A Markdown plugin that reads `@{name}` as an inline mention node. */
+const MENTIONS = createRichTextExtension(
+ createMarkdownPlugin<'test-mentions', MentionNode>({
+ name: 'test-mentions',
+ apiVersion: 1,
+ parseKey: 'v1',
+ syntax: {
+ inline: [
+ {
+ startsWith: ['@{'],
+ maxSpan: 40,
+ tokenize({source, offset, end}) {
+ const close = source.indexOf('}', offset + 2);
+ if (close < 0 || close >= end) {
+ return {status: 'no-match'};
+ }
+ return {
+ status: 'match',
+ end: close + 1,
+ node: {
+ type: 'extension',
+ plugin: 'test-mentions',
+ name: 'mention',
+ display: 'inline',
+ data: {label: source.slice(offset + 2, close)},
+ },
+ };
+ },
+ },
+ ],
+ },
+ renderers: {
+ mention: {
+ render: ({node}) => <mark>@{node.data.label}</mark>,
+ toText: node => `@${node.data.label}`,
+ },
+ },
+ }),
+);
+
+type FieldNode = MarkdownExtensionNode<
+ 'test-fields',
+ 'field',
+ {readonly label: string},
+ 'inline'
+>;
+
+/** A Markdown plugin that draws `%{name}` as an inline text input. */
+const FIELDS = createRichTextExtension(
+ createMarkdownPlugin<'test-fields', FieldNode>({
+ name: 'test-fields',
+ apiVersion: 1,
+ parseKey: 'v1',
+ syntax: {
+ inline: [
+ {
+ startsWith: ['%{'],
+ maxSpan: 40,
+ tokenize({source, offset, end}) {
+ const close = source.indexOf('}', offset + 2);
+ if (close < 0 || close >= end) {
+ return {status: 'no-match'};
+ }
+ return {
+ status: 'match',
+ end: close + 1,
+ node: {
+ type: 'extension',
+ plugin: 'test-fields',
+ name: 'field',
+ display: 'inline',
+ data: {label: source.slice(offset + 2, close)},
+ },
+ };
+ },
+ },
+ ],
+ },
+ renderers: {
+ field: {
+ render: ({node}) => <input aria-label={node.data.label} />,
+ toText: node => node.data.label,
+ },
+ },
+ }),
+);
+
+async function renderEditor(
+ document: string = DOCUMENT,
+): Promise<LexicalEditor> {
+ let captured: LexicalEditor | undefined;
+ function CaptureEditor() {
+ const [editor] = useLexicalComposerContext();
+ useEffect(() => {
+ captured = editor;
+ }, [editor]);
+ return null;
+ }
+ render(
+ <RichTextEditor
+ label="Notes"
+ defaultValue={markdownToEditorStateJSON(document, {
+ extensions: [MENTIONS, FIELDS],
+ })}
+ markdownExtensions={[MENTIONS, FIELDS]}
+ plugins={<CaptureEditor />}
+ />,
+ );
+ await waitFor(() => expect(captured).toBeDefined());
+ return captured!;
+}
+
+function $codeBlock(): CodeNode {
+ const code = $getRoot().getChildren().find($isCodeNode);
+ if (code == null) {
+ throw new Error('The editor holds no code block');
+ }
+ return code;
+}
+
+/** Puts the caret on the code block's empty last line. */
+function caretInCode(editor: LexicalEditor) {
+ act(() => {
+ editor.update(() => $codeBlock().selectEnd(), {discrete: true});
+ });
+}
+
+/** Pastes clipboard data of the given types, and commits the paste. */
+function paste(
+ editor: LexicalEditor,
+ data: Record<string, string>,
+ target?: EventTarget,
+) {
+ const event = new ClipboardEvent('paste', {cancelable: true});
+ if (target != null) {
+ Object.defineProperty(event, 'target', {value: target});
+ }
+ Object.defineProperty(event, 'clipboardData', {
+ value: {
+ getData: (type: string) => data[type] ?? '',
+ types: Object.keys(data),
+ files: [],
+ },
+ });
+ act(() => {
+ editor.dispatchCommand(PASTE_COMMAND, event);
+ editor.read(() => undefined);
+ });
+}
+
+/**
+ * Each top-level block's type, the code block's text, and anything the code
+ * block holds besides plain code: an element, a decorator, or formatted text.
+ */
+function shape(editor: LexicalEditor) {
+ return editor.read(() => {
+ const code = $codeBlock();
+ return {
+ blocks: $getRoot()
+ .getChildren()
+ .map(block => block.getType()),
+ code: code.getTextContent(),
+ codeHolds: code.getChildren().flatMap(child => {
+ if ($isTextNode(child)) {
+ return child.getFormat() === 0
+ ? []
+ : [`formatted ${child.getType()}`];
+ }
+ return $isLineBreakNode(child) ? [] : [child.getType()];
+ }),
+ };
+ });
+}
+
+/** A word processor's clipboard: a heading, formatted text, a list, a table. */
+const RICH_HTML =
+ '<h2>Plan</h2>' +
+ '<p><b>Bold</b> and <i>italic</i> with <a href="https://example.com">a link</a></p>' +
+ '<ul><li>one</li><li>two</li></ul>' +
+ '<table><tbody><tr><td>a</td><td>b</td></tr></tbody></table>';
+const RICH_TEXT = 'Plan\nBold and italic with a link\none\ntwo\na\tb';
+
+describe('pasting into a code block', () => {
+ it('pastes rich content as the plain text on the clipboard', async () => {
+ const editor = await renderEditor();
+ caretInCode(editor);
+
+ paste(editor, {'text/html': RICH_HTML, 'text/plain': RICH_TEXT});
+ expect(shape(editor)).toEqual({
+ blocks: ['paragraph', 'code', 'paragraph'],
+ code: `const x = 1;\n${RICH_TEXT}`,
+ codeHolds: [],
+ });
+ });
+
+ it('keeps copied code exactly, indentation included', async () => {
+ const editor = await renderEditor();
+ caretInCode(editor);
+ const code = 'if (x) {\n\treturn 1;\n}';
+
+ paste(editor, {
+ 'text/html': `<pre><code>${code}</code></pre>`,
+ 'text/plain': code,
+ });
+ expect(shape(editor)).toEqual({
+ blocks: ['paragraph', 'code', 'paragraph'],
+ code: `const x = 1;\n${code}`,
+ codeHolds: [],
+ });
+ });
+
+ it('pastes HTML with no plain text as the text of its blocks, one line each', async () => {
+ const editor = await renderEditor();
+ caretInCode(editor);
+
+ paste(editor, {
+ 'text/html':
+ '<p>intro</p><table><tr><td>a</td><td>b</td></tr></table><ul><li>one</li><li>two</li></ul>',
+ });
+ expect(shape(editor)).toEqual({
+ blocks: ['paragraph', 'code', 'paragraph'],
+ code: 'const x = 1;\nintro\na\nb\none\ntwo',
+ codeHolds: [],
+ });
+ });
+
+ it('pastes blocks copied from an editor, with no plain text, as their lines', async () => {
+ const editor = await renderEditor();
+ caretInCode(editor);
+ const copied = JSON.parse(
+ markdownToEditorStateJSON('## Heading\n\n- one\n- two\n\n**Last**\n'),
+ ).root.children;
+
+ paste(editor, {
+ 'application/x-lexical-editor': JSON.stringify({
+ namespace: 'astryx-editor',
+ nodes: copied,
+ }),
+ });
+ expect(shape(editor)).toEqual({
+ blocks: ['paragraph', 'code', 'paragraph'],
+ code: 'const x = 1;\nHeading\none\ntwo\nLast',
+ codeHolds: [],
+ });
+ });
+
+ it('pastes a Markdown plugin node as its source (spec:AST-064)', async () => {
+ const editor = await renderEditor();
+ caretInCode(editor);
+ // Inline content copied from inside a paragraph: text and a mention.
+ const [paragraph] = JSON.parse(
+ markdownToEditorStateJSON('Hi @{ada}', {extensions: [MENTIONS]}),
+ ).root.children;
+
+ paste(editor, {
+ 'application/x-lexical-editor': JSON.stringify({
+ namespace: 'astryx-editor',
+ nodes: paragraph.children,
+ }),
+ });
+ expect(shape(editor)).toEqual({
+ blocks: ['paragraph', 'code', 'paragraph'],
+ code: 'const x = 1;\nHi @{ada}',
+ codeHolds: [],
+ });
+ });
+
+ it('still pastes rich content as blocks outside a code block', async () => {
+ const editor = await renderEditor();
+ act(() => {
+ editor.update(() => $getRoot().getLastChildOrThrow().selectEnd(), {
+ discrete: true,
+ });
+ });
+
+ paste(editor, {
+ 'text/html': '<h2>Plan</h2><p>Next</p>',
+ 'text/plain': 'Plan\nNext',
+ });
+ const after = shape(editor);
+ expect(after.code).toBe('const x = 1;\n');
+ expect(after.blocks).toEqual([
+ 'paragraph',
+ 'code',
+ 'paragraph',
+ 'paragraph',
+ ]);
+ });
+
+ it('pastes plain text when the caret is inside a link in a code block', async () => {
+ const editor = await renderEditor();
+ act(() => {
+ editor.update(
+ () => {
+ const url = $createTextNode('https://example.com');
+ const link = $createLinkNode('https://example.com');
+ link.append(url);
+ $codeBlock().append(link);
+ url.select(5, 5);
+ },
+ {discrete: true},
+ );
+ });
+
+ paste(editor, {'text/html': RICH_HTML, 'text/plain': RICH_TEXT});
+ const after = shape(editor);
+ expect(after.blocks).toEqual(['paragraph', 'code', 'paragraph']);
+ expect(after.code).toContain(RICH_TEXT);
+ });
+
+ it('leaves a paste into an input a plugin node draws to that input', async () => {
+ const editor = await renderEditor(
+ 'Name %{Inline field}:\n\n```ts\nconst x = 1;\n\n```\n\nDone.\n',
+ );
+ caretInCode(editor);
+ const input = await screen.findByRole('textbox', {name: 'Inline field'});
+ act(() => input.focus());
+
+ paste(editor, {'text/html': RICH_HTML, 'text/plain': RICH_TEXT}, input);
+ expect(shape(editor).code).toBe('const x = 1;\n');
+ });
+});
diff --git a/packages/richtext/src/CodePastePlugin.tsx b/packages/richtext/src/CodePastePlugin.tsx
new file mode 100644
index 0000000000..76ca226bb3
--- /dev/null
+++ b/packages/richtext/src/CodePastePlugin.tsx
@@ -0,0 +1,143 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file CodePastePlugin.tsx
+ * @input Uses @lexical/react (composer context), @lexical/code (CodeNode), and
+ * lexical.
+ * @output Exports CodePastePlugin, which makes rich content pasted or dropped
+ * into a code block go in as plain lines of code.
+ * @position Rendered by RichTextEditor; always on; not exported. A paste
+ * whose selection starts in a code block goes in as plain text: the
+ * clipboard's plain text, or else one line per pasted block.
+ */
+
+import {useEffect} from 'react';
+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
+import {$isCodeNode} from '@lexical/code';
+import {
+ $addUpdateTag,
+ $findMatchingParent,
+ $getSelection,
+ $isElementNode,
+ $isRangeSelection,
+ $isSelectionCapturedInDecoratorInput,
+ COMMAND_PRIORITY_LOW,
+ isDOMNode,
+ mergeRegister,
+ PASTE_COMMAND,
+ PASTE_TAG,
+ SELECTION_INSERT_CLIPBOARD_NODES_COMMAND,
+ type BaseSelection,
+ type LexicalNode,
+ type RangeSelection,
+} from 'lexical';
+
+/** Clipboard types that carry more than plain text. */
+const RICH_TYPES = ['text/html', 'application/x-lexical-editor'];
+
+/** Whether content inserted at the selection lands in a code block. */
+function $startsInCodeBlock(
+ selection: BaseSelection | null,
+): selection is RangeSelection {
+ if (!$isRangeSelection(selection)) {
+ return false;
+ }
+ const start = selection.isBackward() ? selection.focus : selection.anchor;
+ const node = start.getNode();
+ // A link (an autolinked URL) can sit between the text and its code block.
+ return $findMatchingParent(node, $isCodeNode) !== null;
+}
+
+/**
+ * Clipboard nodes as plain lines: each block's text on a line of its own (a
+ * paragraph, a heading, a list item, a table cell), and inline content
+ * between blocks on one line.
+ */
+function $plainLinesOf(nodes: ReadonlyArray<LexicalNode>): string {
+ const lines: string[] = [];
+ let inline: string | null = null;
+ const endInline = () => {
+ if (inline != null) {
+ lines.push(inline);
+ inline = null;
+ }
+ };
+ const visit = (node: LexicalNode) => {
+ if (node.isInline()) {
+ inline = (inline ?? '') + node.getTextContent();
+ return;
+ }
+ endInline();
+ if (
+ $isElementNode(node) &&
+ node.getChildren().some(child => !child.isInline())
+ ) {
+ node.getChildren().forEach(visit);
+ endInline();
+ } else {
+ lines.push(node.getTextContent());
+ }
+ };
+ nodes.forEach(visit);
+ endInline();
+ return lines.join('\n');
+}
+
+export function CodePastePlugin(): null {
+ const [editor] = useLexicalComposerContext();
+ useEffect(
+ () =>
+ mergeRegister(
+ // Ahead of the rich-text paste, which inserts the clipboard's rich
+ // content when there is any.
+ editor.registerCommand(
+ PASTE_COMMAND,
+ event => {
+ // A paste into an input a decorator node renders is that input's.
+ if (
+ isDOMNode(event.target) &&
+ $isSelectionCapturedInDecoratorInput(event.target)
+ ) {
+ return false;
+ }
+ const data = 'clipboardData' in event ? event.clipboardData : null;
+ if (
+ !editor.isEditable() ||
+ data == null ||
+ !RICH_TYPES.some(type => data.types.includes(type))
+ ) {
+ return false;
+ }
+ const text = data.getData('text/plain');
+ const selection = $getSelection();
+ if (text === '' || !$startsInCodeBlock(selection)) {
+ return false;
+ }
+ event.preventDefault();
+ // Its own undo step, as every paste is.
+ $addUpdateTag(PASTE_TAG);
+ selection.insertRawText(text);
+ return true;
+ },
+ COMMAND_PRIORITY_LOW,
+ ),
+ // Every insertion of clipboard nodes, a paste with no plain text or a
+ // drop, comes through here; ahead of the table's own handler.
+ editor.registerCommand(
+ SELECTION_INSERT_CLIPBOARD_NODES_COMMAND,
+ ({nodes, selection}) => {
+ if (!$startsInCodeBlock(selection)) {
+ return false;
+ }
+ selection.insertRawText($plainLinesOf(nodes));
+ return true;
+ },
+ COMMAND_PRIORITY_LOW,
+ ),
+ ),
+ [editor],
+ );
+ return null;
+}
diff --git a/packages/richtext/src/RichTextEditor.doc.mjs b/packages/richtext/src/RichTextEditor.doc.mjs
index 30fe89fdac..f4faafd4f0 100644
--- a/packages/richtext/src/RichTextEditor.doc.mjs
+++ b/packages/richtext/src/RichTextEditor.doc.mjs
@@ -243,6 +243,11 @@ export const docs = {
description:
'Backspace at the very start of a code block turns it into a paragraph holding its lines, each on its own line, with the caret at its start. The code never merges into the block above, so a heading above keeps its own text. Backspace anywhere else in a code block deletes as usual.',
},
+ {
+ guidance: true,
+ description:
+ 'Pasting into a code block inserts plain code. Rich content, such as a web page, a word processor document, or blocks copied from another editor, goes in as the plain text on the clipboard; when the clipboard has no plain text, each pasted block goes in as one line of its text. Headings, lists, tables, and formatting never land inside a code block.',
+ },
{
guidance: true,
description:
diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsx
index f4da33c6a8..66a2a5579b 100644
--- a/packages/richtext/src/RichTextEditor.tsx
+++ b/packages/richtext/src/RichTextEditor.tsx
@@ -79,6 +79,7 @@ import {TextSemanticsExtension} from './textSemantics';
import {TableColumnFloorPlugin} from './TableColumnFloorPlugin';
import {CodeBackspacePlugin} from './CodeBackspacePlugin';
import {CodeBlockHeaderPlugin} from './CodeBlockHeaderPlugin';
+import {CodePastePlugin} from './CodePastePlugin';
import {CodeSyntaxPlugin} from './CodeSyntaxPlugin';
import {MarkdownExtensionsPlugin} from './MarkdownExtensionsPlugin';
import type {RichTextMarkdownExtension} from './markdownExtensions';
@@ -729,6 +730,7 @@ export const RichTextEditor = function RichTextEditor({
{/* Backspace at the very start of a code block makes it a
paragraph, instead of merging it into the block above. */}
<CodeBackspacePlugin />
+ <CodePastePlugin />
{markdownExtensions != null && markdownExtensions.length > 0 ? (
<MarkdownExtensionsPlugin
extensions={markdownExtensions}