Skip to content

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

TypeScript

fix(lab): CodeEditor Tab keyboard trap — Escape then Tab moves focus (#4379)

Baraa Hamodi2901b1d28044
diff --git a/packages/lab/src/CodeEditor/CodeEditor.test.tsx b/packages/lab/src/CodeEditor/CodeEditor.test.tsx
index 20a04575ee..5423798c0e 100644
--- a/packages/lab/src/CodeEditor/CodeEditor.test.tsx
+++ b/packages/lab/src/CodeEditor/CodeEditor.test.tsx
@@ -1,9 +1,55 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import {describe, it, expect} from 'vitest';
-import {render, screen} from '@testing-library/react';
+/**
+ * @file CodeEditor.test.tsx
+ * @input Uses vitest, @testing-library/react, @testing-library/user-event, CodeEditor
+ * @output Unit tests for CodeEditor accessibility and keyboard behavior
+ * @position Testing; validates CodeEditor.tsx implementation
+ *
+ * SYNC: When CodeEditor.tsx changes, update tests to match new behavior
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {render, screen, fireEvent} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import {CodeEditor} from './CodeEditor';
+/** Place a collapsed caret at a character offset inside the editor. */
+function setCaret(el: HTMLElement, offset: number) {
+ const sel = window.getSelection();
+ const range = document.createRange();
+ const node = el.firstChild;
+ if (node && node.nodeType === Node.TEXT_NODE) {
+ range.setStart(node, offset);
+ } else {
+ range.setStart(el, 0);
+ }
+ range.collapse(true);
+ sel?.removeAllRanges();
+ sel?.addRange(range);
+}
+
+function renderEditor(value = '', props: {escapeHint?: string} = {}) {
+ const onChange = vi.fn();
+ render(
+ <div>
+ <button>before</button>
+ <CodeEditor
+ value={value}
+ onChange={onChange}
+ language="typescript"
+ label="Edit snippet"
+ {...props}
+ />
+ <button>after</button>
+ </div>,
+ );
+ const editor = screen.getByRole('textbox', {name: 'Edit snippet'});
+ editor.focus();
+ setCaret(editor, value.length);
+ return {editor, onChange};
+}
+
describe('CodeEditor', () => {
it('uses the label prop as the accessible name', () => {
render(
@@ -18,4 +64,128 @@ describe('CodeEditor', () => {
screen.getByRole('textbox', {name: 'Edit snippet'}),
).toBeInTheDocument();
});
+
+ it('advertises the Escape-then-Tab escape via aria-describedby', () => {
+ const {editor} = renderEditor();
+ const hintId = editor.getAttribute('aria-describedby');
+ expect(hintId).toBeTruthy();
+ const hint = document.getElementById(hintId as string);
+ expect(hint).toHaveTextContent(
+ 'Press Escape then Tab to move focus out of the editor.',
+ );
+ });
+
+ it('supports overriding the escape hint text', () => {
+ const {editor} = renderEditor('', {escapeHint: 'Échap puis Tab'});
+ const hintId = editor.getAttribute('aria-describedby');
+ const hint = document.getElementById(hintId as string);
+ expect(hint).toHaveTextContent('Échap puis Tab');
+ });
+
+ it('Tab inserts two spaces by default and keeps focus in the editor', async () => {
+ const user = userEvent.setup();
+ const {editor, onChange} = renderEditor();
+
+ await user.keyboard('{Tab}');
+
+ expect(onChange).toHaveBeenCalledWith(' ');
+ expect(document.activeElement).toBe(editor);
+ });
+
+ it('Escape then Tab moves focus out of the editor without indenting', async () => {
+ const user = userEvent.setup();
+ const {editor, onChange} = renderEditor();
+
+ await user.keyboard('{Escape}{Tab}');
+
+ expect(document.activeElement).not.toBe(editor);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('Escape then Shift+Tab lets the browser move focus backward', async () => {
+ // user-event cannot compute a backward tab destination from a
+ // contenteditable element in jsdom, so assert on the preventDefault
+ // contract: an unprevented Shift+Tab keydown means the browser performs
+ // its native backward focus move.
+ const user = userEvent.setup();
+ const {editor, onChange} = renderEditor();
+
+ await user.keyboard('{Escape}');
+ fireEvent.keyDown(editor, {key: 'Shift'});
+ const notPrevented = fireEvent.keyDown(editor, {
+ key: 'Tab',
+ shiftKey: true,
+ });
+
+ expect(notPrevented).toBe(true);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('tab-moves-focus mode is one-shot: the following Tab indents again', async () => {
+ const user = userEvent.setup();
+ const {editor, onChange} = renderEditor();
+
+ await user.keyboard('{Escape}{Tab}');
+ expect(document.activeElement).not.toBe(editor);
+
+ editor.focus();
+ setCaret(editor, 0);
+ await user.keyboard('{Tab}');
+
+ expect(onChange).toHaveBeenCalledWith(' ');
+ expect(document.activeElement).toBe(editor);
+ });
+
+ it('typing after Escape re-arms Tab indentation', async () => {
+ const user = userEvent.setup();
+ const {editor, onChange} = renderEditor();
+
+ await user.keyboard('{Escape}');
+ // Any non-modifier key re-arms indentation mode.
+ fireEvent.keyDown(editor, {key: 'a'});
+ await user.keyboard('{Tab}');
+
+ expect(document.activeElement).toBe(editor);
+ expect(onChange).toHaveBeenCalledWith(' ');
+ });
+
+ it('Shift+Tab outdents the current line in normal mode', async () => {
+ const user = userEvent.setup();
+ const {editor, onChange} = renderEditor(' const x = 1;');
+
+ await user.keyboard('{Shift>}{Tab}{/Shift}');
+
+ expect(onChange).toHaveBeenCalledWith('const x = 1;');
+ expect(document.activeElement).toBe(editor);
+ });
+
+ it('Shift+Tab removes a single leading space when only one exists', async () => {
+ const user = userEvent.setup();
+ const {onChange} = renderEditor(' const x = 1;');
+
+ await user.keyboard('{Shift>}{Tab}{/Shift}');
+
+ expect(onChange).toHaveBeenCalledWith('const x = 1;');
+ });
+
+ it('Shift+Tab on an unindented line changes nothing and keeps focus', async () => {
+ const user = userEvent.setup();
+ const {editor, onChange} = renderEditor('const x = 1;');
+
+ await user.keyboard('{Shift>}{Tab}{/Shift}');
+
+ expect(onChange).not.toHaveBeenCalled();
+ expect(document.activeElement).toBe(editor);
+ });
+
+ it('Shift+Tab outdents only the current line in multi-line code', async () => {
+ const user = userEvent.setup();
+ const {editor, onChange} = renderEditor(' a;\n b;');
+ // Caret on the second line (offset 7 = inside " b;").
+ setCaret(editor, 7);
+
+ await user.keyboard('{Shift>}{Tab}{/Shift}');
+
+ expect(onChange).toHaveBeenCalledWith(' a;\nb;');
+ });
});
diff --git a/packages/lab/src/CodeEditor/CodeEditor.tsx b/packages/lab/src/CodeEditor/CodeEditor.tsx
index 5bdad77a89..bf37eb7fe0 100644
--- a/packages/lab/src/CodeEditor/CodeEditor.tsx
+++ b/packages/lab/src/CodeEditor/CodeEditor.tsx
@@ -2,7 +2,8 @@
/**
* @file CodeEditor.tsx
- * @input Uses React, StyleX, theme tokens, CSS Custom Highlight API
+ * @input Uses React, StyleX, theme tokens, CSS Custom Highlight API,
+ * VisuallyHidden (core)
* @output Exports CodeEditor component and CodeEditorProps
* @position Core implementation; editable code input (lab/experimental)
*
@@ -14,8 +15,16 @@
'use client';
-import {useEffect, useLayoutEffect, useRef, useCallback, useState} from 'react';
+import {
+ useEffect,
+ useId,
+ useLayoutEffect,
+ useRef,
+ useCallback,
+ useState,
+} from 'react';
import type {BaseProps} from '@astryxdesign/core';
+import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';
import * as stylex from '@stylexjs/stylex';
import {
colorVars,
@@ -145,6 +154,13 @@ export interface CodeEditorProps extends Omit<
size?: 'sm' | 'md';
/** Custom tokenizer */
tokenizer?: (code: string, language: string) => TokenLine[];
+ /**
+ * Hint exposed to assistive technology (via aria-describedby) explaining
+ * how to move focus out of the editor. English default — the lab package
+ * has no i18n catalog yet, so override this prop to localize.
+ * @default 'Press Escape then Tab to move focus out of the editor.'
+ */
+ escapeHint?: string;
}
// ---------------------------------------------------------------------------
@@ -168,6 +184,47 @@ const AUTO_CLOSE_PAIRS: Record<string, string> = {
'`': '`',
};
+/**
+ * Modifier keys that must NOT re-arm Tab indentation after Escape has armed
+ * "tab moves focus" mode — otherwise the Shift keydown that precedes
+ * Shift+Tab would cancel the mode before Tab arrives.
+ */
+const MODE_NEUTRAL_KEYS = new Set([
+ 'Shift',
+ 'Control',
+ 'Alt',
+ 'Meta',
+ 'CapsLock',
+]);
+
+/** Place a collapsed caret at a character offset within an element's text. */
+function setCaretAtTextOffset(el: HTMLElement, offset: number): void {
+ const sel = window.getSelection();
+ if (!sel) {
+ return;
+ }
+ const range = document.createRange();
+ let remaining = offset;
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+ let node = walker.nextNode();
+ while (node) {
+ const length = node.textContent?.length ?? 0;
+ if (remaining <= length) {
+ range.setStart(node, remaining);
+ range.collapse(true);
+ sel.removeAllRanges();
+ sel.addRange(range);
+ return;
+ }
+ remaining -= length;
+ node = walker.nextNode();
+ }
+ range.selectNodeContents(el);
+ range.collapse(false);
+ sel.removeAllRanges();
+ sel.addRange(range);
+}
+
let editorInstanceCounter = 0;
// ---------------------------------------------------------------------------
@@ -178,7 +235,12 @@ let editorInstanceCounter = 0;
* An editable code input using contentEditable="plaintext-only".
*
* Uses CSS Custom Highlight API for syntax coloring. Supports
- * auto-indent, tab insertion, and bracket auto-closing.
+ * auto-indent, tab insertion, Shift+Tab outdent, and bracket auto-closing.
+ *
+ * Because Tab is captured for indentation, pressing Escape arms a one-shot
+ * "tab moves focus" mode so keyboard users can leave the editor (WCAG 2.1.2).
+ * The escape is advertised to assistive technology via a visually hidden
+ * aria-describedby hint (see `escapeHint`).
*
* @example
* ```
@@ -203,6 +265,7 @@ export function CodeEditor({
size = 'md',
tokenizer: customTokenizer,
label,
+ escapeHint = 'Press Escape then Tab to move focus out of the editor.',
xstyle,
className,
style,
@@ -213,6 +276,10 @@ export function CodeEditor({
const [instanceId] = useState(() => ++editorInstanceCounter);
const [focused, setFocused] = useState(false);
const isComposingRef = useRef(false);
+ // One-shot "tab moves focus" mode, armed by Escape (WCAG 2.1.2 — the
+ // standard escape from a code editor's Tab-to-indent keyboard trap).
+ const tabMovesFocusRef = useRef(false);
+ const hintId = useId();
const lines = value.split('\n');
@@ -306,13 +373,68 @@ export function CodeEditor({
return;
}
- // Tab key: insert 2 spaces
+ // Escape arms one-shot "tab moves focus" mode so keyboard users can
+ // leave the editor. Only engage when nothing inside the editor (e.g.
+ // an embedded popover/autocomplete) already consumed the Escape.
+ if (e.key === 'Escape') {
+ if (!e.defaultPrevented) {
+ tabMovesFocusRef.current = true;
+ }
+ return;
+ }
+
if (e.key === 'Tab') {
+ // Tab-moves-focus mode: let the browser handle Tab / Shift+Tab
+ // natively so focus leaves the editor. One-shot — disarm.
+ if (tabMovesFocusRef.current) {
+ tabMovesFocusRef.current = false;
+ return;
+ }
+
e.preventDefault();
const sel = window.getSelection();
if (!sel || sel.rangeCount === 0) {
return;
}
+ const el = editorRef.current;
+ if (!el) {
+ return;
+ }
+
+ // Shift+Tab: outdent — remove up to two leading spaces on the
+ // current line.
+ if (e.shiftKey) {
+ const range = sel.getRangeAt(0);
+ const preCaretRange = range.cloneRange();
+ preCaretRange.selectNodeContents(el);
+ preCaretRange.setEnd(range.startContainer, range.startOffset);
+ const cursorOffset = preCaretRange.toString().length;
+
+ const fullText = el.textContent ?? '';
+ const lineStart = fullText.lastIndexOf('\n', cursorOffset - 1) + 1;
+ const line = fullText.slice(lineStart);
+ const removeCount = line.startsWith(' ')
+ ? 2
+ : line.startsWith(' ')
+ ? 1
+ : 0;
+ if (removeCount === 0) {
+ return;
+ }
+ const newText =
+ fullText.slice(0, lineStart) +
+ fullText.slice(lineStart + removeCount);
+ el.textContent = newText;
+ const removedBeforeCursor = Math.min(
+ removeCount,
+ Math.max(0, cursorOffset - lineStart),
+ );
+ setCaretAtTextOffset(el, cursorOffset - removedBeforeCursor);
+ onChange(newText);
+ return;
+ }
+
+ // Tab: insert 2 spaces
const range = sel.getRangeAt(0);
range.deleteContents();
const textNode = document.createTextNode(' ');
@@ -321,13 +443,17 @@ export function CodeEditor({
range.setEndAfter(textNode);
sel.removeAllRanges();
sel.addRange(range);
- const el = editorRef.current;
- if (el) {
- onChange(el.textContent ?? '');
- }
+ onChange(el.textContent ?? '');
return;
}
+ // Any other non-modifier key re-arms Tab indentation. Modifiers are
+ // excluded so Escape → Shift+Tab still moves focus backward (the
+ // Shift keydown fires before the Tab keydown).
+ if (!MODE_NEUTRAL_KEYS.has(e.key)) {
+ tabMovesFocusRef.current = false;
+ }
+
// Enter key: preserve indentation
if (e.key === 'Enter') {
e.preventDefault();
@@ -453,15 +579,22 @@ export function CodeEditor({
aria-multiline="true"
aria-label={label}
aria-readonly={isReadOnly}
+ aria-describedby={isReadOnly ? undefined : hintId}
spellCheck={false}
onInput={handleInput}
onKeyDown={handleKeyDown}
onFocus={() => setFocused(true)}
- onBlur={() => setFocused(false)}
+ onBlur={() => {
+ setFocused(false);
+ tabMovesFocusRef.current = false;
+ }}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
{...stylex.props(styles.editor, sizeStyle)}
/>
+ {!isReadOnly && (
+ <VisuallyHidden id={hintId}>{escapeHint}</VisuallyHidden>
+ )}
</div>
</div>
</div>