An open source design system that's fully customizable and agent ready
TypeScript
refactor(core): consolidate the IME composition guard into utils/ime (#4907)
nynexman4464a7b6045d55a9
diff --git a/.changeset/ime-guard-utils-home.md b/.changeset/ime-guard-utils-home.mdnew file mode 100644index 0000000000..4bc53f106f--- /dev/null+++ b/.changeset/ime-guard-utils-home.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] `isImeKeyEvent` — the guard that stops an IME composition keystroke being read as a command — now lives at `@astryxdesign/core/utils` alongside the other pure helpers, with the reasoning for its two signals written down in one place. It stays exported from `@astryxdesign/core/hooks` for this release but is deprecated there: it is a plain predicate, not a hook, and that barrel is a `'use client'` boundary, so importing it from `hooks` pulls a server-safe function onto a client path. Move imports to `@astryxdesign/core/utils`; the `hooks` re-export will be removed in an upcoming major.++@nynexman4464diff --git a/IME_GUARD_DESIGN.md b/IME_GUARD_DESIGN.mdnew file mode 100644index 0000000000..b29a398f99--- /dev/null+++ b/IME_GUARD_DESIGN.md@@ -0,0 +1,92 @@+# IME Composition Guard — Shared Base Design++> Scratch design doc for the reviewer. Not shipped. Branch:+> `nynexman4464/refactor/ime-guard-shared-base`.++## TL;DR recommendation++1. **Keep `isImeKeyEvent` as the single low-level predicate.** It is the right+ primitive. Do **not** add a `useImeSafeKeyDown` wrapper hook — see §3 for why+ it would be over-engineering and, at 2 of 7 sites, outright wrong.+2. **Relocate it from `hooks/useFocusTrap.ts` → `utils/ime.ts`** (a discoverable+ home matching the pure-predicate convention in `utils/`), with the canonical+ "why" doc comment living there and nowhere else.+3. **Re-export from `useFocusTrap.ts` (deprecated) for back-compat**, and migrate+ the 3 existing importers + 3 inline duplicators to the shared predicate.+4. Give the lint rule (separate stream) one blessed symbol to point at:+ `@astryxdesign/core/src/utils/ime#isImeKeyEvent`.++## 1. Inventory (7 sites in core, +1 different pattern in lab)++| # | Site | Guards | Handler | Detection | Event source | Notes |+|---|------|--------|---------|-----------|--------------|-------|+| 1 | `hooks/useFocusTrap.ts` | Escape (dismiss trap) | native `keydown` | `isImeKeyEvent` (canonical def lived here) | native DOM `KeyboardEvent` | Also home of the exported helper — odd place for a general util. |+| 2 | `Typeahead/BaseTypeahead.tsx` | Enter/Esc/Arrows/Home/End (candidate nav + commit) | React `onKeyDown` | `isImeKeyEvent(e.nativeEvent)` | `e.nativeEvent` | Early return before all key logic. Added via PR #4860. |+| 3 | `PowerSearch/PowerSearchEditPopover.tsx` | Enter (save), Escape (cancel) | React `onKeyDown` | `isImeKeyEvent(e.nativeEvent)` | `e.nativeEvent` | Early return before Enter/Escape branch. |+| 4 | `Dialog/Dialog.tsx` | Escape (close) | native `keydown` | `isImeKeyEvent(event)` **+** `hasActiveFocusTrapEscape()` | native DOM `KeyboardEvent` | Composite guard; also defers to layered popover. |+| 5 | `ContextMenu/ContextMenu.tsx` | Escape (dismiss) | native `keydown` (document listener) | **inline** `e.isComposing \|\| e.keyCode === 229` | native DOM `KeyboardEvent` | Duplicated predicate. |+| 6 | `Tooltip/useTooltip.tsx` | Escape (dismiss, WCAG 1.4.13) | native `keydown` (document listener) | **inline** `e.isComposing \|\| e.keyCode === 229` | native DOM `KeyboardEvent` | Duplicated predicate. |+| 7 | `Chat/ChatComposerInput.tsx` | Enter (submit) | React `onKeyDown` | **inline** `e.nativeEvent.isComposing \|\| e.nativeEvent.keyCode === 229` | `e.nativeEvent` | Duplicated predicate; only guards Enter. |+| — | `lab/CodeEditor/CodeEditor.tsx` | **onInput** (not keydown) | React `onInput` + `onCompositionStart/End` | **ref tracking** (`isComposingRef`) | n/a | DIFFERENT pattern & different concern — see §4. Left untouched. |++### Detection styles observed+- **Shared predicate** (sites 1–4): call `isImeKeyEvent(...)`.+- **Inline duplication** (sites 5–7): open-code `isComposing || keyCode === 229`.+- **Ref tracking** (CodeEditor): track `compositionstart`/`compositionend` to+ gate the *input/change* path, not a keydown command.++### SyntheticEvent vs nativeEvent+- React's `KeyboardEvent` SyntheticEvent DOES expose `isComposing`. But the+ React-handler sites (BaseTypeahead, PowerSearch, Chat) deliberately read+ `e.nativeEvent` to avoid any React normalization gap and to reach `keyCode`.+- Native-listener sites (focus-trap, Dialog, ContextMenu, Tooltip) pass the DOM+ `KeyboardEvent` directly.+- The predicate is **structurally typed** (`{isComposing?; keyCode?}`) so both+ shapes are accepted with no casting.++### Is `keyCode === 229` still load-bearing? — Yes.+`229` is the sentinel keyCode browsers report while a key event is being+processed by an IME. Some IMEs and older Safari fire the composing `keydown`+with `isComposing` **not yet** `true` but DO report `229`. Dropping the fallback+would regress those. Keep both signals until a browser-matrix audit says+otherwise. (Documented once, in `utils/ime.ts`.)++## 2. Where it should live+`utils/` already houses pure, event/data helpers (`getKey`, `mergeProps`,+`composeEventHandlers`, `inputAria`) each as `<name>.ts` + `<name>.test.ts` with+a barrel `index.ts`. `isImeKeyEvent` is a pure predicate — it belongs there, not+buried in a focus-trap hook. New file: `packages/core/src/utils/ime.ts`,+re-exported from `utils/index.ts`. `useFocusTrap.ts` keeps a deprecated+re-export so existing relative imports don't break.++## 3. Wrapper hook (`useImeSafeKeyDown`) — rejected, with reasons+A `useImeSafeKeyDown(handler)` that no-ops during composition sounds tidy but:+- **Call sites are not uniform.** 4 use native DOM listeners inside `useEffect`+ (not a React `onKeyDown` prop the hook could wrap); 3 use React handlers.+- **Wrapping is wrong at 2 sites.** `useFocusTrap` and `Dialog` combine the IME+ check with *other* conditions (`isTopEscapeHandler`, `defaultPrevented`,+ `hasActiveFocusTrapEscape()`), and must still run that surrounding logic — a+ blanket "no-op the whole handler during composition" changes behavior.+- **The predicate is already the minimal correct primitive.** An early+ `if (isImeKeyEvent(e)) return;` is explicit, greppable, and lint-targetable.+- A wrapper adds a hook, a render-identity concern, and a second thing the lint+ rule must special-case — net negative. **Recommend: predicate + lint rule.**++## 4. CodeEditor is intentionally out of scope+`lab/CodeEditor` guards `onInput` (would otherwise write partial CJK syllables+into `value`) via `compositionstart/end` ref tracking — a different concern than+"don't treat a composing keydown as a command", so the shared keydown predicate+doesn't replace it. **Flag:** its `handleKeyDown` handles Escape (arms+tab-moves-focus) and Tab *without* an IME guard, so a composing Escape/Tab could+misfire. Latent, in `lab`, and behavioral — left for a separate fix.++## 5. What this branch implements (low-risk only)+- New `utils/ime.ts` (canonical predicate + the one authoritative doc comment)+ and `utils/ime.test.ts` (two-signal coverage).+- `utils/index.ts` re-exports `isImeKeyEvent`.+- `useFocusTrap.ts`: local def removed; imports from `utils/ime`; deprecated+ re-export kept for back-compat.+- Migrated importers to the util path: `Dialog`, `BaseTypeahead`, `PowerSearch`.+- De-duplicated the 3 inline sites (`ContextMenu`, `Tooltip`, `ChatComposerInput`)+ to call `isImeKeyEvent`, deferring rationale to `utils/ime.ts`.+- **No behavioral change** — same boolean logic everywhere; pure consolidation.diff --git a/packages/core/src/Chat/ChatComposerInput.tsx b/packages/core/src/Chat/ChatComposerInput.tsxindex 1f7560a2cc..6b8b07c780 100644--- a/packages/core/src/Chat/ChatComposerInput.tsx+++ b/packages/core/src/Chat/ChatComposerInput.tsx@@ -43,7 +43,7 @@ import {typeScaleVars,typographyVars,} from '../theme/tokens.stylex';-import {mergeProps} from '../utils';+import {mergeProps, isImeKeyEvent} from '../utils';import {useTriggerMenu} from './useTriggerMenu';import {useChatComposerTokens, isCustomToken} from './useChatComposerTokens';import {ensureCaretInside, insertTextAtCursor} from './chatComposerSelection';@@ -559,9 +559,8 @@ export function ChatComposerInput(props: ChatComposerInputProps) {if (e.key === 'Enter' && !e.shiftKey) {// Never submit mid-composition — an IME uses Enter to commit a- // candidate (e.g. Japanese/Chinese/Korean input), and browsers may- // also surface the legacy keyCode 229 for composing keystrokes.- if (e.nativeEvent.isComposing || e.nativeEvent.keyCode === 229) {+ // candidate. See utils/ime.ts for the full rationale.+ if (isImeKeyEvent(e.nativeEvent)) {return;}diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsxindex 3b55552783..52527a0dc1 100644--- a/packages/core/src/ContextMenu/ContextMenu.tsx+++ b/packages/core/src/ContextMenu/ContextMenu.tsx@@ -63,7 +63,7 @@ import {easeVars,shadowVars,} from '../theme/tokens.stylex';-import {mergeProps, mergeRefs} from '../utils';+import {mergeProps, mergeRefs, isImeKeyEvent} from '../utils';import type {BaseProps} from '../BaseProps';import type {StyleXStyles} from '../theme/types';import {themeProps} from '../utils/themeProps';@@ -334,7 +334,9 @@ export function ContextMenu({if (e.key !== 'Escape') {return;}- if (e.isComposing || e.keyCode === 229) {+ if (isImeKeyEvent(e)) {+ // Ignore Escape that is committing/cancelling an IME composition;+ // see utils/ime.ts for why.return;}e.preventDefault();diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsxindex aa942028fa..024133a1e3 100644--- a/packages/core/src/Dialog/Dialog.tsx+++ b/packages/core/src/Dialog/Dialog.tsx@@ -27,7 +27,8 @@ import {import type {BaseProps} from '../BaseProps';import * as stylex from '@stylexjs/stylex';import {useScrollLock} from '../hooks/useScrollLock';-import {hasActiveFocusTrapEscape, isImeKeyEvent} from '../hooks/useFocusTrap';+import {hasActiveFocusTrapEscape} from '../hooks/useFocusTrap';+import {isImeKeyEvent} from '../utils/ime';import {colorVars,radiusVars,diff --git a/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx b/packages/core/src/PowerSearch/PowerSearchEditPopover.tsxindex 60c3c0a00f..ce0fe0e679 100644--- a/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx+++ b/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx@@ -20,7 +20,7 @@ import {HStack, VStack} from '../Stack';import {Icon} from '../Icon';import {TreeList, type TreeListItemData} from '../TreeList';import {useTranslator} from '../i18n';-import {isImeKeyEvent} from '../hooks/useFocusTrap';+import {isImeKeyEvent} from '../utils/ime';import {spacingVars, typeScaleVars} from '../theme/tokens.stylex';import {PowerSearchValueEditor} from './PowerSearchValueEditor';import {resolveOperatorLabel} from './resolveOperatorLabel';diff --git a/packages/core/src/Tooltip/useTooltip.tsx b/packages/core/src/Tooltip/useTooltip.tsxindex 45ad4d3373..b0719ff3e8 100644--- a/packages/core/src/Tooltip/useTooltip.tsx+++ b/packages/core/src/Tooltip/useTooltip.tsx@@ -28,6 +28,7 @@ import {} from '../Layer/useLayer';import {layerAnimations} from '../Layer/layerAnimations.stylex';import {themeProps} from '../utils/themeProps';+import {isImeKeyEvent} from '../utils/ime';import {colorVars,radiusVars,@@ -454,7 +455,9 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {if (e.key !== 'Escape') {return;}- if (e.isComposing || e.keyCode === 229) {+ if (isImeKeyEvent(e)) {+ // Ignore Escape that is committing/cancelling an IME composition;+ // see utils/ime.ts for why.return;}clearTimeouts();diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsxindex d0368829c8..fc0f840356 100644--- a/packages/core/src/Typeahead/BaseTypeahead.tsx+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx@@ -30,7 +30,7 @@ import * as stylex from '@stylexjs/stylex';import type {StyleXStyles} from '@stylexjs/stylex';import {usePopover} from '../Popover/usePopover';import {useAnnounce} from '../hooks/useAnnounce';-import {isImeKeyEvent} from '../hooks/useFocusTrap';+import {isImeKeyEvent} from '../utils/ime';import {TypeaheadItem} from './TypeaheadItem';import {Icon} from '../Icon';import {diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.tsindex f96b7ccedb..ad14642941 100644--- a/packages/core/src/hooks/index.ts+++ b/packages/core/src/hooks/index.ts@@ -11,13 +11,17 @@* SYNC: When modified, update this header*/-export {- hasActiveFocusTrapEscape,- isImeKeyEvent,- useFocusTrap,-} from './useFocusTrap';+export {hasActiveFocusTrapEscape, useFocusTrap} from './useFocusTrap';export type {UseFocusTrapOptions, UseFocusTrapReturn} from './useFocusTrap';+/**+ * @deprecated Import from `@astryxdesign/core/utils` instead — this is a pure+ * predicate, not a hook, and the `hooks` barrel is a `'use client'` boundary.+ * Re-exported here for one release so consumers can move; will be removed in+ * an upcoming major.+ */+export {isImeKeyEvent} from '../utils/ime';+export {useAnnounce} from './useAnnounce';export type {AnnounceFn, AnnouncePoliteness} from './useAnnounce';diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.tsindex dae073bbc6..07448ff743 100644--- a/packages/core/src/hooks/useFocusTrap.ts+++ b/packages/core/src/hooks/useFocusTrap.ts@@ -19,6 +19,7 @@import {useCallback, useEffect, useRef} from 'react';import {FOCUSABLE_SELECTOR} from './focusableSelector';+import {isImeKeyEvent} from '../utils/ime';/*** Module-level stack of active focus-trap Escape handlers.@@ -94,20 +95,6 @@ export function hasActiveFocusTrapEscape(): boolean {return escapeStack.length > 0;}-/**- * Whether an Escape keydown should be ignored because it is cancelling an- * in-progress IME composition. CJK/IME users press Escape to cancel- * composition; that must not close the surrounding overlay. `keyCode === 229`- * covers browsers that fire keydown before `isComposing` is set. Exported so- * other overlays (Dialog, Drawer, CommandPalette) share one definition.- */-export function isImeKeyEvent(event: {- isComposing?: boolean;- keyCode?: number;-}): boolean {- return event.isComposing === true || event.keyCode === 229;-}-/*** Whether an element is currently perceivable/focusable — excludes ones hidden* via `display:none`/`visibility:hidden` or inside an `inert`/`hidden` subtree,diff --git a/packages/core/src/utils/ime.test.ts b/packages/core/src/utils/ime.test.tsnew file mode 100644index 0000000000..6bb8b208e2--- /dev/null+++ b/packages/core/src/utils/ime.test.ts@@ -0,0 +1,32 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {isImeKeyEvent} from './ime';++describe('isImeKeyEvent', () => {+ it('detects the modern isComposing signal', () => {+ expect(isImeKeyEvent({isComposing: true})).toBe(true);+ expect(isImeKeyEvent({isComposing: true, keyCode: 13})).toBe(true);+ });++ it('detects the legacy keyCode 229 fallback (IME processing sentinel)', () => {+ // Some IMEs / older Safari fire the composing keydown with isComposing+ // not yet set to true but report keyCode 229.+ expect(isImeKeyEvent({keyCode: 229})).toBe(true);+ expect(isImeKeyEvent({isComposing: false, keyCode: 229})).toBe(true);+ });++ it('returns false for ordinary (non-composing) keydowns', () => {+ expect(isImeKeyEvent({})).toBe(false);+ expect(isImeKeyEvent({isComposing: false})).toBe(false);+ expect(isImeKeyEvent({keyCode: 13})).toBe(false); // plain Enter+ expect(isImeKeyEvent({keyCode: 27})).toBe(false); // plain Escape+ expect(isImeKeyEvent({isComposing: false, keyCode: 13})).toBe(false);+ });++ it('only treats a literal `true` isComposing as composing', () => {+ // Guards against truthy-but-not-true values leaking through.+ // @ts-expect-error intentionally passing a non-boolean to assert strictness+ expect(isImeKeyEvent({isComposing: 1})).toBe(false);+ });+});diff --git a/packages/core/src/utils/ime.ts b/packages/core/src/utils/ime.tsnew file mode 100644index 0000000000..d8bd963205--- /dev/null+++ b/packages/core/src/utils/ime.ts@@ -0,0 +1,69 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ime.ts+ * @input Receives a keyboard event (React SyntheticEvent's `nativeEvent`, or a+ * native DOM KeyboardEvent) with optional `isComposing` / `keyCode`.+ * @output Exports `isImeKeyEvent`, the canonical predicate for "this keydown is+ * part of an in-progress IME composition and must not be treated as a command".+ * @position Shared low-level utility; consumed by every editable/overlay surface+ * that handles Enter/Escape/arrows in `onKeyDown` (Typeahead, PowerSearch,+ * Dialog, ContextMenu, Tooltip, Chat composer, focus-trap Escape, ...).+ *+ * ── Why this exists (read once, here — do not re-explain at call sites) ──+ *+ * When a CJK user (Korean / Japanese / Chinese) is composing text via an IME,+ * the browser fires a `keydown` event to COMMIT or CANCEL the pending+ * composition (Enter commits the highlighted candidate; Escape cancels it;+ * ArrowUp/Down/Home/End navigate the candidate window). Crucially this+ * `keydown` fires BEFORE the `compositionend` event that actually writes the+ * committed text into the field. So a naive `onKeyDown` handler sees a bare+ * "Enter" or "Escape" and misreads the composition-commit/cancel as an+ * application command — accepting a typeahead suggestion, submitting a chat+ * message, closing a dialog/menu/tooltip, or saving a filter — mid-composition.+ * The fix is to detect the composing keydown and early-return before running+ * any command logic.+ *+ * Two signals, both needed:+ *+ * 1. `event.isComposing === true` — the modern, spec'd signal+ * (https://www.w3.org/TR/uievents/#dom-keyboardevent-iscomposing). This is+ * the primary check and is reliable in current evergreen browsers.+ *+ * 2. `event.keyCode === 229` — the legacy fallback. `229` is the sentinel+ * keyCode browsers report for "the key event is being processed by an IME".+ * It is still load-bearing: some IMEs and older Safari fire the composing+ * `keydown` with `isComposing` NOT yet set to `true`, but DO report+ * keyCode 229. Keeping both makes the guard robust across the browser+ * matrix we support. Do not drop the 229 fallback without a browser-matrix+ * audit.+ *+ * ── Which event object to pass ──+ *+ * React's SyntheticEvent for KeyboardEvent *does* surface `isComposing`, but to+ * avoid any cross-browser normalization gap prefer passing the *native* event+ * (`e.nativeEvent`) from React handlers — that is what BaseTypeahead,+ * PowerSearch, and the Chat composer do. Native DOM listeners (Dialog,+ * ContextMenu, Tooltip, focus-trap) pass the DOM `KeyboardEvent` directly.+ * The parameter is intentionally structurally typed so both shapes are accepted.+ *+ * Note: `keyCode` is deprecated on the DOM `KeyboardEvent` type but is still+ * present at runtime; we read it defensively via the optional structural field.+ */++/**+ * The sentinel `keyCode` browsers report while a key event is being processed+ * by an IME (the composing keydown that fires before `compositionend`). See the+ * file header for why this legacy signal is still load-bearing alongside+ * `isComposing`.+ */+const IME_PROCESSING_KEY_CODE = 229;++export function isImeKeyEvent(event: {+ isComposing?: boolean;+ keyCode?: number;+}): boolean {+ return (+ event.isComposing === true || event.keyCode === IME_PROCESSING_KEY_CODE+ );+}diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.tsindex c8737164e7..8975453b0d 100644--- a/packages/core/src/utils/index.ts+++ b/packages/core/src/utils/index.ts@@ -107,3 +107,5 @@ export {rtlStyles} from './rtlStyles';// The shared focus ring, exported for @astryxdesign/lab — same reason// rtlStyles is: a style that must be identical across packages, not copied.export {focusOutlineStyles, focusOutlineProps} from './focusOutline.stylex';++export {isImeKeyEvent} from './ime';