Skip to content

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

TypeScript

feat(richtext): indent and outdent code block lines with Tab (#8579)

Ernest8fa403c98d8d
diff --git a/.changeset/richtext-code-tab.md b/.changeset/richtext-code-tab.md
new file mode 100644
index 0000000000..76aecb36ee
--- /dev/null
+++ b/.changeset/richtext-code-tab.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/richtext': patch
+---
+
+[feat] In `RichTextEditor`, Tab and Shift+Tab in a code block indent and outdent every line the selection touches, by the indent the block already uses (a tab when one of its lines starts with a tab, otherwise the fewest leading spaces of any indented line, kept between 2 and 8, otherwise 2 spaces). The selection stays on the same characters and each press is one undo step. Tab used to put a tab character in place of the selection, and Shift+Tab did the same. Escape then Tab still moves focus out of the editor.
+@emilyhorsman @ernestt
diff --git a/packages/richtext/README.md b/packages/richtext/README.md
index 248633c173..1895f257b6 100644
--- a/packages/richtext/README.md
+++ b/packages/richtext/README.md
@@ -71,6 +71,12 @@ if your app has its own reset) loads first.
## Editing code blocks
+In a code block, Tab and Shift+Tab indent and outdent every line the selection
+touches, by the indent the block already uses: a tab when one of its lines
+starts with a tab, otherwise the fewest leading spaces of any indented line,
+kept between 2 and 8, otherwise 2 spaces. Press Escape, then Tab, to move focus
+out of the editor.
+
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.
diff --git a/packages/richtext/src/CodeTabPlugin.test.tsx b/packages/richtext/src/CodeTabPlugin.test.tsx
new file mode 100644
index 0000000000..1fbc225231
--- /dev/null
+++ b/packages/richtext/src/CodeTabPlugin.test.tsx
@@ -0,0 +1,311 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {beforeAll, describe, expect, it} from 'vitest';
+import {act, fireEvent, render, screen, waitFor} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {useEffect} from 'react';
+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
+import {$isCodeNode, type CodeNode} from '@lexical/code';
+import {
+ $getRoot,
+ $getSelection,
+ $isParagraphNode,
+ $isRangeSelection,
+ $isTextNode,
+ UNDO_COMMAND,
+ type LexicalEditor,
+} from 'lexical';
+import {RichTextEditor} 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();
+ }
+});
+
+/**
+ * Renders an editor holding a paragraph and then a code block of `code`, and
+ * focuses it.
+ */
+async function renderCode(code: string, {isReadOnly = false} = {}) {
+ let captured: LexicalEditor | undefined;
+ function CaptureEditor() {
+ const [editor] = useLexicalComposerContext();
+ useEffect(() => {
+ captured = editor;
+ }, [editor]);
+ return null;
+ }
+ render(
+ <RichTextEditor
+ label="Notes"
+ isReadOnly={isReadOnly}
+ defaultValue={markdownToEditorStateJSON(
+ `Intro\n\n\`\`\`\n${code}\n\`\`\`\n`,
+ )}
+ plugins={<CaptureEditor />}
+ />,
+ );
+ await waitFor(() => expect(captured).toBeDefined());
+ // The block's frame draws after mount; its Copy code is the next tab stop.
+ await screen.findByRole('button', {name: 'Copy code'});
+ const textbox = screen.getByRole('textbox', {name: 'Notes'});
+ textbox.focus();
+ return {editor: captured!, 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 select(editor: LexicalEditor, from: number, to = from) {
+ act(() => {
+ editor.update(
+ () => {
+ const code = $codeBlock();
+ const pointAt = (offset: number) => {
+ let left = offset;
+ for (const child of code.getChildren()) {
+ const size = child.getTextContentSize();
+ if ($isTextNode(child) && left <= size) {
+ return {key: child.getKey(), offset: left};
+ }
+ left -= size;
+ }
+ throw new Error(`No text at offset ${offset}`);
+ };
+ const anchor = pointAt(from);
+ const focus = pointAt(to);
+ const selection = code.select(0, 0);
+ selection.anchor.set(anchor.key, anchor.offset, 'text');
+ selection.focus.set(focus.key, focus.offset, 'text');
+ },
+ {discrete: true},
+ );
+ });
+}
+
+/**
+ * The code block's text with the selection drawn in: `|` for a caret, or
+ * `[` at the anchor and `]` at the focus.
+ */
+function marked(editor: LexicalEditor): string {
+ // `editor.read` commits the update a key press scheduled before reading.
+ return editor.read(() => {
+ const code = $codeBlock();
+ const selection = $getSelection();
+ const mark = (key: string, offset: number) => {
+ if (!$isRangeSelection(selection)) {
+ return '';
+ }
+ const {anchor, focus} = selection;
+ if (selection.isCollapsed()) {
+ return anchor.key === key && anchor.offset === offset ? '|' : '';
+ }
+ return (
+ (anchor.key === key && anchor.offset === offset ? '[' : '') +
+ (focus.key === key && focus.offset === offset ? ']' : '')
+ );
+ };
+ const children = code.getChildren();
+ let text = '';
+ children.forEach((child, index) => {
+ text += mark(code.getKey(), index);
+ const content = child.getTextContent();
+ if ($isTextNode(child)) {
+ for (let i = 0; i < content.length; i++) {
+ text += mark(child.getKey(), i) + content[i];
+ }
+ text += mark(child.getKey(), content.length);
+ } else {
+ text += content;
+ }
+ });
+ return text + mark(code.getKey(), children.length);
+ });
+}
+
+const codeText = (editor: LexicalEditor) =>
+ editor.read(() => $codeBlock().getTextContent());
+
+/**
+ * Presses Tab and commits the edit it scheduled, as a browser does before the
+ * next key. Returns whether the editor kept the key (default prevented).
+ */
+function pressTab(
+ editor: LexicalEditor,
+ textbox: HTMLElement,
+ shiftKey = false,
+): boolean {
+ const kept = !fireEvent.keyDown(textbox, {key: 'Tab', code: 'Tab', shiftKey});
+ editor.read(() => undefined);
+ return kept;
+}
+
+describe('Tab in a code block', () => {
+ it("indents the caret's line, and Shift+Tab outdents it, with the caret on the same character", async () => {
+ const {editor, textbox} = await renderCode('alpha\n beta\ngamma');
+ select(editor, 'al'.length);
+
+ expect(pressTab(editor, textbox)).toBe(true);
+ expect(marked(editor)).toBe(' al|pha\n beta\ngamma');
+
+ expect(pressTab(editor, textbox, true)).toBe(true);
+ expect(marked(editor)).toBe('al|pha\n beta\ngamma');
+
+ // Nothing left to outdent: the key still stays in the editor.
+ expect(pressTab(editor, textbox, true)).toBe(true);
+ expect(marked(editor)).toBe('al|pha\n beta\ngamma');
+ expect(document.activeElement).toBe(textbox);
+ });
+
+ it('indents and outdents every line a selection touches, keeping the selection on the same characters', async () => {
+ const {editor, textbox} = await renderCode('alpha\n beta\ngamma');
+ select(editor, 'a'.length, 'alpha\n beta\ngam'.length);
+
+ expect(pressTab(editor, textbox)).toBe(true);
+ expect(marked(editor)).toBe(' a[lpha\n beta\n gam]ma');
+
+ expect(pressTab(editor, textbox, true)).toBe(true);
+ expect(marked(editor)).toBe('a[lpha\n beta\ngam]ma');
+ });
+
+ it('keeps a backward selection backward', async () => {
+ const {editor, textbox} = await renderCode('alpha\nbeta');
+ select(editor, 'alpha\nbe'.length, 'al'.length);
+
+ pressTab(editor, textbox);
+ expect(marked(editor)).toBe(' al]pha\n be[ta');
+ });
+
+ it('leaves alone a line the selection only reaches the start of', async () => {
+ const {editor, textbox} = await renderCode('one\ntwo\nthree');
+ select(editor, 0, 'one\n'.length);
+
+ pressTab(editor, textbox);
+ expect(marked(editor)).toBe(' [one\n]two\nthree');
+ });
+
+ it.each([
+ [
+ 'a tab when a line starts with one',
+ '\tx\nyz',
+ '\tx\ny'.length,
+ '\tx\n\ty|z',
+ ],
+ [
+ 'the fewest spaces a line starts with',
+ 'a\n b\n c',
+ 0,
+ ' |a\n b\n c',
+ ],
+ ['two spaces when no line is indented', 'a\nb', 0, ' |a\nb'],
+ ['at least two spaces', ' a', 1, ' |a'],
+ ['at most eight spaces', `${' '.repeat(12)}a`, 12, `${' '.repeat(20)}|a`],
+ ])('indents by the block’s own indent: %s', async (_, code, caret, after) => {
+ const {editor, textbox} = await renderCode(code);
+ select(editor, caret);
+
+ pressTab(editor, textbox);
+ expect(marked(editor)).toBe(after);
+ });
+
+ it('undoes each press on its own', async () => {
+ const {editor, textbox} = await renderCode('alpha\n beta\ngamma');
+ select(editor, 'a'.length, 'alpha\n beta\ngam'.length);
+ pressTab(editor, textbox);
+ pressTab(editor, textbox, true);
+ pressTab(editor, textbox);
+ expect(codeText(editor)).toBe(' alpha\n beta\n gamma');
+
+ act(() => {
+ editor.dispatchCommand(UNDO_COMMAND, undefined);
+ });
+ expect(marked(editor)).toBe('a[lpha\n beta\ngam]ma');
+ });
+
+ it('undoes one press of a tab-indented line on its own, even right after another', async () => {
+ // Each press adds one character before the caret here, the edit that
+ // typing makes, which history would otherwise merge into one step.
+ const {editor, textbox} = await renderCode('\tx\ny');
+ select(editor, '\tx\n'.length);
+ pressTab(editor, textbox);
+ pressTab(editor, textbox);
+ expect(marked(editor)).toBe('\tx\n\t\t|y');
+
+ act(() => {
+ editor.dispatchCommand(UNDO_COMMAND, undefined);
+ });
+ expect(marked(editor)).toBe('\tx\n\t|y');
+ });
+
+ it('keeps typing right after a press of a tab-indented line out of its undo step', async () => {
+ const {editor, textbox} = await renderCode('\tx\ny');
+ select(editor, '\tx\n'.length);
+ pressTab(editor, textbox);
+ act(() => {
+ editor.update(() => {
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) {
+ selection.insertText('r');
+ }
+ });
+ });
+ expect(marked(editor)).toBe('\tx\n\tr|y');
+
+ act(() => {
+ editor.dispatchCommand(UNDO_COMMAND, undefined);
+ });
+ expect(marked(editor)).toBe('\tx\n\t|y');
+ });
+
+ it('still lets Escape then Tab move focus out of the editor', async () => {
+ const user = userEvent.setup();
+ const {editor} = await renderCode('alpha');
+ select(editor, 'al'.length);
+
+ await user.keyboard('{Escape}');
+ await user.tab();
+ // The next stop after the editable text is the block's own Copy code.
+ expect(document.activeElement).toBe(
+ screen.getByRole('button', {name: 'Copy code'}),
+ );
+ expect(codeText(editor)).toBe('alpha');
+ });
+
+ it('keeps Tab’s meaning outside a code block', async () => {
+ const {editor, textbox} = await renderCode('alpha');
+ act(() => {
+ editor.update(() => $getRoot().getFirstChildOrThrow().selectStart(), {
+ discrete: true,
+ });
+ });
+
+ expect(pressTab(editor, textbox)).toBe(true);
+ const introIndent = editor.read(() => {
+ const intro = $getRoot().getFirstChildOrThrow();
+ return $isParagraphNode(intro) ? intro.getIndent() : null;
+ });
+ expect(introIndent).toBe(1);
+ expect(codeText(editor)).toBe('alpha');
+ });
+
+ it('leaves a read-only editor’s Tab as focus movement', async () => {
+ const user = userEvent.setup();
+ const {editor} = await renderCode('alpha', {isReadOnly: true});
+
+ await user.tab();
+ expect(document.activeElement).toBe(
+ screen.getByRole('button', {name: 'Copy code'}),
+ );
+ expect(codeText(editor)).toBe('alpha');
+ });
+});
diff --git a/packages/richtext/src/CodeTabPlugin.tsx b/packages/richtext/src/CodeTabPlugin.tsx
new file mode 100644
index 0000000000..b23fd97fe8
--- /dev/null
+++ b/packages/richtext/src/CodeTabPlugin.tsx
@@ -0,0 +1,298 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file CodeTabPlugin.tsx
+ * @input Uses @lexical/react (composer context), @lexical/code (CodeNode), and
+ * lexical.
+ * @output Exports CodeTabPlugin, which makes Tab and Shift+Tab in a code block
+ * indent and outdent every line the selection touches, by the indent the
+ * block's own lines use.
+ * @position Rendered by RichTextEditor; always on, and not exported from the
+ * package. A press indents by the block's own indent, so edited code keeps
+ * the indentation its author chose; the selection stays on the same
+ * characters, and each press is one undo step. It replaces only what Tab
+ * did in a code block before: TabIndentationPlugin put a tab character in
+ * place of the selection. Its listener sits at the front of the
+ * editor-priority queue, ahead of TabIndentationPlugin and behind every
+ * low-priority listener, so Escape then Tab still moves focus out of the
+ * editor (TabFocusEscapePlugin, WCAG 2.1.2). A selection that reaches
+ * outside the code block keeps TabIndentationPlugin's meaning. Read-only
+ * and disabled editors are unchanged.
+ */
+
+import {useEffect} from 'react';
+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
+import {$isCodeNode, type CodeNode} from '@lexical/code';
+import {
+ $addUpdateTag,
+ $createTextNode,
+ $getSelection,
+ $isRangeSelection,
+ $isTabNode,
+ $isTextNode,
+ COMMAND_PRIORITY_BEFORE_EDITOR,
+ HISTORY_PUSH_TAG,
+ KEY_TAB_COMMAND,
+ type LexicalNode,
+ type PointType,
+ type RangeSelection,
+ type TextNode,
+} from 'lexical';
+
+/** The narrowest space indent a block uses, and the widest. */
+const MIN_SPACE_INDENT = 2;
+const MAX_SPACE_INDENT = 8;
+
+function leadingSpaces(line: string): number {
+ return /^ */.exec(line)?.[0].length ?? 0;
+}
+
+/**
+ * The indent a code block's lines use: a tab when any line starts with one;
+ * otherwise the fewest spaces an indented line starts with, kept between two
+ * and eight; otherwise two spaces.
+ */
+function codeIndentUnit(lines: ReadonlyArray<string>): string {
+ if (lines.some(line => line.startsWith('\t'))) {
+ return '\t';
+ }
+ const widths = lines.map(leadingSpaces).filter(width => width > 0);
+ const width = widths.length === 0 ? MIN_SPACE_INDENT : Math.min(...widths);
+ return ' '.repeat(
+ Math.min(MAX_SPACE_INDENT, Math.max(MIN_SPACE_INDENT, width)),
+ );
+}
+
+/**
+ * A code block's children, the offset in the block's text where each one
+ * starts, and that text. A line ends at a line break node or at a newline
+ * inside a text node: imported code holds newlines, and Enter adds line
+ * break nodes.
+ */
+interface CodeLayout {
+ readonly children: ReadonlyArray<LexicalNode>;
+ readonly starts: ReadonlyArray<number>;
+ readonly text: string;
+}
+
+function $layoutOf(code: CodeNode): CodeLayout {
+ const children = code.getChildren();
+ const starts: number[] = [];
+ let text = '';
+ for (const child of children) {
+ starts.push(text.length);
+ text += child.getTextContent();
+ }
+ return {children, starts, text};
+}
+
+/** A text node that can take a caret and grow: any but a tab node. */
+function $isPlainText(node: LexicalNode): node is TextNode {
+ return $isTextNode(node) && !$isTabNode(node);
+}
+
+/** The code block that holds both ends of the selection, or null. */
+function $selectionCodeBlock(selection: RangeSelection): CodeNode | null {
+ const blockOf = (point: PointType) => {
+ const node = point.getNode();
+ return $isCodeNode(node) ? node : node.getParent();
+ };
+ const block = blockOf(selection.anchor);
+ return $isCodeNode(block) && block.is(blockOf(selection.focus))
+ ? block
+ : null;
+}
+
+/** Where a point of the block's selection falls in the block's text. */
+function $offsetOf(
+ code: CodeNode,
+ layout: CodeLayout,
+ point: PointType,
+): number {
+ if (point.key === code.getKey()) {
+ return point.offset < layout.children.length
+ ? layout.starts[point.offset]
+ : layout.text.length;
+ }
+ const index = layout.children.findIndex(
+ child => child.getKey() === point.key,
+ );
+ return index < 0 ? 0 : layout.starts[index] + point.offset;
+}
+
+/**
+ * Moves a selection point to an offset in the block's text: into the text
+ * node there, or between children where none holds it (beside a tab or a
+ * line break, or on an empty line).
+ */
+function $placePoint(code: CodeNode, point: PointType, offset: number): void {
+ const children = code.getChildren();
+ let start = 0;
+ for (let index = 0; index < children.length; index++) {
+ const child = children[index];
+ const size = child.getTextContentSize();
+ if ($isPlainText(child) && offset >= start && offset <= start + size) {
+ point.set(child.getKey(), offset - start, 'text');
+ return;
+ }
+ if (offset <= start) {
+ point.set(code.getKey(), index, 'element');
+ return;
+ }
+ start += size;
+ }
+ point.set(code.getKey(), children.length, 'element');
+}
+
+/** Inserts text at an offset in the block's text. */
+function $insertAt(code: CodeNode, offset: number, text: string): void {
+ const {children, starts} = $layoutOf(code);
+ for (let index = 0; index < children.length; index++) {
+ const child = children[index];
+ const start = starts[index];
+ if (
+ $isPlainText(child) &&
+ offset >= start &&
+ offset <= start + child.getTextContentSize()
+ ) {
+ const content = child.getTextContent();
+ const at = offset - start;
+ child.setTextContent(content.slice(0, at) + text + content.slice(at));
+ return;
+ }
+ if (offset <= start) {
+ child.insertBefore($createTextNode(text));
+ return;
+ }
+ }
+ code.append($createTextNode(text));
+}
+
+/** Removes `count` characters at an offset in the block's text. */
+function $removeAt(code: CodeNode, offset: number, count: number): void {
+ const {children, starts} = $layoutOf(code);
+ let left = count;
+ for (let index = 0; index < children.length && left > 0; index++) {
+ const child = children[index];
+ const size = child.getTextContentSize();
+ if (!$isTextNode(child) || starts[index] + size <= offset) {
+ continue;
+ }
+ const from = Math.max(0, offset - starts[index]);
+ const removed = Math.min(left, size - from);
+ const content = child.getTextContent();
+ const rest = content.slice(0, from) + content.slice(from + removed);
+ if (rest === '') {
+ child.remove();
+ } else {
+ child.setTextContent(rest);
+ }
+ left -= removed;
+ }
+}
+
+/**
+ * Indents, or outdents, every line the selection touches by the block's own
+ * indent, and puts the selection back on the characters it held.
+ */
+function $shiftLines(
+ code: CodeNode,
+ selection: RangeSelection,
+ isOutdent: boolean,
+): void {
+ const layout = $layoutOf(code);
+ const lines = layout.text.split('\n');
+ const lineStarts: number[] = [];
+ let lineStart = 0;
+ for (const line of lines) {
+ lineStarts.push(lineStart);
+ lineStart += line.length + 1;
+ }
+ const lineAt = (offset: number) => {
+ let line = 0;
+ while (line + 1 < lineStarts.length && lineStarts[line + 1] <= offset) {
+ line++;
+ }
+ return line;
+ };
+ const unit = codeIndentUnit(lines);
+ // A tab-indented block outdents a space-indented line by the narrowest
+ // space indent.
+ const spaceUnit = unit === '\t' ? MIN_SPACE_INDENT : unit.length;
+ const anchor = $offsetOf(code, layout, selection.anchor);
+ const focus = $offsetOf(code, layout, selection.focus);
+ const start = Math.min(anchor, focus);
+ const end = Math.max(anchor, focus);
+ const first = lineAt(start);
+ let last = lineAt(end);
+ // A selection that ends where a line begins does not reach into that line.
+ if (last > first && lineStarts[last] === end) {
+ last--;
+ }
+ // Each edit as [offset, characters added (negative when removed)], made
+ // from the last line up so the offsets of the lines above stay true.
+ const edits: Array<readonly [number, number]> = [];
+ for (let line = last; line >= first; line--) {
+ const at = lineStarts[line];
+ if (!isOutdent) {
+ $insertAt(code, at, unit);
+ edits.push([at, unit.length]);
+ continue;
+ }
+ const removed = lines[line].startsWith('\t')
+ ? 1
+ : Math.min(leadingSpaces(lines[line]), spaceUnit);
+ if (removed > 0) {
+ $removeAt(code, at, removed);
+ edits.push([at, -removed]);
+ }
+ }
+ // A point keeps its character: text added at or before it pushes it on,
+ // and a point inside removed indentation moves to its line's start.
+ const shifted = (offset: number) =>
+ edits.reduce((moved, [at, delta]) => {
+ if (delta > 0) {
+ return offset >= at ? moved + delta : moved;
+ }
+ return offset > at ? moved - Math.min(-delta, offset - at) : moved;
+ }, offset);
+ $placePoint(code, selection.anchor, shifted(anchor));
+ $placePoint(code, selection.focus, shifted(focus));
+}
+
+export function CodeTabPlugin(): null {
+ const [editor] = useLexicalComposerContext();
+ useEffect(
+ () =>
+ editor.registerCommand(
+ KEY_TAB_COMMAND,
+ event => {
+ const selection = $getSelection();
+ if (!editor.isEditable() || !$isRangeSelection(selection)) {
+ return false;
+ }
+ const code = $selectionCodeBlock(selection);
+ if (code == null) {
+ return false;
+ }
+ event.preventDefault();
+ // One undo step per press, even when a press adds or removes a
+ // single character beside the caret. The push tag starts a step
+ // before the press. A dirty block makes history class the press
+ // as its own change, so typing after it starts another step.
+ $addUpdateTag(HISTORY_PUSH_TAG);
+ $shiftLines(code, selection, event.shiftKey);
+ code.markDirty();
+ return true;
+ },
+ // After TabFocusEscapePlugin's low-priority listener, which lets an
+ // armed Tab move focus, and before TabIndentationPlugin's; see the
+ // file header.
+ COMMAND_PRIORITY_BEFORE_EDITOR,
+ ),
+ [editor],
+ );
+ return null;
+}
diff --git a/packages/richtext/src/RichTextEditor.doc.mjs b/packages/richtext/src/RichTextEditor.doc.mjs
index e2d7705271..37623b9f42 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:
+ 'In a code block, Tab and Shift+Tab indent and outdent every line the selection touches, by the indent the block already uses: a tab when one of its lines starts with a tab, otherwise the fewest spaces an indented line starts with (2 to 8), otherwise 2 spaces. The selection stays on the same characters, and each press is one undo step. Escape then Tab still moves focus out of the editor.',
+ },
{
guidance: true,
description:
diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsx
index 1cec7a5dc8..d48bb630d5 100644
--- a/packages/richtext/src/RichTextEditor.tsx
+++ b/packages/richtext/src/RichTextEditor.tsx
@@ -81,6 +81,7 @@ import {CodeBackspacePlugin} from './CodeBackspacePlugin';
import {CodeBlockHeaderPlugin} from './CodeBlockHeaderPlugin';
import {CodePastePlugin} from './CodePastePlugin';
import {CodeSyntaxPlugin} from './CodeSyntaxPlugin';
+import {CodeTabPlugin} from './CodeTabPlugin';
import {MarkdownExtensionsPlugin} from './MarkdownExtensionsPlugin';
import type {RichTextMarkdownExtension} from './markdownExtensions';
import type {CodeLanguage} from '@astryxdesign/core/CodeBlock';
@@ -741,6 +742,9 @@ export const RichTextEditor = function RichTextEditor({
transformers={markdownTransformers}
/>
) : null}
+ {/* In a code block, Tab indents the lines the selection
+ touches instead of inserting a tab character. */}
+ <CodeTabPlugin />
<TabIndentationPlugin />
<TabFocusEscapePlugin />
<SelectAllScopePlugin />
@@ -835,7 +839,8 @@ const ESCAPE_REARM_EXEMPT_KEYS = new Set([
* listeners from the highest priority down, stopping at the first one that
* returns true. Registering at COMMAND_PRIORITY_LOW (1) therefore runs first;
* when the escape is armed we return true WITHOUT calling
- * `event.preventDefault()`, so the indentation handler never sees the event
+ * `event.preventDefault()`, so the indentation handlers (TabIndentationPlugin,
+ * and CodeTabPlugin at the front of the same priority) never see the event
* and the browser performs its default Tab focus navigation.
*/
function TabFocusEscapePlugin(): null {