An open source design system that's fully customizable and agent ready
TypeScript
fix(richtext): turn a code block into a paragraph on Backspace at its start (#8581)
Ernestc5c1f52750c3
diff --git a/.changeset/richtext-code-backspace.md b/.changeset/richtext-code-backspace.mdnew file mode 100644index 0000000000..09654a9519--- /dev/null+++ b/.changeset/richtext-code-backspace.md@@ -0,0 +1,6 @@+---+'@astryxdesign/richtext': patch+---++[fix] In `RichTextEditor`, Backspace at the very start of a code block turns it into a paragraph holding its lines, with the caret at its start. It used to merge the code into the block above, so a heading above took the code in, and the Markdown read back as a longer heading and a stray paragraph. A code block with nothing above it, which already became a paragraph, now keeps its lines when its Markdown is read back.+@emilyhorsman @ernesttdiff --git a/packages/richtext/README.md b/packages/richtext/README.mdindex 7e4d8be10d..5ab8aeb207 100644--- a/packages/richtext/README.md+++ b/packages/richtext/README.md@@ -69,6 +69,11 @@ so your theme's token overrides (`@layer astryx-theme`) win over it, as longas Core's `reset.css` (or a `@layer reset, astryx-base, astryx-theme;` line,if your app has its own reset) loads first.+## Editing code blocks++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.+## ExamplesInteractive examples live in Storybook under **RichText/RichTextEditor**diff --git a/packages/richtext/src/CodeBackspacePlugin.test.tsx b/packages/richtext/src/CodeBackspacePlugin.test.tsxnew file mode 100644index 0000000000..f8383964ae--- /dev/null+++ b/packages/richtext/src/CodeBackspacePlugin.test.tsx@@ -0,0 +1,285 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {beforeAll, describe, expect, it} from 'vitest';+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@testing-library/react';+import {createRef} from 'react';+import {$isCodeNode, type CodeNode} from '@lexical/code';+import {$isHeadingNode} from '@lexical/rich-text';+import {+ $createLineBreakNode,+ $createTextNode,+ $getRoot,+ $getSelection,+ $isElementNode,+ $isLineBreakNode,+ $isRangeSelection,+ $isTextNode,+ DELETE_CHARACTER_COMMAND,+ type LexicalEditor,+} from 'lexical';+import {RichTextEditor, type RichTextEditorRef} from './RichTextEditor';+import {markdownToEditorStateJSON} from './markdownSerializers';++// jsdom's Range has no getBoundingClientRect, which Lexical calls to scroll+// the selection into view while the editor has focus.+beforeAll(() => {+ if (typeof Range.prototype.getBoundingClientRect !== 'function') {+ Range.prototype.getBoundingClientRect = () => new DOMRect();+ }+});++async function renderMarkdown(markdown: string, {isReadOnly = false} = {}) {+ const ref = createRef<RichTextEditorRef>();+ render(+ <RichTextEditor+ ref={ref}+ label="Notes"+ isReadOnly={isReadOnly}+ defaultValue={markdownToEditorStateJSON(markdown)}+ />,+ );+ await waitFor(() => expect(ref.current).not.toBeNull());+ const textbox = screen.getByRole('textbox', {name: 'Notes'});+ textbox.focus();+ const handle = ref.current!;+ return {handle, editor: handle.getEditor(), textbox};+}++function $codeBlock(): CodeNode {+ const code = $getRoot().getChildren().find($isCodeNode);+ if (code == null) {+ throw new Error('The editor holds no code block');+ }+ return code;+}++/** Selects from one offset of the code block's text to another. */+function selectInCode(editor: LexicalEditor, from: number, to = from) {+ act(() => {+ editor.update(+ () => {+ const first = $codeBlock().getFirstChild();+ if ($isTextNode(first)) {+ first.select(from, to);+ } else {+ $codeBlock().selectStart();+ }+ },+ {discrete: true},+ );+ });+}++/**+ * Presses Backspace and commits the edit it scheduled, as a browser does+ * before the next key. Returns whether the editor kept the key.+ */+function pressBackspace(editor: LexicalEditor, textbox: HTMLElement): boolean {+ const kept = !fireEvent.keyDown(textbox, {+ key: 'Backspace',+ code: 'Backspace',+ });+ editor.read(() => undefined);+ return kept;+}++/**+ * Each top-level block as `type: content`, a heading by its tag: a line+ * break node is `⏎`, a newline inside text stays a newline, and a collapsed+ * caret is `|`.+ */+function blocks(editor: LexicalEditor): string[] {+ return editor.read(() => {+ const selection = $getSelection();+ const caret =+ $isRangeSelection(selection) && selection.isCollapsed()+ ? selection.anchor+ : null;+ return $getRoot()+ .getChildren()+ .map(block => {+ const name = $isHeadingNode(block) ? block.getTag() : block.getType();+ const children = $isElementNode(block) ? block.getChildren() : [];+ const caretAt = (index: number) =>+ caret?.key === block.getKey() && caret.offset === index ? '|' : '';+ let content = '';+ children.forEach((child, index) => {+ content += caretAt(index);+ const text = child.getTextContent();+ if ($isLineBreakNode(child)) {+ content += '⏎';+ } else if ($isTextNode(child) && caret?.key === child.getKey()) {+ content += `${text.slice(0, caret.offset)}|${text.slice(caret.offset)}`;+ } else {+ content += text;+ }+ });+ return `${name}: ${content}${caretAt(children.length)}`;+ });+ });+}++const blockTypes = (editor: LexicalEditor) =>+ editor.read(() =>+ $getRoot()+ .getChildren()+ .map(block => block.getType()),+ );++describe('Backspace at the very start of a code block', () => {+ it('turns the block into a paragraph of its lines, and the heading above keeps its text', async () => {+ const {handle, editor, textbox} = await renderMarkdown(+ '### Code and quote\n\n```\nconst first = 1;\nconst second = 2;\n```\n\nAfter the code\n',+ );+ selectInCode(editor, 0);++ expect(pressBackspace(editor, textbox)).toBe(true);+ expect(blocks(editor)).toEqual([+ 'h3: Code and quote',+ 'paragraph: |const first = 1;⏎const second = 2;',+ 'paragraph: After the code',+ ]);+ // Each line break exports as a hard break, so the Markdown reads back+ // as the editor shows it, and the heading as written.+ expect(handle.getMarkdown()).toBe(+ '### Code and quote\n\nconst first = 1;\\\nconst second = 2;\n\nAfter the code\n',+ );+ });++ it('never merges the code into a paragraph above', async () => {+ const {editor, textbox} = await renderMarkdown(+ 'Intro\n\n```\nalpha\nbeta\n```\n',+ );+ selectInCode(editor, 0);++ pressBackspace(editor, textbox);+ expect(blocks(editor)).toEqual([+ 'paragraph: Intro',+ 'paragraph: |alpha⏎beta',+ ]);+ });++ it('keeps the lines of a block with nothing above it', async () => {+ const {handle, editor, textbox} = await renderMarkdown(+ '```\nalpha\nbeta\n```\n\nAfter\n',+ );+ selectInCode(editor, 0);++ pressBackspace(editor, textbox);+ expect(blocks(editor)).toEqual([+ 'paragraph: |alpha⏎beta',+ 'paragraph: After',+ ]);+ expect(handle.getMarkdown()).toBe('alpha\\\nbeta\n\nAfter\n');+ });++ it('drops the empty last line, under a heading and with nothing above', async () => {+ const underHeading = await renderMarkdown(+ '## Title\n\n```\nalpha\n\n```\n\nAfter\n',+ );+ selectInCode(underHeading.editor, 0);+ pressBackspace(underHeading.editor, underHeading.textbox);+ expect(blocks(underHeading.editor)).toEqual([+ 'h2: Title',+ 'paragraph: |alpha',+ 'paragraph: After',+ ]);+ expect(underHeading.handle.getMarkdown()).toBe(+ '## Title\n\nalpha\n\nAfter\n',+ );+ cleanup();++ const alone = await renderMarkdown('```\nalpha\nbeta\n\n```\n');+ selectInCode(alone.editor, 0);+ pressBackspace(alone.editor, alone.textbox);+ expect(blocks(alone.editor)).toEqual(['paragraph: |alpha⏎beta']);+ expect(alone.handle.getMarkdown()).toBe('alpha\\\nbeta\n');+ });++ it('turns an empty block into an empty paragraph', async () => {+ const {editor, textbox} = await renderMarkdown(+ '## Title\n\n```\n```\n\nAfter\n',+ );+ selectInCode(editor, 0);++ pressBackspace(editor, textbox);+ expect(blocks(editor)).toEqual([+ 'h2: Title',+ 'paragraph: |',+ 'paragraph: After',+ ]);+ });++ it('does the same for the backward deletion that input events dispatch', async () => {+ const {editor} = await renderMarkdown('## Title\n\n```\nalpha\n```\n');+ selectInCode(editor, 0);++ act(() => {+ editor.dispatchCommand(DELETE_CHARACTER_COMMAND, true);+ });+ expect(blocks(editor)).toEqual(['h2: Title', 'paragraph: |alpha']);+ });+});++describe('Backspace that keeps its usual meaning', () => {+ // jsdom cannot delete text inside a line, so these check only that the+ // block stays a code block, which is all this behavior decides.+ it('leaves the code block alone with the caret inside its first line', async () => {+ const {editor, textbox} = await renderMarkdown(+ 'Intro\n\n```\nalpha\nbeta\n```\n',+ );+ selectInCode(editor, 'alp'.length);++ pressBackspace(editor, textbox);+ expect(blockTypes(editor)).toEqual(['paragraph', 'code']);+ });++ it('leaves the code block alone at the start of a later line', async () => {+ const {editor, textbox} = await renderMarkdown(+ 'Intro\n\n```\nalpha\n```\n',+ );+ // Lines as Enter leaves them: text nodes with a line break node between,+ // so the caret sits at offset 0 of a text node that is not the first.+ act(() => {+ editor.update(+ () => {+ const second = $createTextNode('beta');+ $codeBlock().append($createLineBreakNode(), second);+ second.select(0, 0);+ },+ {discrete: true},+ );+ });++ pressBackspace(editor, textbox);+ expect(blockTypes(editor)).toEqual(['paragraph', 'code']);+ });++ it('deletes a selection that starts at the block start', async () => {+ const {editor, textbox} = await renderMarkdown(+ 'Intro\n\n```\nalpha\nbeta\n```\n',+ );+ selectInCode(editor, 0, 'alpha'.length);++ pressBackspace(editor, textbox);+ expect(blocks(editor)).toEqual(['paragraph: Intro', 'code: |\nbeta']);+ });++ it('changes nothing in a read-only editor', async () => {+ const {editor, textbox} = await renderMarkdown(+ '## Title\n\n```\nalpha\n```\n',+ {isReadOnly: true},+ );+ selectInCode(editor, 0);++ pressBackspace(editor, textbox);+ expect(blockTypes(editor)).toEqual(['heading', 'code']);+ });+});diff --git a/packages/richtext/src/CodeBackspacePlugin.tsx b/packages/richtext/src/CodeBackspacePlugin.tsxnew file mode 100644index 0000000000..8767579508--- /dev/null+++ b/packages/richtext/src/CodeBackspacePlugin.tsx@@ -0,0 +1,96 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file CodeBackspacePlugin.tsx+ * @input Uses @lexical/react (composer context), @lexical/code (CodeNode), and+ * lexical.+ * @output Exports CodeBackspacePlugin, which makes Backspace at the very start+ * of a code block turn the block into a paragraph holding its lines.+ * @position Rendered by RichTextEditor; always on, not exported. Lexical's+ * own Backspace there merges the code into the block above, and a heading+ * above reads back as a longer heading and a stray paragraph.+ */++import {useEffect} from 'react';+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';+import {$isCodeNode, type CodeNode} from '@lexical/code';+import {+ $createLineBreakNode,+ $createParagraphNode,+ $createTextNode,+ $getSelection,+ $isRangeSelection,+ COMMAND_PRIORITY_LOW,+ DELETE_CHARACTER_COMMAND,+ type ParagraphNode,+} from 'lexical';++/** Start is offset 0 of the block or of its first child, not the start of a later line. */+function $codeBlockAtCaretStart(): CodeNode | null {+ const selection = $getSelection();+ if (+ !$isRangeSelection(selection) ||+ !selection.isCollapsed() ||+ selection.anchor.offset !== 0+ ) {+ return null;+ }+ const node = selection.anchor.getNode();+ const code = $isCodeNode(node) ? node : node.getParent();+ if (!$isCodeNode(code)) {+ return null;+ }+ return node.is(code) || node.is(code.getFirstChild()) ? code : null;+}++/**+ * A newline inside text exports as a soft break, and the lines read back as+ * one. A line break node exports as a hard break. Empty lines at the end of+ * the code are dropped: a hard break that ends a paragraph reads back as a+ * literal backslash.+ */+function $paragraphOfLines(code: CodeNode): ParagraphNode {+ const paragraph = $createParagraphNode();+ code+ .getTextContent()+ .replace(/\n+$/, '')+ .split('\n')+ .forEach((line, index) => {+ if (index > 0) {+ paragraph.append($createLineBreakNode());+ }+ if (line !== '') {+ paragraph.append($createTextNode(line));+ }+ });+ return paragraph;+}++export function CodeBackspacePlugin(): null {+ const [editor] = useLexicalComposerContext();+ useEffect(+ () =>+ editor.registerCommand(+ DELETE_CHARACTER_COMMAND,+ isBackward => {+ if (!isBackward || !editor.isEditable()) {+ return false;+ }+ const code = $codeBlockAtCaretStart();+ if (code == null) {+ return false;+ }+ const paragraph = $paragraphOfLines(code);+ code.replace(paragraph);+ paragraph.selectStart();+ return true;+ },+ // Ahead of the rich-text deletion, which would do the merge.+ COMMAND_PRIORITY_LOW,+ ),+ [editor],+ );+ return null;+}diff --git a/packages/richtext/src/RichTextEditor.doc.mjs b/packages/richtext/src/RichTextEditor.doc.mjsindex b0076e9ba9..30fe89fdac 100644--- a/packages/richtext/src/RichTextEditor.doc.mjs+++ b/packages/richtext/src/RichTextEditor.doc.mjs@@ -238,6 +238,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:+ '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:diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsxindex 04e4744a32..710cbfaa12 100644--- a/packages/richtext/src/RichTextEditor.tsx+++ b/packages/richtext/src/RichTextEditor.tsx@@ -77,6 +77,7 @@ import {TablePlugin} from '@lexical/react/LexicalTablePlugin';import {HorizontalRuleExtension} from '@lexical/extension';import {TextSemanticsExtension} from './textSemantics';import {TableColumnFloorPlugin} from './TableColumnFloorPlugin';+import {CodeBackspacePlugin} from './CodeBackspacePlugin';import {CodeBlockHeaderPlugin} from './CodeBlockHeaderPlugin';import {CodeSyntaxPlugin} from './CodeSyntaxPlugin';import {MarkdownExtensionsPlugin} from './MarkdownExtensionsPlugin';@@ -724,6 +725,9 @@ export const RichTextEditor = function RichTextEditor({<TableColumnFloorPlugin /><CodeBlockHeaderPlugin codeLanguages={codeLanguages} /><CodeSyntaxPlugin codeLanguages={codeLanguages} />+ {/* Backspace at the very start of a code block makes it a+ paragraph, instead of merging it into the block above. */}+ <CodeBackspacePlugin />{markdownExtensions != null && markdownExtensions.length > 0 ? (<MarkdownExtensionsPluginextensions={markdownExtensions}