An open source design system that's fully customizable and agent ready
TypeScript
feat(richtext): Cmd+A selects the code block or table cell first (#8584)
Ernesta3976f6232fb
diff --git a/.changeset/in-richtexteditor-cmd-a-ctrl-a-on-other-platform-vt3a.md b/.changeset/in-richtexteditor-cmd-a-ctrl-a-on-other-platform-vt3a.mdnew file mode 100644index 0000000000..6f01ed223d--- /dev/null+++ b/.changeset/in-richtexteditor-cmd-a-ctrl-a-on-other-platform-vt3a.md@@ -0,0 +1,6 @@+---+'@astryxdesign/richtext': patch+---++[feat] In `RichTextEditor`, Cmd+A (Ctrl+A on other platforms) in a code block or a table cell now selects the code or the cell text first, and the whole document on the next press. Anywhere else it still selects the whole document at once.+@emilyhorsman @ernesttdiff --git a/packages/richtext/src/RichTextEditor.doc.mjs b/packages/richtext/src/RichTextEditor.doc.mjsindex db8885c886..b0076e9ba9 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:+ 'Cmd+A (Ctrl+A on other platforms) in a code block or a table cell selects the code or the cell text first; pressing it again selects the whole document. Anywhere else it selects the whole document at once.',+ },{guidance: true,description:diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsxindex 3272fb5ab9..92c52460df 100644--- a/packages/richtext/src/RichTextEditor.tsx+++ b/packages/richtext/src/RichTextEditor.tsx@@ -83,6 +83,7 @@ import {MarkdownExtensionsPlugin} from './MarkdownExtensionsPlugin';import type {RichTextMarkdownExtension} from './markdownExtensions';import type {CodeLanguage} from '@astryxdesign/core/CodeBlock';import {TaskCheckboxPlugin} from './TaskCheckboxPlugin';+import {SelectAllScopePlugin} from './SelectAllScopePlugin';import {type Transformer} from '@lexical/markdown';import {$generateHtmlFromNodes} from '@lexical/html';import {DEFAULT_NODES} from './editorNodes';@@ -730,6 +731,7 @@ export const RichTextEditor = function RichTextEditor({) : null}<TabIndentationPlugin /><TabFocusEscapePlugin />+ <SelectAllScopePlugin />{hasMarkdownShortcuts && (<MarkdownShortcutPlugin transformers={markdownTransformers} />)}diff --git a/packages/richtext/src/SelectAllScopePlugin.test.tsx b/packages/richtext/src/SelectAllScopePlugin.test.tsxnew file mode 100644index 0000000000..4bc057c0b9--- /dev/null+++ b/packages/richtext/src/SelectAllScopePlugin.test.tsx@@ -0,0 +1,185 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SelectAllScopePlugin.test.tsx+ * @input Uses vitest, @testing-library/react, lexical, RichTextEditor, and the+ * Markdown serializers.+ * @output Presses Ctrl+A (Mod+A off Apple platforms) in a mounted+ * RichTextEditor and checks that a code block or table cell holding the+ * caret is selected first and the whole document on the next press.+ * @position Testing; validates SelectAllScopePlugin.tsx through+ * RichTextEditor.+ */++import {beforeAll, describe, expect, it} from 'vitest';+import {createRef} from 'react';+import {act, fireEvent, render} from '@testing-library/react';+import {+ $getRoot,+ $getSelection,+ $isRangeSelection,+ SELECT_ALL_COMMAND,+ SKIP_SCROLL_INTO_VIEW_TAG,+ type LexicalEditor,+} from 'lexical';+import {+ RichTextEditor,+ type RichTextEditorProps,+ type RichTextEditorRef,+} from './RichTextEditor';+import {markdownToEditorStateJSON} from './markdownSerializers';++// jsdom's Range has no getBoundingClientRect, which Lexical calls to scroll+// the selection into view in a focused editor.+beforeAll(() => {+ if (typeof Range.prototype.getBoundingClientRect !== 'function') {+ Range.prototype.getBoundingClientRect = () => new DOMRect();+ }+});++const DOCUMENT =+ 'Above.\n\n```sql\nSELECT 1\nFROM t\n```\n\n| Owner | Approved |\n| --- | --- |\n| Ada | Yes |\n\nBelow.\n';++function mount(props: Partial<RichTextEditorProps> = {}): LexicalEditor {+ const ref = createRef<RichTextEditorRef>();+ render(+ <RichTextEditor+ label="Notes"+ {...props}+ ref={ref}+ defaultValue={markdownToEditorStateJSON(DOCUMENT)}+ />,+ );+ const editor = ref.current?.getEditor();+ if (editor == null) {+ throw new Error('No editor');+ }+ return editor;+}++/**+ * Focuses the editor, as a person typing in it has, and puts the caret in+ * the text that starts with `text`. A non-editable editor keeps no DOM+ * selection, so focusing it would move the caret; it is left unfocused.+ */+async function caretIn(editor: LexicalEditor, text: string): Promise<void> {+ await act(async () => {+ if (editor.isEditable()) {+ editor.getRootElement()?.focus();+ }+ editor.update(+ () => {+ const node = $getRoot()+ .getAllTextNodes()+ .find(textNode => textNode.getTextContent().startsWith(text));+ if (node == null) {+ throw new Error(`No text starts with ${text}`);+ }+ node.select(1, 1);+ },+ {discrete: true, tag: SKIP_SCROLL_INTO_VIEW_TAG},+ );+ });+}++function selectedText(editor: LexicalEditor): string {+ return editor.getEditorState().read(() => {+ const selection = $getSelection();+ return $isRangeSelection(selection) ? selection.getTextContent() : '';+ });+}++/** Presses Ctrl+A, the select-all shortcut off Apple platforms. */+async function selectAll(editor: LexicalEditor): Promise<string> {+ const root = editor.getRootElement();+ if (root == null) {+ throw new Error('No editor root');+ }+ await act(async () => {+ fireEvent.keyDown(root, {key: 'a', ctrlKey: true});+ });+ return selectedText(editor);+}++function expectWholeDocument(text: string): void {+ expect(text).toContain('Above.');+ expect(text).toContain('SELECT 1');+ expect(text).toContain('Approved');+ expect(text).toContain('Below.');+}++describe('select all, one scope at a time', () => {+ it('selects the code block holding the caret, then the whole document', async () => {+ const editor = mount();+ await caretIn(editor, 'SELECT 1');+ expect(await selectAll(editor)).toBe('SELECT 1\nFROM t');+ expectWholeDocument(await selectAll(editor));+ });++ it('selects the table cell holding the caret, then the whole document', async () => {+ const editor = mount();+ await caretIn(editor, 'Approved');+ expect(await selectAll(editor)).toBe('Approved');+ expectWholeDocument(await selectAll(editor));+ });++ it('selects the whole document at once from a paragraph', async () => {+ const editor = mount();+ await caretIn(editor, 'Above.');+ expectWholeDocument(await selectAll(editor));+ });++ it('selects the whole document when the code block is already selected', async () => {+ const editor = mount();+ await act(async () => {+ editor.getRootElement()?.focus();+ editor.update(+ () => {+ const code = $getRoot()+ .getAllTextNodes()+ .find(node => node.getTextContent().startsWith('SELECT 1'))+ ?.getParent();+ if (code == null) {+ throw new Error('No code block');+ }+ code.select(0, code.getChildrenSize());+ },+ {discrete: true, tag: SKIP_SCROLL_INTO_VIEW_TAG},+ );+ });+ expectWholeDocument(await selectAll(editor));+ });++ it('selects the whole document when the selection runs out of the code block', async () => {+ const editor = mount();+ await act(async () => {+ editor.getRootElement()?.focus();+ editor.update(+ () => {+ const texts = $getRoot().getAllTextNodes();+ const code = texts.find(node =>+ node.getTextContent().startsWith('SELECT 1'),+ );+ const below = texts.find(node => node.getTextContent() === 'Below.');+ if (code == null || below == null) {+ throw new Error('No code block or closing paragraph');+ }+ const selection = code.select(1, 1);+ selection.focus.set(below.getKey(), 2, 'text');+ },+ {discrete: true, tag: SKIP_SCROLL_INTO_VIEW_TAG},+ );+ });+ expectWholeDocument(await selectAll(editor));+ });++ it('keeps select all whole in a read-only editor', async () => {+ const editor = mount({isReadOnly: true});+ await caretIn(editor, 'SELECT 1');+ // Past the DOM, which ignores keys in a non-editable editor.+ await act(async () => {+ editor.dispatchCommand(SELECT_ALL_COMMAND, new KeyboardEvent('keydown'));+ });+ expectWholeDocument(selectedText(editor));+ });+});diff --git a/packages/richtext/src/SelectAllScopePlugin.tsx b/packages/richtext/src/SelectAllScopePlugin.tsxnew file mode 100644index 0000000000..24d208705c--- /dev/null+++ b/packages/richtext/src/SelectAllScopePlugin.tsx@@ -0,0 +1,86 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file SelectAllScopePlugin.tsx+ * @input Uses @lexical/react (composer context), @lexical/code (CodeNode),+ * @lexical/table (TableCellNode), and lexical (the select-all command and+ * selection).+ * @output Exports SelectAllScopePlugin, which makes Cmd+A (Ctrl+A off Apple+ * platforms) select the content of the code block or table cell holding the+ * caret first, and the whole document on the next press.+ * @position Rendered by RichTextEditor, always on; a read-only or disabled+ * editor keeps the browser's and Lexical's select all. Elsewhere, and when+ * the selection already covers its code block or cell or runs outside it,+ * the press falls through to Lexical's own select all, which takes the+ * whole document.+ */++import {useEffect} from 'react';+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';+import {$isCodeNode} from '@lexical/code';+import {$isTableCellNode} from '@lexical/table';+import {+ $getSelection,+ $isBlockFullySelected,+ $isRangeSelection,+ COMMAND_PRIORITY_NORMAL,+ SELECT_ALL_COMMAND,+ type ElementNode,+ type LexicalEditor,+ type LexicalNode,+} from 'lexical';++/** Whether select all stops at `node` before taking the whole document. */+function $isScope(node: LexicalNode): node is ElementNode {+ return $isCodeNode(node) || $isTableCellNode(node);+}++/** The scopes holding `node`, innermost first. */+function $scopesOf(node: LexicalNode): Array<ElementNode> {+ const scopes: Array<ElementNode> = [];+ for (let at: LexicalNode | null = node; at !== null; at = at.getParent()) {+ if ($isScope(at)) {+ scopes.push(at);+ }+ }+ return scopes;+}++/**+ * Selects the content of the innermost scope that holds the whole selection+ * and is not yet fully selected; false, to let the document be selected,+ * when there is none.+ */+function $selectScope(): boolean {+ const selection = $getSelection();+ if (!$isRangeSelection(selection)) {+ return false;+ }+ const focusScopes = $scopesOf(selection.focus.getNode());+ for (const scope of $scopesOf(selection.anchor.getNode())) {+ if (+ focusScopes.some(each => each.is(scope)) &&+ !$isBlockFullySelected(scope, selection)+ ) {+ scope.select(0, scope.getChildrenSize());+ return true;+ }+ }+ return false;+}++function registerSelectAllScope(editor: LexicalEditor): () => void {+ return editor.registerCommand(+ SELECT_ALL_COMMAND,+ () => editor.isEditable() && $selectScope(),+ COMMAND_PRIORITY_NORMAL,+ );+}++export function SelectAllScopePlugin(): null {+ const [editor] = useLexicalComposerContext();+ useEffect(() => registerSelectAllScope(editor), [editor]);+ return null;+}