Skip to content

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

TypeScript

fix(lab): RichTextEditor Tab keyboard trap — Escape then Tab moves focus (#4380)

Baraa Hamodi381694fe77fc
diff --git a/apps/sandbox/next.config.mjs b/apps/sandbox/next.config.mjs
index eb21184a40..c475b31bf9 100644
--- a/apps/sandbox/next.config.mjs
+++ b/apps/sandbox/next.config.mjs
@@ -1,7 +1,30 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+import {createRequire} from 'node:module';
+import path from 'node:path';
+
import {withAstryx} from '@astryxdesign/build/next';
+const require = createRequire(import.meta.url);
+
+/**
+ * Locate lexical's built ESM entry for the alias below. `require.resolve`
+ * lands on the CJS entry inside dist/, so walk up to the package root rather
+ * than resolving `lexical/package.json` (not export-mapped). Returns null when
+ * lexical isn't installed so the alias is simply omitted.
+ */
+function resolveLexicalDist() {
+ try {
+ let dir = path.dirname(require.resolve('lexical'));
+ while (path.basename(dir) !== 'lexical') {
+ dir = path.dirname(dir);
+ }
+ return path.join(dir, 'dist', 'Lexical.mjs');
+ } catch {
+ return null;
+ }
+}
+
/** @type {import('next').NextConfig} */
const nextConfig = {
output: process.env.NODE_ENV === 'production' ? 'export' : undefined,
@@ -18,6 +41,28 @@ const nextConfig = {
ignoreBuildErrors: false,
},
webpack(config, {dev}) {
+ // withAstryx resolves requests issued FROM @astryxdesign modules with the
+ // `source` condition so astryx packages build from TS source. lexical also
+ // ships a `source` export, so lab's bare runtime `import ... from
+ // 'lexical'` (RichTextEditor keyboard commands) would resolve to lexical's
+ // raw TS — whose `declare` class fields this app's Babel pipeline rejects.
+ // Pin bare `lexical` to its built ESM entry (an env-switching wrapper, so
+ // dev/prod selection is preserved). App-local on purpose: lab is a private
+ // package, so no external withAstryx consumer can hit this — the shared
+ // build package stays agnostic to non-core libraries.
+ // Scoped by issuer (same shape as withAstryx's source-condition rule) so
+ // only astryx-issued requests are pinned — everything else keeps normal
+ // export-map resolution (e.g. Lexical.node.mjs in the server bundle).
+ const lexicalDist = resolveLexicalDist();
+ if (lexicalDist != null) {
+ config.module = config.module || {};
+ config.module.rules = config.module.rules || [];
+ config.module.rules.unshift({
+ test: /[\\/]node_modules[\\/]@astryxdesign[\\/]/,
+ resolve: {alias: {lexical$: lexicalDist}},
+ });
+ }
+
// Workarounds for Node v24+ where webpack's hashing/caching feeds
// `undefined` to Hash.update and crashes the dev server.
config.output = config.output || {};
diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs b/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs
index 7593e67290..0fa441f0dc 100644
--- a/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs
+++ b/packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs
@@ -109,6 +109,13 @@ export const docs = {
description: 'Automatically focus the editor on mount.',
default: 'false',
},
+ {
+ name: 'tabEscapeHint',
+ type: 'string',
+ description:
+ 'Screen-reader hint describing how to move focus out of the editor, since Tab is bound to indentation (press Escape, then Tab). Visually hidden, wired via aria-describedby. Override to localize; pass "" to omit.',
+ default: "'Press Escape then Tab to move focus out of the editor.'",
+ },
{
name: 'maxLength',
type: 'number',
diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx
index e1bce516b3..c8778c8a5b 100644
--- a/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx
+++ b/packages/lab/src/RichTextEditor/RichTextEditor.test.tsx
@@ -9,11 +9,17 @@
* SYNC: When the editor components change, update these tests to match.
*/
-import {describe, it, expect, vi} from 'vitest';
+import {describe, it, expect, vi, beforeAll} from 'vitest';
import {render, screen, waitFor, fireEvent} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import {createRef, useEffect} from 'react';
import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
import type {EditorState, LexicalEditor} from 'lexical';
+import {
+ $createListItemNode,
+ $createListNode,
+ $isListItemNode,
+} from '@lexical/list';
import {
$getRoot,
$createParagraphNode,
@@ -606,6 +612,138 @@ describe('RichTextEditor', () => {
});
});
+describe('RichTextEditor Tab keyboard trap escape (WCAG 2.1.2)', () => {
+ const DEFAULT_HINT = 'Press Escape then Tab to move focus out of the editor.';
+
+ beforeAll(() => {
+ // jsdom's Range does not implement getBoundingClientRect, which Lexical
+ // calls (via scroll-into-view) whenever it reconciles a collapsed
+ // selection while the editor is focused. Stub it so the focused-editor
+ // keyboard tests below can run without uncaught exceptions.
+ if (typeof Range.prototype.getBoundingClientRect !== 'function') {
+ Range.prototype.getBoundingClientRect = () => new DOMRect();
+ }
+ });
+
+ /**
+ * Renders the editor followed by a button, focuses the contenteditable and
+ * seeds a single-item bullet list with the caret at the start of the item —
+ * the position where TabIndentationPlugin turns Tab into an indent (and
+ * calls preventDefault, which is the keyboard trap under test).
+ */
+ async function setUpListEditor() {
+ let editorRef: LexicalEditor | undefined;
+ function CaptureEditor() {
+ const [editor] = useLexicalComposerContext();
+ useEffect(() => {
+ editorRef = editor;
+ }, [editor]);
+ return null;
+ }
+ render(
+ <>
+ <RichTextEditor label="Notes" plugins={<CaptureEditor />} />
+ <button type="button">after</button>
+ </>,
+ );
+ await waitFor(() => expect(editorRef).toBeDefined());
+ const textbox = screen.getByRole('textbox');
+ textbox.focus();
+ editorRef!.update(() => {
+ const root = $getRoot();
+ root.clear();
+ const list = $createListNode('bullet');
+ const item = $createListItemNode();
+ const text = $createTextNode('Item one');
+ item.append(text);
+ list.append(item);
+ root.append(list);
+ text.select(0, 0);
+ });
+ return {editor: editorRef!, textbox};
+ }
+
+ /** Indent of the list item containing the seeded text node. */
+ function getItemIndent(editor: LexicalEditor): number {
+ return editor.getEditorState().read(() => {
+ const text = $getRoot().getAllTextNodes()[0];
+ const item = text.getParent();
+ return $isListItemNode(item) ? item.getIndent() : -1;
+ });
+ }
+
+ it('indents the list item on Tab and keeps focus in the editor', async () => {
+ const user = userEvent.setup();
+ const {editor, textbox} = await setUpListEditor();
+ expect(getItemIndent(editor)).toBe(0);
+ await user.tab();
+ expect(getItemIndent(editor)).toBe(1);
+ // The keydown was consumed by indentation, so focus did not move.
+ expect(document.activeElement).toBe(textbox);
+ });
+
+ it('moves focus out (without indenting) on Tab after Escape', async () => {
+ const user = userEvent.setup();
+ const {editor, textbox} = await setUpListEditor();
+ await user.keyboard('{Escape}');
+ await user.tab();
+ expect(document.activeElement).not.toBe(textbox);
+ expect(document.activeElement).toBe(
+ screen.getByRole('button', {name: 'after'}),
+ );
+ expect(getItemIndent(editor)).toBe(0);
+ });
+
+ it('re-arms indentation when another key is pressed after Escape', async () => {
+ const user = userEvent.setup();
+ const {editor, textbox} = await setUpListEditor();
+ await user.keyboard('{Escape}');
+ // Any non-modifier key press (typing, arrows, …) cancels the escape.
+ fireEvent.keyDown(textbox, {key: 'a'});
+ await user.tab();
+ expect(document.activeElement).toBe(textbox);
+ expect(getItemIndent(editor)).toBe(1);
+ });
+
+ it('does not re-arm on a bare modifier, so Escape then Shift+Tab escapes', async () => {
+ const user = userEvent.setup();
+ const {textbox} = await setUpListEditor();
+ await user.keyboard('{Escape}');
+ // Pressing Shift on its own (the first half of Shift+Tab) must not
+ // cancel the escape. fireEvent returns false when preventDefault was
+ // called — an unprevented Tab keydown means native focus movement.
+ fireEvent.keyDown(textbox, {key: 'Shift'});
+ expect(fireEvent.keyDown(textbox, {key: 'Tab', shiftKey: true})).toBe(true);
+ });
+
+ it('advertises the escape via a visually hidden aria-describedby hint', () => {
+ render(<RichTextEditor label="Notes" />);
+ const textbox = screen.getByRole('textbox');
+ const hint = screen.getByText(DEFAULT_HINT);
+ expect(hint.id).not.toBe('');
+ expect(
+ (textbox.getAttribute('aria-describedby') ?? '').split(/\s+/),
+ ).toContain(hint.id);
+ });
+
+ it('supports overriding and suppressing the hint text', () => {
+ const {unmount} = render(
+ <RichTextEditor label="Notes" tabEscapeHint="Custom escape hint" />,
+ );
+ expect(screen.getByText('Custom escape hint')).toBeInTheDocument();
+ expect(screen.queryByText(DEFAULT_HINT)).not.toBeInTheDocument();
+ unmount();
+ render(<RichTextEditor label="Notes" tabEscapeHint="" />);
+ expect(screen.queryByText(DEFAULT_HINT)).not.toBeInTheDocument();
+ expect(screen.getByRole('textbox')).not.toHaveAttribute('aria-describedby');
+ });
+
+ it('omits the hint when the editor is not editable', () => {
+ render(<RichTextEditor label="Notes" isReadOnly />);
+ expect(screen.queryByText(DEFAULT_HINT)).not.toBeInTheDocument();
+ });
+});
+
describe('RichTextView', () => {
it('renders serialized content read-only', async () => {
render(<RichTextView value={HELLO_STATE} />);
diff --git a/packages/lab/src/RichTextEditor/RichTextEditor.tsx b/packages/lab/src/RichTextEditor/RichTextEditor.tsx
index e3c97dbb6c..f82040ad1f 100644
--- a/packages/lab/src/RichTextEditor/RichTextEditor.tsx
+++ b/packages/lab/src/RichTextEditor/RichTextEditor.tsx
@@ -4,7 +4,8 @@
/**
* @file RichTextEditor.tsx
- * @input Uses React, useId, Lexical (lexical + @lexical/react), Field, design tokens
+ * @input Uses React, useId, Lexical (lexical + @lexical/react), Field,
+ * VisuallyHidden, design tokens
* @output Exports RichTextEditor component, RichTextEditorProps, RichTextEditorStatus,
* RichTextEditorStatusType, RichTextEditorSize
* @position Experimental (lab) implementation; consumed by RichTextEditor/index.ts and
@@ -78,12 +79,18 @@ import {
export type {Transformer} from '@lexical/markdown';
import {$generateHtmlFromNodes} from '@lexical/html';
import {DEFAULT_NODES} from './editorNodes';
-import type {
- EditorState,
- Klass,
- LexicalEditor,
- LexicalNode,
- EditorThemeClasses,
+import {
+ BLUR_COMMAND,
+ COMMAND_PRIORITY_LOW,
+ KEY_DOWN_COMMAND,
+ KEY_ESCAPE_COMMAND,
+ KEY_TAB_COMMAND,
+ mergeRegister,
+ type EditorState,
+ type Klass,
+ type LexicalEditor,
+ type LexicalNode,
+ type EditorThemeClasses,
} from 'lexical';
/**
@@ -182,6 +189,13 @@ const sizeStyles = stylex.create({
},
});
+/**
+ * Default screen-reader hint advertising the Tab escape. Overridable (or
+ * suppressible) via the `tabEscapeHint` prop for localization.
+ */
+const DEFAULT_TAB_ESCAPE_HINT =
+ 'Press Escape then Tab to move focus out of the editor.';
+
/**
* Fraction of `maxLength` at which the character counter begins announcing
* remaining/over-limit characters to screen readers. Matches TextArea.
@@ -339,6 +353,15 @@ export interface RichTextEditorProps extends Omit<
transformers?: ReadonlyArray<Transformer>;
/** Whether to automatically focus the editor on mount. @default false */
hasAutoFocus?: boolean;
+ /**
+ * Screen-reader hint describing how to move focus out of the editor, since
+ * Tab is bound to indentation (press Escape, then Tab). Rendered visually
+ * hidden and referenced from the editor's `aria-describedby`. Override it
+ * to localize the text, or pass an empty string to omit the hint entirely
+ * (e.g. when the host app provides its own instructions).
+ * @default 'Press Escape then Tab to move focus out of the editor.'
+ */
+ tabEscapeHint?: string;
/**
* Maximum number of characters. When set, a character counter
* (current/max) is displayed below the editor. Like TextArea, this does
@@ -403,6 +426,7 @@ export const RichTextEditor = forwardRef<
hasMarkdownShortcuts = true,
transformers = TRANSFORMERS,
hasAutoFocus = false,
+ tabEscapeHint = DEFAULT_TAB_ESCAPE_HINT,
maxLength,
namespace = 'astryx-editor',
xstyle,
@@ -418,6 +442,7 @@ export const RichTextEditor = forwardRef<
const statusMessageID = useId();
const placeholderID = useId();
const counterID = useId();
+ const tabEscapeHintID = useId();
// Plain-text character count, tracked from inside the composer via
// CharCountPlugin. Only used when maxLength is set.
@@ -449,12 +474,15 @@ export const RichTextEditor = forwardRef<
},
};
+ const hasTabEscapeHint = editable && tabEscapeHint !== '';
+
const ariaDescribedBy =
[
description ? descriptionID : null,
status?.message ? statusMessageID : null,
placeholder ? placeholderID : null,
maxLength != null ? counterID : null,
+ hasTabEscapeHint ? tabEscapeHintID : null,
]
.filter(Boolean)
.join(' ') || undefined;
@@ -520,6 +548,7 @@ export const RichTextEditor = forwardRef<
<ListPlugin />
<LinkPlugin />
<TabIndentationPlugin />
+ <TabFocusEscapePlugin />
{hasMarkdownShortcuts && (
<MarkdownShortcutPlugin transformers={markdownTransformers} />
)}
@@ -542,6 +571,9 @@ export const RichTextEditor = forwardRef<
)}
</div>
</LexicalComposer>
+ {hasTabEscapeHint && (
+ <VisuallyHidden id={tabEscapeHintID}>{tabEscapeHint}</VisuallyHidden>
+ )}
</div>
{maxLength != null && (
<div
@@ -566,6 +598,93 @@ export const RichTextEditor = forwardRef<
RichTextEditor.displayName = 'RichTextEditor';
+/**
+ * Keys that must not cancel an armed Tab escape: Escape (arming again),
+ * Tab (the escape itself) and bare modifier presses — the Shift keydown that
+ * precedes Shift+Tab must not disarm, or Escape → Shift+Tab could never
+ * escape backwards.
+ */
+const ESCAPE_REARM_EXEMPT_KEYS = new Set([
+ 'Escape',
+ 'Tab',
+ 'Shift',
+ 'Control',
+ 'Alt',
+ 'Meta',
+]);
+
+/**
+ * WCAG 2.1.2 (No Keyboard Trap) escape for TabIndentationPlugin.
+ *
+ * TabIndentationPlugin rebinds Tab to indent/outdent, which would otherwise
+ * trap keyboard focus inside the editor. This plugin restores an exit: after
+ * Escape is pressed, the next Tab (or Shift+Tab) performs native focus
+ * movement instead of indenting; pressing any other non-modifier key — or
+ * leaving the editor — re-arms indentation.
+ *
+ * Mechanics: TabIndentationPlugin handles KEY_TAB_COMMAND at
+ * COMMAND_PRIORITY_EDITOR (0), the lowest priority, and Lexical runs command
+ * 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
+ * and the browser performs its default Tab focus navigation.
+ */
+function TabFocusEscapePlugin(): null {
+ const [editor] = useLexicalComposerContext();
+ useEffect(() => {
+ let escapeArmed = false;
+ return mergeRegister(
+ editor.registerCommand<KeyboardEvent>(
+ KEY_ESCAPE_COMMAND,
+ () => {
+ escapeArmed = true;
+ // Consumed: this supersedes @lexical/rich-text's default Escape
+ // handler (COMMAND_PRIORITY_EDITOR), which blurs the editor and
+ // drops focus on the document body — disorienting, and it would
+ // immediately disarm via BLUR_COMMAND below. Consumer plugins that
+ // handle Escape (e.g. to close a popover) register at a higher
+ // priority and still run first.
+ return true;
+ },
+ COMMAND_PRIORITY_LOW,
+ ),
+ editor.registerCommand<KeyboardEvent>(
+ KEY_TAB_COMMAND,
+ () => {
+ if (!escapeArmed) {
+ return false;
+ }
+ escapeArmed = false;
+ // Consume the command (blocks indentation) but leave the event's
+ // default alone so focus moves natively.
+ return true;
+ },
+ COMMAND_PRIORITY_LOW,
+ ),
+ editor.registerCommand<KeyboardEvent>(
+ KEY_DOWN_COMMAND,
+ event => {
+ if (escapeArmed && !ESCAPE_REARM_EXEMPT_KEYS.has(event.key)) {
+ escapeArmed = false;
+ }
+ return false;
+ },
+ COMMAND_PRIORITY_LOW,
+ ),
+ editor.registerCommand(
+ BLUR_COMMAND,
+ () => {
+ escapeArmed = false;
+ return false;
+ },
+ COMMAND_PRIORITY_LOW,
+ ),
+ );
+ }, [editor]);
+ return null;
+}
+
/**
* Focuses the editor on mount. Split into its own plugin so it runs inside the
* composer context.