Skip to content

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

TypeScript

fix(overlays): topmost-only Escape dismissal + IME composition guard (#3357)

Cindy Zhang8796e0f4319d
diff --git a/.changeset/escape-stack-ime-guard.md b/.changeset/escape-stack-ime-guard.md
new file mode 100644
index 0000000000..b0cc395bc3
--- /dev/null
+++ b/.changeset/escape-stack-ime-guard.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Escape now dismisses only the top-most open layer instead of closing every open layer at once — a popover or menu nested inside a Dialog no longer closes both on a single Escape press. Also guards against IME composition: pressing Escape to cancel a CJK/IME composition inside a Dialog or popover no longer closes the overlay (#3343).
+@cixzhang
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index a497aa04f5..0976150032 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -20,6 +20,7 @@ import {useEffect, useMemo, useRef, type ReactNode} from 'react';
import type {BaseProps} from '../BaseProps';
import * as stylex from '@stylexjs/stylex';
import {useScrollLock} from '../hooks/useScrollLock';
+import {hasActiveFocusTrapEscape, isImeKeyEvent} from '../hooks/useFocusTrap';
import {
colorVars,
radiusVars,
@@ -422,6 +423,12 @@ export function Dialog({
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
+ // Ignore IME composition-cancel, and defer to any popover/menu layered
+ // on top of this dialog so a single Escape closes only the top-most
+ // layer (the popover's own focus trap handles it and stops propagation).
+ if (isImeKeyEvent(event) || hasActiveFocusTrapEscape()) {
+ return;
+ }
event.preventDefault();
if (allowEscape) {
onOpenChange(false);
@@ -447,6 +454,11 @@ export function Dialog({
// Handle native cancel event (browser Escape handling)
const handleCancel = (event: React.SyntheticEvent<HTMLDialogElement>) => {
event.preventDefault();
+ // Defer to a popover/menu layered on top of this dialog; it will dismiss
+ // itself on the same Escape press.
+ if (hasActiveFocusTrapEscape()) {
+ return;
+ }
if (allowEscape) {
onOpenChange(false);
}
diff --git a/packages/core/src/hooks/useFocusTrap.test.tsx b/packages/core/src/hooks/useFocusTrap.test.tsx
index b7c95258c1..3042dff994 100644
--- a/packages/core/src/hooks/useFocusTrap.test.tsx
+++ b/packages/core/src/hooks/useFocusTrap.test.tsx
@@ -3,13 +3,13 @@
/**
* @file useFocusTrap.test.tsx
* @input Uses vitest, @testing-library/react, useFocusTrap hook
- * @output Unit tests for useFocusTrap tabbable-element model
- * @position Testing; validates useFocusTrap.ts focusable detection
+ * @output Unit tests for useFocusTrap tabbable-element model + Escape/IME guard
+ * @position Testing; validates useFocusTrap.ts focusable detection + dismissal coordination
*
* SYNC: When useFocusTrap.ts changes, update tests to match new behavior
*/
-import {describe, it, expect} from 'vitest';
+import {describe, it, expect, vi} from 'vitest';
import {render, screen, fireEvent} from '@testing-library/react';
import {useFocusTrap} from './useFocusTrap';
@@ -32,6 +32,23 @@ function Trap({children}: {children: React.ReactNode}) {
);
}
+function EscapeTrap({
+ isActive,
+ onEscape,
+ label,
+}: {
+ isActive: boolean;
+ onEscape: () => void;
+ label: string;
+}) {
+ const {containerRef} = useFocusTrap<HTMLDivElement>({isActive, onEscape});
+ return (
+ <div ref={containerRef} data-testid={label}>
+ <button type="button">{label}-btn</button>
+ </div>
+ );
+}
+
describe('useFocusTrap tabbable model (infra-8)', () => {
it('treats a contenteditable as focusable (focusFirst lands on it)', () => {
render(
@@ -66,3 +83,50 @@ describe('useFocusTrap tabbable model (infra-8)', () => {
expect(screen.getByTestId('real-btn')).toHaveFocus();
});
});
+
+describe('useFocusTrap Escape coordination', () => {
+ it('calls onEscape for a single active trap', () => {
+ const onEscape = vi.fn();
+ render(<EscapeTrap isActive onEscape={onEscape} label="only" />);
+ fireEvent.keyDown(document, {key: 'Escape'});
+ expect(onEscape).toHaveBeenCalledTimes(1);
+ });
+
+ it('only the top-most trap responds to Escape when nested', () => {
+ const outer = vi.fn();
+ const inner = vi.fn();
+ render(
+ <>
+ <EscapeTrap isActive onEscape={outer} label="outer" />
+ <EscapeTrap isActive onEscape={inner} label="inner" />
+ </>,
+ );
+ // The most recently activated trap (inner) is on top.
+ fireEvent.keyDown(document, {key: 'Escape'});
+ expect(inner).toHaveBeenCalledTimes(1);
+ expect(outer).not.toHaveBeenCalled();
+ });
+
+ it('ignores Escape during IME composition', () => {
+ const onEscape = vi.fn();
+ render(<EscapeTrap isActive onEscape={onEscape} label="ime" />);
+ fireEvent.keyDown(document, {key: 'Escape', isComposing: true});
+ expect(onEscape).not.toHaveBeenCalled();
+ // keyCode 229 (composition) is also ignored
+ fireEvent.keyDown(document, {key: 'Escape', keyCode: 229});
+ expect(onEscape).not.toHaveBeenCalled();
+ // a normal Escape still works
+ fireEvent.keyDown(document, {key: 'Escape'});
+ expect(onEscape).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not respond after the trap is deactivated', () => {
+ const onEscape = vi.fn();
+ const {rerender} = render(
+ <EscapeTrap isActive onEscape={onEscape} label="toggle" />,
+ );
+ rerender(<EscapeTrap isActive={false} onEscape={onEscape} label="toggle" />);
+ fireEvent.keyDown(document, {key: 'Escape'});
+ expect(onEscape).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.ts
index 0980deed20..13c91d7af3 100644
--- a/packages/core/src/hooks/useFocusTrap.ts
+++ b/packages/core/src/hooks/useFocusTrap.ts
@@ -19,6 +19,56 @@ import {useCallback, useEffect, useRef} from 'react';
import {FOCUSABLE_SELECTOR} from './focusableSelector';
+/**
+ * Module-level stack of active focus-trap Escape handlers.
+ *
+ * Every active `useFocusTrap` used to attach its own document-level `keydown`
+ * listener with no coordination, so a single Escape press closed *every* open
+ * layer at once (e.g. a popover nested inside a Dialog closed both). Tracking
+ * traps in a shared stack lets only the most recently activated (top-most)
+ * trap respond to Escape.
+ */
+const escapeStack: (() => void)[] = [];
+
+function pushEscapeHandler(handler: () => void): void {
+ escapeStack.push(handler);
+}
+
+function removeEscapeHandler(handler: () => void): void {
+ const index = escapeStack.lastIndexOf(handler);
+ if (index !== -1) {
+ escapeStack.splice(index, 1);
+ }
+}
+
+function isTopEscapeHandler(handler: () => void): boolean {
+ return escapeStack[escapeStack.length - 1] === handler;
+}
+
+/**
+ * Whether any focus-trap Escape handler is currently active (i.e. a popover
+ * layer is open). Other overlay primitives that manage their own Escape (e.g.
+ * Dialog) can consult this to defer to a popover layered on top of them,
+ * giving topmost-only dismissal until a full layer stack exists.
+ */
+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,
@@ -222,6 +272,16 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(
return;
}
+ // Register this trap on the shared Escape stack so only the top-most
+ // active trap responds to Escape. A stable identity per active period is
+ // enough — we push on activate and remove on cleanup.
+ const escapeHandler = () => {
+ onEscape?.();
+ };
+ if (onEscape) {
+ pushEscapeHandler(escapeHandler);
+ }
+
const handleKeyDown = (event: KeyboardEvent) => {
const container = containerRef.current;
if (!container) {
@@ -229,7 +289,19 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(
}
if (event.key === 'Escape' && onEscape) {
+ // Ignore Escape that is cancelling an IME composition, already handled
+ // by a nested handler, or not targeting the top-most trap.
+ if (
+ event.defaultPrevented ||
+ isImeKeyEvent(event) ||
+ !isTopEscapeHandler(escapeHandler)
+ ) {
+ return;
+ }
+ // Mark handled and stop propagation so an outer layer (e.g. a Dialog
+ // hosting this popover) does not also dismiss on the same press.
event.preventDefault();
+ event.stopPropagation();
onEscape();
return;
}
@@ -266,6 +338,9 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(
return () => {
document.removeEventListener('keydown', handleKeyDown);
+ if (onEscape) {
+ removeEscapeHandler(escapeHandler);
+ }
};
}, [isActive, onEscape]);