Skip to content

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

TypeScript

feat(lint): @astryx/no-unguarded-ime-keydown — enforce IME composition guards (#4909)

nynexman4464ba74b44112c6
diff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.md
index f0c2719773..6bf2128a83 100644
--- a/internal/eslint-plugin-astryx/README.md
+++ b/internal/eslint-plugin-astryx/README.md
@@ -281,8 +281,7 @@ const styles = stylex.create({
wrapper: {
':focus-within': {outline: `2px solid ${colorVars['--color-accent']}`},
},
-});
-```
+});```
**Good:**
@@ -326,3 +325,67 @@ stylex.props(focusOutlineStyles.focusVisible, styles.base);
**Scope:** only what the ring LOOKS like — the `outline` shorthand, `outlineWidth`, `outlineStyle` — under a literal `:focus-visible` condition. Not flagged: `outlineOffset` (where the ring sits is a local constraint — inset into a tight grid, or held clear of a field border — and such a component still follows the theme's width, style and color), `outlineColor` (re-coloring per variant is the documented override), and a computed condition key such as `stylex.when.ancestor(':has(:focus-visible)', scope)`, which a shared style cannot express because a scope marker cannot be shared between components.
Ships as an **error in both tiers**: core and lab are clean, and this keeps them that way.
+
+### `@astryx/no-unguarded-ime-keydown`
+
+Flags an `onKeyDown` handler on an **editable surface** that branches on a
+"command" key (Enter/Escape/arrows/Page/Home/End, or a legacy `keyCode`/`which`)
+**without an IME composition guard**.
+
+For CJK (Korean/Japanese/Chinese) input, the browser fires `keydown` with
+`isComposing === true` (or the legacy `keyCode === 229`) **before**
+`compositionend` writes the pending syllable. A handler that reads
+`e.key === 'Enter'` (or `'Escape'`, an arrow…) to accept a suggestion, select an
+option, submit, or close then misfires on the keystroke that was only meant to
+**commit the composition**. Early-return on `isImeKeyEvent(e.nativeEvent)` (from
+`@astryxdesign/core/utils/ime` — it returns
+`event.isComposing === true || event.keyCode === 229`) before handling command
+keys.
+
+**Scope (deliberately conservative — a noisy rule gets disabled):** only flags
+when all of (1) the element is an editable surface — a `<textarea>`, an
+`<input>` whose `type` can host text composition (not checkbox/number/date/…), a
+`contentEditable` element, `role="textbox"`/`"searchbox"`/`"combobox"`, or a
+known Astryx text-input component (`TextInput`, `Typeahead`, `BaseTypeahead`,
+…) — and **not** a `<button>`/`<a>`/`role="button"` (IME can't compose on a
+button, even one with `role="combobox"`); (2) its handler (inline, or a same-file
+identifier resolving to a function/`useCallback`) branches on a command key; and
+(3) a source-text scan of the handler finds **no** `isImeKeyEvent(`,
+`.isComposing`, or `229`.
+
+**Bad:**
+
+```tsx
+<TextInput
+ onKeyDown={e => {
+ if (e.key === 'Enter') onSelect(); // ❌ fires on a composing Enter
+ }}
+/>
+```
+
+**Good:**
+
+```tsx
+import {isImeKeyEvent} from '@astryxdesign/core/utils/ime';
+
+<TextInput
+ onKeyDown={e => {
+ if (isImeKeyEvent(e.nativeEvent)) return; // ✅ let the IME commit first
+ if (e.key === 'Enter') onSelect();
+ }}
+/>;
+```
+
+Ships as an **error in both tiers**: the editable surfaces that violated it —
+Selector, MultiSelector, DateInput, TimeInput, DateTimeInput, and Typeahead's
+edit-mode Escape — are fixed in the commit below this one, so core is clean and
+this keeps it that way.
+
+**Known limitations (intentional false-negatives):** guard/command-key detection
+is a lenient text scan (any `isImeKeyEvent(`/`.isComposing`/`229` anywhere in the
+handler counts as guarded; a `e.key === ENTER_KEY` variable comparison is not
+detected). Handler indirection is resolved only one hop within the same file — an
+imported handler is treated as unknown and not flagged. A `role`/`type`/
+`contentEditable` spread via `{...props}` is not seen.
+
+See: https://github.com/facebook/astryx/issues/4892
diff --git a/internal/eslint-plugin-astryx/index.js b/internal/eslint-plugin-astryx/index.js
index 61682542ae..d62ef4566b 100644
--- a/internal/eslint-plugin-astryx/index.js
+++ b/internal/eslint-plugin-astryx/index.js
@@ -11,6 +11,7 @@
* - no-raw-paragraph: Disallows components from rendering a <p> by default (render <div> so any content composes)
* - no-style-only-wrapper: Disallows div/span wrappers that only style a single Astryx component (use xstyle)
* - no-nullish-jsx-guard: Flags `!= null` JSX render guards for rendered values (use isRenderable so false/''/true slots don't leak an empty element)
+ * - no-unguarded-ime-keydown: Flags an onKeyDown on an editable surface that branches on command keys without an IME composition guard (isImeKeyEvent/isComposing)
*
* Philosophy: Strict for agents (CI), lenient for humans (local dev)
* - "strict" config: All rules as errors - use in CI/agent environments
@@ -28,6 +29,7 @@ import noClassnameClobberRule from './no-classname-clobber.js';
import noHardcodedAnchorRule from './no-hardcoded-anchor.js';
import noRawParagraphRule from './no-raw-paragraph.js';
import noNullishJsxGuardRule from './no-nullish-jsx-guard.js';
+import noUnguardedImeKeydownRule from './no-unguarded-ime-keydown.js';
import noBorderShorthandRule from './no-border-shorthand.js';
import noPhysicalPropertiesRule from './no-physical-properties.js';
import focusOutlineKeyboardOnlyRule from './focus-outline-keyboard-only.js';
@@ -250,6 +252,7 @@ const plugin = {
'no-hardcoded-anchor': noHardcodedAnchorRule,
'no-raw-paragraph': noRawParagraphRule,
'no-nullish-jsx-guard': noNullishJsxGuardRule,
+ 'no-unguarded-ime-keydown': noUnguardedImeKeydownRule,
'no-border-shorthand': noBorderShorthandRule,
'no-physical-properties': noPhysicalPropertiesRule,
'focus-outline-keyboard-only': focusOutlineKeyboardOnlyRule,
@@ -292,6 +295,11 @@ plugin.configs.strict = {
// Kept as 'warn' so it surfaces everywhere (including CI) without failing
// the build; promote to 'error' once core is migrated (see issue #2538).
'@astryx/no-nullish-jsx-guard': 'warn',
+ // All editable command-key handlers in core now guard IME composition
+ // (Selector, MultiSelector, DateInput, DateTimeInput, TimeInput, and
+ // Typeahead's edit-mode Escape were fixed alongside this rule); error to
+ // prevent regressions (see issue #4892).
+ '@astryx/no-unguarded-ime-keydown': 'error',
'@astryx/no-border-shorthand': 'error',
// RTL physical→logical migration complete; errors to prevent regressions.
'@astryx/no-physical-properties': 'error',
@@ -328,6 +336,9 @@ plugin.configs.recommended = {
'@astryx/no-hardcoded-anchor': 'warn',
'@astryx/no-raw-paragraph': 'warn',
'@astryx/no-nullish-jsx-guard': 'warn',
+ // IME composition migration complete; error to prevent regressions
+ // (see strict config above and issue #4892).
+ '@astryx/no-unguarded-ime-keydown': 'error',
'@astryx/no-border-shorthand': 'warn',
// RTL physical→logical migration complete; errors to prevent regressions.
'@astryx/no-physical-properties': 'error',
diff --git a/internal/eslint-plugin-astryx/no-unguarded-ime-keydown.js b/internal/eslint-plugin-astryx/no-unguarded-ime-keydown.js
new file mode 100644
index 0000000000..562ebea6ff
--- /dev/null
+++ b/internal/eslint-plugin-astryx/no-unguarded-ime-keydown.js
@@ -0,0 +1,405 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file no-unguarded-ime-keydown.js
+ * @description Flag an `onKeyDown` handler on an editable surface that branches
+ * on a "command" key (Enter/Escape/arrows/Page/Home/End or a legacy
+ * `keyCode`/`which`) WITHOUT an IME composition guard.
+ *
+ * THE BUG: for CJK (Korean/Japanese/Chinese) input, the browser fires
+ * `keydown` with `isComposing === true` (or the legacy `keyCode === 229`)
+ * BEFORE `compositionend` writes the pending syllable. A handler that reads
+ * `e.key === 'Enter'` (or `'Escape'`, an arrow, etc.) to accept a suggestion,
+ * select an option, submit, or close then misfires on the keystroke that was
+ * only meant to COMMIT the composition — e.g. it selects the highlighted
+ * option AND clears the field, so the IME's subsequent `compositionend`
+ * writes the pending syllable into the freshly-cleared input and a second
+ * spurious selection happens on the next real Enter.
+ *
+ * THE FIX (already shipped reactively in Typeahead #4860, ChatComposerInput,
+ * PowerSearchEditPopover, Dialog, Tooltip): early-return when
+ * `isImeKeyEvent(e.nativeEvent)` is true. `isImeKeyEvent` lives in
+ * `packages/core/src/utils/ime.ts` and returns
+ * `event.isComposing === true || event.keyCode === 229`. This rule ENFORCES
+ * that guard so new editable surfaces can't reintroduce the bug silently.
+ *
+ * @see packages/core/src/utils/ime.ts (isImeKeyEvent)
+ * @see https://github.com/facebook/astryx/issues/4892
+ *
+ * SEVERITY: shipped at `warn` in BOTH tiers (see index.js). Selector and
+ * MultiSelector currently violate it and are fixed in a separate stream; a
+ * `warn` surfaces the debt everywhere (incl. CI) without failing the build.
+ * Promote to `error` in strict once those migrate (issue #4892).
+ *
+ * HEURISTIC (pragmatic AST + source-text scan, NOT dataflow — matches sibling
+ * rules like no-style-only-wrapper). It flags an `onKeyDown` JSX attribute
+ * only when ALL of:
+ * 1. The element it is on is an EDITABLE surface (a `<textarea>`, an
+ * `<input>` whose `type` can host text composition — i.e. not
+ * checkbox/number/date/etc., see NON_COMPOSABLE_INPUT_TYPES — a
+ * `contentEditable` element, an element with `role="textbox"`/
+ * `"searchbox"`/`"combobox"`, or a known Astryx text-input component in
+ * EDITABLE_COMPONENTS) and is NOT an explicitly non-editable element
+ * (`<button>`, `<a>`, `role="button"`) — IME composition cannot run on a
+ * button even if it carries `role="combobox"` (this is exactly the
+ * Selector trigger case).
+ * 2. Its handler (an inline arrow/function, OR a same-file identifier that
+ * resolves to a function/arrow/useCallback) branches on a COMMAND key —
+ * an `e.key`/`event.key` compared against Enter/Escape/arrow/Page/
+ * Home/End (or a `switch (e.key)` over those), OR reads a legacy
+ * `keyCode`/`which`.
+ * 3. The handler body does NOT contain a composition guard: a source-text
+ * scan finds no `isImeKeyEvent(`, `.isComposing`, or `229`.
+ *
+ * INTENTIONAL FALSE-NEGATIVES (a noisy rule gets disabled — we prefer to miss):
+ * - Guard detection is a lenient text scan of the handler range: ANY mention
+ * of `isImeKeyEvent(`, `.isComposing`, or `229` marks the handler guarded,
+ * even if that mention is dead code or in a nested closure.
+ * - Handler indirection is resolved only ONE hop within the SAME file. A
+ * handler imported from another module, or reached through a variable that
+ * aliases another variable, is treated as "unknown" and NOT flagged.
+ * - Command-key detection is a text scan for the key names / `keyCode` /
+ * `which`; a handler that compares against a variable
+ * (`e.key === ENTER_KEY`) is not detected.
+ * - Editability of native tags is judged by JSX attributes present literally
+ * on the element; a `role`/`contentEditable` spread via `{...props}` is not
+ * seen.
+ */
+
+/**
+ * `<input type="...">` values that CANNOT host IME text composition, so an
+ * onKeyDown on them is not an IME hazard (a checkbox/number/date input never
+ * runs a composition session). Any other type — including `text`, `search`,
+ * `email`, an absent type, or a dynamic `type={...}` we can't read — is treated
+ * as potentially composable and stays in scope.
+ */
+const NON_COMPOSABLE_INPUT_TYPES = new Set([
+ 'checkbox',
+ 'radio',
+ 'button',
+ 'submit',
+ 'reset',
+ 'file',
+ 'range',
+ 'color',
+ 'number',
+ 'date',
+ 'time',
+ 'datetime-local',
+ 'month',
+ 'week',
+ 'hidden',
+ 'image',
+]);
+
+/**
+ * Native tags / roles that can NEVER host IME composition. If the element is
+ * one of these it is treated as non-editable even when it also carries an
+ * editable role (e.g. the Selector trigger `<button role="combobox">`).
+ */
+const NON_EDITABLE_TAGS = new Set(['button', 'a']);
+const NON_EDITABLE_ROLES = new Set([
+ 'button',
+ 'link',
+ 'menuitem',
+ 'tab',
+ 'option',
+]);
+
+/** ARIA roles that denote an editable text surface. */
+const EDITABLE_ROLES = new Set(['textbox', 'searchbox', 'combobox']);
+
+/**
+ * Astryx components that render an underlying editable `<input>`/`<textarea>`
+ * and forward `onKeyDown` to it. Matched by JSX element name.
+ */
+const EDITABLE_COMPONENTS = new Set([
+ 'TextInput',
+ 'TextArea',
+ 'Textarea',
+ 'NumberInput',
+ 'SearchInput',
+ 'Typeahead',
+ 'BaseTypeahead',
+ 'ComboBox',
+ 'Combobox',
+ 'ChatComposerInput',
+]);
+
+/** Command keys whose literal comparison in a handler indicates branching. */
+const COMMAND_KEYS = [
+ 'Enter',
+ 'Escape',
+ 'ArrowUp',
+ 'ArrowDown',
+ 'ArrowLeft',
+ 'ArrowRight',
+ 'Home',
+ 'End',
+ 'PageUp',
+ 'PageDown',
+];
+
+/** JSX element name as a string (`input`, `TextInput`, `foo.Bar` -> `Bar`). */
+function jsxName(nameNode) {
+ if (!nameNode) return null;
+ if (nameNode.type === 'JSXIdentifier') return nameNode.name;
+ // JSXMemberExpression (e.g. Foo.Bar) — use the trailing property.
+ if (nameNode.type === 'JSXMemberExpression')
+ return jsxName(nameNode.property);
+ return null;
+}
+
+/**
+ * Read the static string value of a JSX attribute (`role="combobox"` ->
+ * `combobox`). Returns null for expression-container / non-string values.
+ */
+function staticAttrValue(attr) {
+ if (!attr || attr.type !== 'JSXAttribute') return null;
+ const v = attr.value;
+ if (v == null) return true; // boolean attribute present (e.g. contentEditable)
+ if (v.type === 'Literal' && typeof v.value === 'string') return v.value;
+ if (
+ v.type === 'JSXExpressionContainer' &&
+ v.expression?.type === 'Literal' &&
+ typeof v.expression.value === 'string'
+ ) {
+ return v.expression.value;
+ }
+ return null;
+}
+
+/** Find a named attribute (case-insensitive on the React prop name). */
+function findAttr(openingElement, name) {
+ const lower = name.toLowerCase();
+ return openingElement.attributes.find(
+ a =>
+ a.type === 'JSXAttribute' &&
+ a.name?.type === 'JSXIdentifier' &&
+ a.name.name.toLowerCase() === lower,
+ );
+}
+
+/**
+ * Is the element this `onKeyDown` is attached to an editable surface? Returns
+ * false for buttons/links and button-ish roles even if an editable role is
+ * also present (IME can't compose on them).
+ */
+function isEditableElement(openingElement) {
+ const tag = jsxName(openingElement.name);
+ if (tag == null) return false;
+
+ const roleAttr = findAttr(openingElement, 'role');
+ const role = roleAttr ? staticAttrValue(roleAttr) : null;
+
+ // Hard non-editable: native button/anchor, or an explicit button-ish role.
+ if (NON_EDITABLE_TAGS.has(tag)) return false;
+ if (typeof role === 'string' && NON_EDITABLE_ROLES.has(role)) return false;
+
+ // Native editable tags. For <input>, exclude non-text `type`s (checkbox,
+ // number, date, …) that can't host IME composition. A dynamic/absent type is
+ // treated as composable (stays in scope).
+ if (tag === 'input') {
+ const typeAttr = findAttr(openingElement, 'type');
+ const typeVal = typeAttr ? staticAttrValue(typeAttr) : null;
+ if (
+ typeof typeVal === 'string' &&
+ NON_COMPOSABLE_INPUT_TYPES.has(typeVal)
+ ) {
+ return false;
+ }
+ return true;
+ }
+ if (tag === 'textarea') return true;
+ // Known Astryx text-input components.
+ if (EDITABLE_COMPONENTS.has(tag)) return true;
+ // contentEditable (present as boolean or ="true"/={true}).
+ const ce = findAttr(openingElement, 'contentEditable');
+ if (ce) {
+ const val = staticAttrValue(ce);
+ if (val === true || val === 'true' || val === '') return true;
+ if (
+ ce.value?.type === 'JSXExpressionContainer' &&
+ ce.value.expression?.type === 'Literal' &&
+ ce.value.expression.value === true
+ ) {
+ return true;
+ }
+ }
+ // Editable ARIA role on a non-button element.
+ if (typeof role === 'string' && EDITABLE_ROLES.has(role)) return true;
+
+ return false;
+}
+
+/**
+ * Resolve the handler NODE for an `onKeyDown` attribute value. Handles:
+ * - inline arrow/function expression
+ * - a same-file identifier bound to an arrow/function/useCallback(...) or a
+ * function declaration.
+ * Returns the node whose source text should be scanned, or null if unknown.
+ */
+function resolveHandlerNode(attrValue, context) {
+ if (!attrValue || attrValue.type !== 'JSXExpressionContainer') return null;
+ const expr = attrValue.expression;
+ if (expr == null) return null;
+
+ if (
+ expr.type === 'ArrowFunctionExpression' ||
+ expr.type === 'FunctionExpression'
+ ) {
+ return expr;
+ }
+
+ if (expr.type === 'Identifier') {
+ const sourceCode = context.sourceCode ?? context.getSourceCode();
+ const scope = sourceCode.getScope
+ ? sourceCode.getScope(expr)
+ : context.getScope();
+ const resolved = findVariable(scope, expr.name);
+ if (!resolved) return null;
+ for (const def of resolved.defs) {
+ if (def.type === 'FunctionName' && def.node) return def.node;
+ if (def.node?.type === 'VariableDeclarator' && def.node.init) {
+ return unwrapInit(def.node.init);
+ }
+ }
+ }
+ return null;
+}
+
+/** Walk a scope chain to find a variable by name. */
+function findVariable(scope, name) {
+ let current = scope;
+ while (current) {
+ const found = current.variables.find(v => v.name === name);
+ if (found) return found;
+ current = current.upper;
+ }
+ return null;
+}
+
+/**
+ * Unwrap common wrappers around a handler initializer:
+ * const h = useCallback(() => {...}, [...]) -> the inner arrow
+ * const h = () => {...} -> the arrow itself
+ */
+function unwrapInit(init) {
+ if (init == null) return null;
+ if (
+ init.type === 'ArrowFunctionExpression' ||
+ init.type === 'FunctionExpression'
+ ) {
+ return init;
+ }
+ // useCallback(fn, deps) / React.useCallback(fn, deps) — first arg is the fn.
+ if (init.type === 'CallExpression') {
+ const callee = init.callee;
+ const calleeName =
+ callee?.type === 'Identifier'
+ ? callee.name
+ : callee?.type === 'MemberExpression'
+ ? callee.property?.name
+ : null;
+ if (calleeName === 'useCallback' || calleeName === 'useMemo') {
+ const first = init.arguments?.[0];
+ if (
+ first?.type === 'ArrowFunctionExpression' ||
+ first?.type === 'FunctionExpression'
+ ) {
+ return first;
+ }
+ }
+ }
+ return null;
+}
+
+/**
+ * Does the handler source text branch on a command key? Looks for either
+ * - a `.key` comparison / switch that mentions any COMMAND_KEYS literal, or
+ * - a legacy `keyCode` / `which` read.
+ */
+function branchesOnCommandKey(text) {
+ const readsKey = /\.\s*key\b/.test(text);
+ const mentionsCommandKey = COMMAND_KEYS.some(k =>
+ new RegExp(`['"\`]${k}['"\`]`).test(text),
+ );
+ if (readsKey && mentionsCommandKey) return true;
+ // Legacy numeric key reads are themselves command-key branching.
+ if (/\.\s*(keyCode|which)\b/.test(text)) return true;
+ return false;
+}
+
+/**
+ * Lenient guard detection: any mention of a composition guard anywhere in the
+ * handler body counts. Prefer false-negatives (miss) over false-positives.
+ */
+function hasImeGuard(text) {
+ if (/\bisImeKeyEvent\s*\(/.test(text)) return true;
+ if (/\.\s*isComposing\b/.test(text)) return true;
+ if (/\bisComposing\b/.test(text)) return true;
+ if (/\b229\b/.test(text)) return true;
+ return false;
+}
+
+const rule = {
+ meta: {
+ type: 'problem',
+ docs: {
+ description:
+ 'Require an IME composition guard (isImeKeyEvent / isComposing) in an ' +
+ 'onKeyDown handler on an editable surface that branches on Enter/Escape/' +
+ 'arrow/Page/Home/End keys — otherwise CJK composition keystrokes misfire.',
+ category: 'Best Practices',
+ recommended: true,
+ url: 'https://github.com/facebook/astryx/issues/4892',
+ },
+ messages: {
+ unguardedImeKeydown:
+ 'This `onKeyDown` on an editable surface branches on a command key ' +
+ '(Enter/Escape/arrows/…) without an IME composition guard. A CJK ' +
+ 'composition keystroke fires `keydown` before `compositionend`, so it ' +
+ 'misfires this branch. Early-return on ' +
+ '`isImeKeyEvent(e.nativeEvent)` (from ' +
+ '`@astryxdesign/core/utils/ime`) before handling command keys.',
+ },
+ schema: [],
+ },
+ create(context) {
+ const filename = context.filename ?? context.getFilename();
+ // Test/story fixtures intentionally exercise raw patterns.
+ if (filename.includes('.test.') || filename.includes('.stories.')) {
+ return {};
+ }
+ const sourceCode = context.sourceCode ?? context.getSourceCode();
+
+ return {
+ JSXAttribute(node) {
+ if (
+ node.name?.type !== 'JSXIdentifier' ||
+ node.name.name !== 'onKeyDown'
+ ) {
+ return;
+ }
+ const openingElement = node.parent;
+ if (openingElement?.type !== 'JSXOpeningElement') return;
+
+ if (!isEditableElement(openingElement)) return;
+
+ const handlerNode = resolveHandlerNode(node.value, context);
+ if (handlerNode == null) return;
+
+ const text = sourceCode.getText(handlerNode);
+ if (!branchesOnCommandKey(text)) return;
+ if (hasImeGuard(text)) return;
+
+ context.report({
+ node: node,
+ messageId: 'unguardedImeKeydown',
+ });
+ },
+ };
+ },
+};
+
+export default rule;
diff --git a/internal/eslint-plugin-astryx/no-unguarded-ime-keydown.test.mjs b/internal/eslint-plugin-astryx/no-unguarded-ime-keydown.test.mjs
new file mode 100644
index 0000000000..1a36dd7aa7
--- /dev/null
+++ b/internal/eslint-plugin-astryx/no-unguarded-ime-keydown.test.mjs
@@ -0,0 +1,284 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file no-unguarded-ime-keydown.test.mjs
+ * @description Tests for the Astryx no-unguarded-ime-keydown ESLint rule.
+ */
+
+import {RuleTester} from 'eslint';
+import tseslint from 'typescript-eslint';
+import rule from './no-unguarded-ime-keydown.js';
+
+const tester = new RuleTester({
+ languageOptions: {
+ parser: tseslint.parser,
+ parserOptions: {
+ ecmaVersion: 2022,
+ sourceType: 'module',
+ ecmaFeatures: {jsx: true},
+ },
+ },
+});
+
+// RuleTester registers its own describe/it blocks internally, so it must run
+// at the top level (Vitest 4 forbids calling suite functions inside an it()).
+tester.run('no-unguarded-ime-keydown', rule, {
+ valid: [
+ // ✅ The real BaseTypeahead pattern: a same-file `handleKeyDown` that
+ // early-returns on `isImeKeyEvent(e.nativeEvent)` before the Enter
+ // switch, referenced by the input's onKeyDown.
+ {
+ code: `
+ function C() {
+ const handleKeyDown = (e) => {
+ if (isImeKeyEvent(e.nativeEvent)) {
+ return;
+ }
+ switch (e.key) {
+ case 'ArrowDown':
+ setHighlightedIndex(0);
+ break;
+ case 'Enter':
+ handleSelect();
+ break;
+ case 'Escape':
+ popover.hide();
+ break;
+ }
+ };
+ return <input onKeyDown={handleKeyDown} />;
+ }
+ `,
+ },
+
+ // ✅ Inline handler with an early `if (e.isComposing) return;` guard.
+ {
+ code: `
+ const C = () => (
+ <TextInput
+ onKeyDown={e => {
+ if (e.isComposing) return;
+ if (e.key === 'Enter') onSubmit();
+ }}
+ />
+ );
+ `,
+ },
+
+ // ✅ useCallback-wrapped handler guarded by the legacy keyCode 229 check.
+ {
+ code: `
+ function C() {
+ const handleKeyDown = useCallback(e => {
+ if (e.keyCode === 229) return;
+ if (e.key === 'Escape') close();
+ }, []);
+ return <textarea onKeyDown={handleKeyDown} />;
+ }
+ `,
+ },
+
+ // ✅ Editable surface but the handler only reads Tab — not a command key,
+ // so IME can't misfire it.
+ {
+ code: `
+ const C = () => (
+ <input
+ onKeyDown={e => {
+ if (e.key === 'Tab') advanceFocus();
+ }}
+ />
+ );
+ `,
+ },
+
+ // ✅ onKeyDown on a NON-editable button branching on Enter — IME can't run
+ // on a button, so not flagged.
+ {
+ code: `
+ const C = () => (
+ <button
+ onKeyDown={e => {
+ if (e.key === 'Enter') activate();
+ }}
+ />
+ );
+ `,
+ },
+
+ // ✅ role="button" div branching on Enter — non-editable, not flagged.
+ {
+ code: `
+ const C = () => (
+ <div
+ role="button"
+ onKeyDown={e => {
+ if (e.key === 'Enter' || e.key === 'Escape') toggle();
+ }}
+ />
+ );
+ `,
+ },
+
+ // ✅ The Selector TRIGGER shape: a <button role="combobox"> branching on
+ // command keys. role="combobox" would look editable, but a button can't
+ // host IME composition — must NOT flag.
+ {
+ code: `
+ const C = () => (
+ <button
+ role="combobox"
+ onKeyDown={e => {
+ if (e.key === 'ArrowDown' || e.key === 'Enter') openOrMove();
+ }}
+ />
+ );
+ `,
+ },
+
+ // ✅ <input type="checkbox"> branching on Enter — a checkbox can't host
+ // IME text composition, so not flagged (the SelectableCard shape).
+ {
+ code: `
+ const C = () => (
+ <input
+ type="checkbox"
+ onKeyDown={e => { if (e.key === 'Enter') toggle(); }}
+ />
+ );
+ `,
+ },
+
+ // ✅ <input type="number"> branching on arrows — non-composable type.
+ {
+ code: `
+ const C = () => (
+ <input
+ type="number"
+ onKeyDown={e => { if (e.key === 'ArrowUp') step(); }}
+ />
+ );
+ `,
+ },
+
+ // ✅ Handler not resolvable in this file (imported) — treated as unknown,
+ // not flagged.
+ {
+ code: `
+ import {handleKeyDown} from './keys';
+ const C = () => <input onKeyDown={handleKeyDown} />;
+ `,
+ },
+
+ // ✅ Test fixtures are skipped.
+ {
+ code: `
+ const C = () => (
+ <input onKeyDown={e => { if (e.key === 'Enter') go(); }} />
+ );
+ `,
+ filename: '/packages/core/src/Selector/Selector.test.tsx',
+ },
+ ],
+
+ invalid: [
+ // ❌ Inline handler on a TextInput branching on Enter, no guard.
+ {
+ code: `
+ const C = () => (
+ <TextInput onKeyDown={e => { if (e.key === 'Enter') onSelect(); }} />
+ );
+ `,
+ errors: [{messageId: 'unguardedImeKeydown'}],
+ },
+
+ // ❌ Native <input> with an identifier handler that switches on e.key
+ // Enter/Escape with no composition guard.
+ {
+ code: `
+ function C() {
+ const handleKeyDown = (e) => {
+ switch (e.key) {
+ case 'Enter':
+ submit();
+ break;
+ case 'Escape':
+ cancel();
+ break;
+ }
+ };
+ return <input onKeyDown={handleKeyDown} />;
+ }
+ `,
+ errors: [{messageId: 'unguardedImeKeydown'}],
+ },
+
+ // ❌ The real Selector shape: a TextInput (role="combobox") whose inline
+ // onKeyDown forwards Enter/Escape/arrows to onKeyDown with no guard.
+ {
+ code: `
+ const C = () => (
+ <TextInput
+ role="combobox"
+ onKeyDown={e => {
+ if (
+ e.key === 'ArrowDown' ||
+ e.key === 'ArrowUp' ||
+ e.key === 'PageUp' ||
+ e.key === 'PageDown' ||
+ e.key === 'Enter' ||
+ e.key === 'Escape'
+ ) {
+ onKeyDown(e);
+ return;
+ }
+ if (e.key === 'Tab' && (e.shiftKey || !hasQuery)) {
+ onKeyDown(e);
+ }
+ }}
+ />
+ );
+ `,
+ errors: [{messageId: 'unguardedImeKeydown'}],
+ },
+
+ // ❌ contentEditable div branching on Enter, no guard.
+ {
+ code: `
+ const C = () => (
+ <div
+ contentEditable
+ onKeyDown={e => { if (e.key === 'Enter') e.preventDefault(); }}
+ />
+ );
+ `,
+ errors: [{messageId: 'unguardedImeKeydown'}],
+ },
+
+ // ❌ role="textbox" element reading legacy keyCode without a 229 guard.
+ {
+ code: `
+ const C = () => (
+ <div
+ role="textbox"
+ onKeyDown={e => { if (e.keyCode === 13) submit(); }}
+ />
+ );
+ `,
+ errors: [{messageId: 'unguardedImeKeydown'}],
+ },
+
+ // ❌ useCallback handler on a textarea, arrow-key branch, no guard.
+ {
+ code: `
+ function C() {
+ const handleKeyDown = useCallback(e => {
+ if (e.key === 'ArrowDown') moveDown();
+ }, []);
+ return <textarea onKeyDown={handleKeyDown} />;
+ }
+ `,
+ errors: [{messageId: 'unguardedImeKeydown'}],
+ },
+ ],
+});