Skip to content

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

Merged
cixzhang merged 2 commits into
meta:mainfrom
bhamodi:a11y/lab-richtext-trap
Aug 5, 2026
Merged

cixzhang merged 2 commits into
meta:mainfrom
bhamodi:a11y/lab-richtext-trap

Conversation

@bhamodi

@bhamodi bhamodi commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

RichTextEditor (lab) always registers Lexical's TabIndentationPlugin, which rebinds Tab/Shift+Tab to indent/outdent and preventDefault()s the keydown. A keyboard-only user who tabs into the editor cannot tab out again -- a serious WCAG 2.1.2 (No Keyboard Trap) violation. Found as finding #3 of the a11y scan; this is the companion to the CodeEditor Tab-trap fix (same UX pattern: keep Tab indentation, add an Escape-then-Tab exit).

Tab indentation itself is worth keeping -- it is how list/quote nesting works -- so instead of removing it, this PR adds a standard escape:

  • Escape arms an exit: the next Tab (or Shift+Tab) performs native focus movement out of the editor instead of indenting.
  • Any other non-modifier key re-arms indentation, so normal editing is unaffected.
  • The escape is advertised to screen-reader users via a visually hidden hint wired into the contenteditable's aria-describedby, overridable/suppressible through a new tabEscapeHint prop (lab has no i18n catalog; the default-English-string-via-prop pattern matches InfoTip's label).

Changes

packages/lab/src/RichTextEditor/RichTextEditor.tsx

  • New internal TabFocusEscapePlugin, rendered alongside TabIndentationPlugin. Lexical mechanics: TabIndentationPlugin handles KEY_TAB_COMMAND at COMMAND_PRIORITY_EDITOR (0), the lowest priority, and Lexical runs command listeners from highest priority down, stopping at the first that returns true. The new plugin registers at COMMAND_PRIORITY_LOW (1), so it always runs first:
    • KEY_ESCAPE_COMMAND -> arm the escape. This handler returns true, deliberately superseding @lexical/rich-text's default Escape handler, which calls editor.blur() and dumps focus on document.body (disorienting, and it would immediately disarm the escape via the blur listener below). Consumer plugins that handle Escape at a higher priority still run first.
    • KEY_TAB_COMMAND -> if armed: disarm and return true without preventDefault(), so the indentation handler never sees the event and the browser performs its native Tab focus navigation. If not armed: return false and indentation proceeds as before.
    • KEY_DOWN_COMMAND -> any key other than Escape/Tab/bare modifiers disarms (bare Shift is exempt so Escape then Shift+Tab can escape backwards).
    • BLUR_COMMAND -> disarm when focus leaves the editor.
  • New tabEscapeHint prop (default: 'Press Escape then Tab to move focus out of the editor.'), rendered via core's VisuallyHidden and appended to the contenteditable's aria-describedby. Only rendered when the editor is editable; pass '' to omit.
  • File header @input updated per the repo documentation protocol.

packages/lab/src/RichTextEditor/RichTextEditor.doc.mjs -- props-table entry for tabEscapeHint (targeted insert only; file otherwise untouched).

packages/lab/src/RichTextEditor/RichTextEditor.test.tsx -- 7 new tests (see below).

Test plan

node_modules/.bin/vitest run packages/lab/src/RichTextEditor --reporter=dot   # 1 file, 23 passed (was 16)
node_modules/.bin/vitest run packages/lab --reporter=dot                      # 19 files, 260 passed
node_modules/.bin/tsc --project packages/lab/tsconfig.json --noEmit           # no new errors (see note)
node_modules/.bin/eslint <changed files>                                      # clean
node_modules/.bin/prettier --check <changed files>                            # clean

New tests (all driven through real keydown events on the contenteditable -- userEvent.tab() / userEvent.keyboard() respect defaultPrevented, so they exercise the actual trap):

  1. Tab indents a seeded bullet-list item (indent 0 -> 1) and focus stays in the editor.
  2. Escape then Tab moves document.activeElement out of the editor (onto the next focusable button) without indenting.
  3. Pressing another key after Escape re-arms indentation (Tab indents again, focus stays).
  4. A bare Shift keydown does not re-arm, so Escape then Shift+Tab still escapes (asserted via defaultPrevented).
  5. The default hint is rendered visually hidden and its id appears in the contenteditable's aria-describedby.
  6. tabEscapeHint is overridable and '' suppresses the hint (and drops it from aria-describedby).
  7. No hint when isReadOnly (editor is not editable, so there is no trap).

Pre-fix failure confirmed: with the tests added but the component fix absent, the 5 behavior/hint tests fail exactly as expected (test 2 shows focus unable to leave the editor); tests 1 and 7 pass pre-fix, as those behaviors already existed. Post-fix: 23/23.

jsdom notes (honest limitations):

  • jsdom's Range lacks getBoundingClientRect, which Lexical calls when reconciling a focused collapsed selection; the test suite stubs it (returns a zero DOMRect) inside the new describe block only.
  • jsdom does not implement contenteditable text editing, so "typing re-arms" is driven as a raw keydown (which is precisely the re-arm signal the implementation uses). Focus movement itself is real: user-event implements Tab's focus-change behavior and honors preventDefault, so test 2 genuinely observes activeElement leaving the editor.
  • Manual step worth doing in a browser: Escape's previous default (Lexical rich-text editor.blur()) is intentionally replaced by the arm behavior -- focus now stays in the editor after Escape until Tab is pressed.

Notes

  • No changeset: scripts/check-changesets.mjs hard-rejects @astryxdesign/lab ("private/ignored and cannot be released"). Lab is canary-only (private: true is npm's guarantee against a stable publish) and is changeset-exempt per the RFC [RFC #3899] feat(lab): experimental Lexical rich-text editor (RichTextEditor + RichTextView) #3900 landing ("Lab is canary-only and private, so no changeset is required"); CI stamps canary versions. The check script passes with no changeset in this PR.
  • tsc --project packages/lab/tsconfig.json reports 7 pre-existing TS2305 errors in Chart/ThreeD (parseHex etc. missing from @astryxdesign/core/utils); output is byte-identical on clean main -- untouched by this PR.
  • The Vercel deploy check fails on every fork PR (known infra); review-required is a human gate.

Review follow-up (2026-07-31)

  • packages/build is no longer touched — byte-identical to main, alias tests and its changeset removed. The lexical$ → built-ESM pin (needed because this fix adds runtime lexical imports, which withAstryx's issuer-scoped source-condition rule would otherwise resolve to lexical's raw TS with declare class fields that the sandbox Babel pipeline rejects) now lives in apps/sandbox/next.config.mjs, with the same issuer-scoped rule shape. App-local is sufficient: @astryxdesign/lab is private, so no external withAstryx consumer can ever build lab from source — the shared build package stays agnostic to libraries outside core.
  • On the earlier review note about the pin bypassing dev/prod condition selection: dist/Lexical.mjs is an env-switching wrapper (process.env.NODE_ENV !== 'production' ? dev : prod), so build-time env selection is preserved.
  • Rebased onto current main; the conflict with the new getHTML()/getMarkdown() imperative-ref work was in the lexical import block only (runtime command imports merged with $generateHtmlFromNodes + type-only imports). vitest run packages/lab/src/RichTextEditor: 46/46 green post-merge.

@vercel

vercel Bot commented Jul 26, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
astryx Ready Ready Preview Aug 5, 2026 3:34am

Request Review

@github-actions github-actions Bot added community Authored by a community contributor (not on the eng/design team) needs:code-review High-risk change (new package/component/API) — needs human code review before merge labels Jul 26, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 26, 2026
@github-actions

github-actions Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

PR Analysis Report

📚 Storybook Preview

View Storybook for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

🧪 Sandbox Preview

View Sandbox for this PR
GitHub Pages may take up to a minute to hydrate after deploy.

Modified Components

RichTextEditor (@astryxdesign/lab) · View in Storybook
Metric Before After Delta
Bundle Size (ESM) N/A N/A N/A
Lines of Code N/A 1576 -
Complexity N/A Very High (103) -

Bundle Size Summary

Package Size (ESM) Size (CJS) Gzipped
@astryxdesign/lab N/A 3.5KB 1.5KB

Accessibility Audit

Status: No accessibility violations detected.


Generated by PR Enrichment workflow | Storybook | Sandbox | View full report

@cixzhang

Copy link
Copy Markdown
Contributor

@potatowagon can you help take a look :)

@potatowagon

Copy link
Copy Markdown
Contributor

Review

Solid, ship-worthy. Correct WCAG 2.1.2 fix, well-tested (ran locally, 42/42 pass), no regressions found. Traced the command-priority reasoning against Lexical's actual dispatch order — it holds up. A few minor items below, none blocking.

✅ Verified correct

  • Command ordering is genuinely safe. Lexical's onKeyDown dispatches KEY_DOWN_COMMAND first, and $handleKeyDown (a KEY_DOWN listener) re-dispatches KEY_TAB/KEY_ESCAPE within that same chain. So on a Tab press the plugin's KEY_DOWN handler sees key === 'Tab' — which is in ESCAPE_REARM_EXEMPT_KEYS, so it does not disarm before the KEY_TAB handler reads the flag. That exempt-set is load-bearing and correct.
  • Priority claim checks out. TabIndentationPlugin registers at COMMAND_PRIORITY_EDITOR (0); this plugin at LOW (1) runs first. Returning true without preventDefault() is the right lever to block indent while letting native focus move.
  • Build alias scoping is correct. lexical$ exact-match (the $ suffix) only pins the bare lexical request, not @lexical/* subpackages — so the @lexical/* TS-source path the comment relies on is preserved. resolveLexicalDist fails safe (returns null → alias omitted).

🟡 Minor

  1. The build alias pins to Lexical.mjs (the default export condition). This bypasses webpack's development/production condition selection, so prod builds of any withAstryx consumer get the un-minified default bundle rather than Lexical.prod.mjs. Harmless in lab/canary, but it's a subtle size/perf regression for external consumers of the wrapper. Consider resolving the dist dir and letting webpack pick the condition, or a comment noting default is intentional.
  2. Hardcoded 'Lexical.mjs' filename is brittle against a future lexical package-layout change. Low risk (this name has been stable for years), but a version bump could silently break the alias → fall back to TS source → the exact declare-class-field Babel error this PR fixes returns. A comment noting the coupling, or globbing dist/Lexical*.mjs, would harden it.

🔵 Nits

  1. The 'use strict' quote-style flip in next.js is unrelated prettier churn — harmless but adds blame noise.
  2. DEFAULT_TAB_ESCAPE_HINT is duplicated as a literal in both the component and the test's DEFAULT_HINT. Minor drift risk; fine as-is since it's not exported.
  3. The behavior tests don't guard the relative command priority (only observable behavior) — if Lexical ever changes TabIndentationPlugin's registration priority this silently breaks. Acceptable tradeoff, just flagging the coupling to Lexical internals.

🔎 Edge cases considered — all OK

  • Escape → click away → refocus → Tab: BLUR_COMMAND disarms on focus loss, so a stale-armed escape can't leak across focus sessions. ✅
  • Escape → Escape → Tab: Escape is exempt from re-arm, just re-arms; still escapes. ✅
  • Consumer Escape handlers (popovers): higher-priority listeners still run first, as documented. ✅
  • Superseding rich-text's default Escape (editor.blur()): intentional and documented — worth the manual browser check you already flagged, since jsdom can't verify it.

@cixzhang cixzhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think accessibility updates look good but I'm not sure about the changes to the build package. This is shipped publically and used mainly to split the StyleX build for layering. It should be agnostic to libraries outside of core.

Comment thread packages/build/src/next.js Outdated
* than resolving `lexical/package.json` (not export-mapped). Returns null when
* lexical isn't installed so the alias is simply omitted.
*/
function resolveLexicalDist() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems odd to need this in the build which might not have anything to do with lexical. Was this to solve some issue unrelated to accessibility?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was needed by this PR, not unrelated: the trap fix adds runtime imports from lexical (KEY_TAB_COMMAND, KEY_ESCAPE_COMMAND, etc.), and withAstryx's issuer-scoped source-condition rule makes any bare lexical request issued from an astryx module resolve to lexical's raw TS source, whose declare class fields the sandbox Babel pipeline rejects. Before this PR, lab only had type-only imports from lexical, so the problem never surfaced.

On the placement, agreed -- the shipped build package should stay agnostic to libraries outside core. The alias is now gone from packages/build entirely (byte-identical to main, alias tests and its changeset removed) and lives in apps/sandbox/next.config.mjs instead, with the same issuer-scoped shape so only astryx-issued requests are pinned. App-local is sufficient because @astryxdesign/lab is private: no external withAstryx consumer can ever build lab from source, so the sandbox is the only place this resolution path exists.

@bhamodi

bhamodi commented Jul 31, 2026

Copy link
Copy Markdown
Contributor Author

@cixzhang Addressed -- packages/build is back to byte-identical with main; the lexical pin moved into apps/sandbox/next.config.mjs (details in the inline thread + the new 'Review follow-up' section of the description). @potatowagon your dev/prod-condition note turned out to be moot: dist/Lexical.mjs is an env-switching wrapper, so both modes still resolve correctly -- and it's now app-local anyway. Also rebased onto current main (the getHTML()/getMarkdown() import conflict resolved, 46/46 tests green).

bhamodi added 2 commits August 4, 2026 20:21
…SM output

The RichTextEditor keyboard-trap fix needs runtime command imports from
'lexical'. withAstryx's issuer-scoped source-condition rule makes those
resolve to lexical's raw TS (declare class fields), which the sandbox
Babel pipeline rejects. Pin lexical$ to dist/Lexical.mjs in the sandbox
app config — app-local because @astryxdesign/lab is private, so no
external withAstryx consumer can hit this; the shared build package
stays agnostic to libraries outside core.
@bhamodi
bhamodi force-pushed the a11y/lab-richtext-trap branch from 145c0f6 to 0dd94dd Compare August 5, 2026 03:28
@github-actions github-actions Bot removed the needs:code-review High-risk change (new package/component/API) — needs human code review before merge label Aug 5, 2026
@bhamodi

bhamodi commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main over the toolbar (#4551), link-support (#4670), and serializer (#4544) work -- the conflicts were import-merges only; the trap plugin, its command priorities, and the tests are unchanged. eslint/prettier pass locally; vitest for this branch needs the new @lexical/headless optional peer from #4544 which isn't installable offline here, so CI is the test verification for this push.

github-actions Bot added a commit that referenced this pull request Aug 5, 2026
@cixzhang
cixzhang merged commit 381694f into meta:main Aug 5, 2026
19 checks passed
@github-actions
github-actions Bot deleted the a11y/lab-richtext-trap branch August 5, 2026 08:23
cixzhang added a commit that referenced this pull request Aug 12, 2026
RichTextEditor's input wrapper spread `themeProps('rich-text-editor', ...)`
and then overwrote it with both `stylex.props(...)` and
`className={className}`. Each of those carries its own `className`, so React
kept only the last one: the stable `astryx-rich-text-editor` class never
reached the DOM, and with it went every StyleX class on the wrapper — border,
padding, disabled and status styling — plus the `xstyle` passthrough. Merged
through `mergeProps` instead, so the theme target, the StyleX classes and any
consumer `className`/`style` all survive.

The ChatSendButton half of this change landed separately on main in #4634
(`fix(Chat): add missing themeProps and fix className clobber`) with the same
`mergeProps` call, so only its regression test remains here.

The changeset goes with it: what is left changes `@astryxdesign/lab` only,
which is `private: true` / canary-only and so cannot be named in changeset
frontmatter (`check:changesets` rejects it), matching how other lab-only
fixes land (#4670, #4550, #4380, #4891).

@cixzhang
cixzhang added a commit that referenced this pull request Aug 12, 2026
RichTextEditor's input wrapper spread `themeProps('rich-text-editor', ...)`
and then overwrote it with both `stylex.props(...)` and
`className={className}`. Each of those carries its own `className`, so React
kept only the last one: the stable `astryx-rich-text-editor` class never
reached the DOM, and with it went every StyleX class on the wrapper — border,
padding, disabled and status styling — plus the `xstyle` passthrough. Merged
through `mergeProps` instead, so the theme target, the StyleX classes and any
consumer `className`/`style` all survive.

The ChatSendButton half of this change landed separately on main in #4634
(`fix(Chat): add missing themeProps and fix className clobber`) with the same
`mergeProps` call, so only its regression test remains here.

The changeset goes with it: what is left changes `@astryxdesign/lab` only,
which is `private: true` / canary-only and so cannot be named in changeset
frontmatter (`check:changesets` rejects it), matching how other lab-only
fixes land (#4670, #4550, #4380, #4891).

@cixzhang
cixzhang added a commit that referenced this pull request Aug 14, 2026
RichTextEditor's input wrapper spread `themeProps('rich-text-editor', ...)`
and then overwrote it with both `stylex.props(...)` and
`className={className}`. Each of those carries its own `className`, so React
kept only the last one: the stable `astryx-rich-text-editor` class never
reached the DOM, and with it went every StyleX class on the wrapper — border,
padding, disabled and status styling — plus the `xstyle` passthrough. Merged
through `mergeProps` instead, so the theme target, the StyleX classes and any
consumer `className`/`style` all survive.

The ChatSendButton half of this change landed separately on main in #4634
(`fix(Chat): add missing themeProps and fix className clobber`) with the same
`mergeProps` call, so only its regression test remains here.

The changeset goes with it: what is left changes `@astryxdesign/lab` only,
which is `private: true` / canary-only and so cannot be named in changeset
frontmatter (`check:changesets` rejects it), matching how other lab-only
fixes land (#4670, #4550, #4380, #4891).

@cixzhang
sangwook-dev added a commit to sangwook-dev/astryx that referenced this pull request Sep 19, 2026
meta#4380 pinned bare lexical imports issued from @astryxdesign modules to
lexical's built ESM: lab's RichTextEditor imported lexical, and withAstryx's
`source` condition sent it to lexical's raw TS. meta#4678 moved the editor into
@astryxdesign/richtext, which the sandbox does not depend on, and left the
alias behind.

Nothing the sandbox compiles imports lexical, @lexical/* or richtext, and the
build output contains no lexical code with or without the alias. Remove it,
along with the lexical devDependency the earlier commit declared for it.

This branch was successfully deployed

1 active deployment
Preview — 0dd94dd1 Deployed Aug 5, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot. community Authored by a community contributor (not on the eng/design team)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants