An open source design system that's fully customizable and agent ready
TypeScript
fix(useListFocus): consume Escape only when an onEscape was supplied (#5346)
Cindy Zhangcea9ecd17644
diff --git a/.changeset/list-focus-escape-passthrough.md b/.changeset/list-focus-escape-passthrough.mdnew file mode 100644index 0000000000..fbe283a72b--- /dev/null+++ b/.changeset/list-focus-escape-passthrough.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[fix] `useListFocus` no longer swallows Escape when no `onEscape` was supplied. The hook called `preventDefault()` on every Escape — a habit inherited from the arrow keys, which share the handler and need it to suppress page scroll — so a list with nothing to dismiss still marked the key handled, and a surrounding layer that defers to `defaultPrevented` (a focus trap, a native popover) never got its turn. Escape is now consumed only when an `onEscape` is passed. Arrow, Home and End handling is unchanged.++Behaviour change: `AvatarGroup`, `ButtonGroup`, `Outline`, `Pagination`, `SegmentedControl`, `TabList` and `Toolbar` pass no `onEscape`, so an Escape pressed inside one of them now reaches the surrounding layer and can dismiss it — the point of the fix, but a host that counted on the key stopping there will notice. `NavHeadingMenu` does the same when it renders without a menu close handler. Menus and flyouts that do pass `onEscape` are unaffected. `patch`, not `[breaking]`: the swallowing was never a contract — the hook documented Escape only as "custom callback", and no component advertised consuming the key.++@cixzhangdiff --git a/packages/core/src/Popover/Popover.test.tsx b/packages/core/src/Popover/Popover.test.tsxindex 23cab1e62f..d688d27530 100644--- a/packages/core/src/Popover/Popover.test.tsx+++ b/packages/core/src/Popover/Popover.test.tsx@@ -2,7 +2,8 @@/*** @file Popover.test.tsx- * @input Uses vitest, @testing-library/react, Popover component+ * @input Uses vitest, @testing-library/react, Popover, Dialog,+ * SegmentedControl* @output Unit tests for Popover component behavior* @position Testing; validates Popover.tsx implementation*@@ -14,6 +15,7 @@ import {render, screen, fireEvent} from '@testing-library/react';import React, {useRef} from 'react';import {Popover} from './Popover';import {Dialog} from '../Dialog';+import {SegmentedControl, SegmentedControlItem} from '../SegmentedControl';// Store original matches to restore laterconst originalMatches = HTMLElement.prototype.matches;@@ -306,6 +308,30 @@ describe('Popover', () => {expect(trigger).toHaveAttribute('aria-expanded', 'false');});+ it('dismisses on Escape pressed inside a roving-focus list', () => {+ render(+ <Popover+ content={+ <SegmentedControl value="grid" onChange={() => {}} label="View">+ <SegmentedControlItem value="grid" label="Grid" />+ <SegmentedControlItem value="list" label="List" />+ </SegmentedControl>+ }+ label="Test">+ <button type="button">Open</button>+ </Popover>,+ );+ const trigger = screen.getByRole('button', {name: 'Open'});+ fireEvent.click(trigger);+ expect(trigger).toHaveAttribute('aria-expanded', 'true');++ // From the segment, so the list's own key handler runs first. jsdom has+ // no popover display, so the open content still reads as hidden.+ const segment = screen.getByRole('radio', {name: 'Grid', hidden: true});+ fireEvent.keyDown(segment, {key: 'Escape'});+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ });+it('stays open on Escape when hasEscapeDismiss is false', () => {render(<Popoverdiff --git a/packages/core/src/hooks/useListFocus.doc.mjs b/packages/core/src/hooks/useListFocus.doc.mjsindex 5500c4a78b..8c644b3357 100644--- a/packages/core/src/hooks/useListFocus.doc.mjs+++ b/packages/core/src/hooks/useListFocus.doc.mjs@@ -36,7 +36,7 @@ export const docs = {{name: 'options.onEscape',type: '() => void',- description: 'Callback when Escape key is pressed (e.g., close menu).',+ description: 'Callback when Escape key is pressed (e.g., close menu). Supplying it also consumes the key (preventDefault); without it Escape passes through to the surrounding layer.',required: false,},{@@ -144,7 +144,7 @@ export const docsDense = {'options.itemSelector': 'selector for focusable items in list.','options.boundarySelector': "boundary selector for lists that contain nested lists (e.g. submenu flyouts); scopes items + key handling to this level.",'options.wrap': 'whether arrow navigation wraps around at ends.',- 'options.onEscape': 'callback when Escape key pressed (e.g. close menu).',+ 'options.onEscape': 'callback when Escape key pressed (e.g. close menu). Also consumes the key; without it Escape passes through to the surrounding layer.','options.orientation': "navigation orientation. 'horizontal' uses ArrowLeft/ArrowRight, 'vertical' uses ArrowUp/ArrowDown, 'both' accepts all four arrows.",'options.hasHomeEnd': 'whether Home/End jump to first/last enabled item.','options.isRtl': 'ArrowLeft/ArrowRight swap for horizontal nav (RTL). default: auto-detect from container computed direction; explicit boolean wins.',diff --git a/packages/core/src/hooks/useListFocus.test.tsx b/packages/core/src/hooks/useListFocus.test.tsxindex 2b2b1c3bfd..b0aae73040 100644--- a/packages/core/src/hooks/useListFocus.test.tsx+++ b/packages/core/src/hooks/useListFocus.test.tsx@@ -3,14 +3,14 @@/*** @file useListFocus.test.tsx* @input Uses vitest, @testing-library/react, useListFocus hook- * @output Unit tests for useListFocus disabled-item skipping, navigation, and- * RTL auto-detection+ * @output Unit tests for useListFocus disabled-item skipping, navigation,+ * Escape consumption, and RTL auto-detection* @position Testing; validates useListFocus.ts keyboard navigation** SYNC: When useListFocus.ts changes, update tests to match new behavior*/-import {describe, it, expect} from 'vitest';+import {describe, it, expect, vi} from 'vitest';import type {KeyboardEvent as ReactKeyboardEvent} from 'react';import {render, screen, fireEvent} from '@testing-library/react';import {useListFocus} from './useListFocus';@@ -525,3 +525,65 @@ describe('useListFocus boundarySelector (nested lists)', () => {expect(innerProbe).toHaveAttribute('data-owns', 'false');});});++// A list inside a host that dismisses on Escape. The host's guard mirrors+// `useFocusTrap`: it acts only on a key no inner handler has consumed.+function EscapeHost({+ onEscape,+ onHostEscape,+}: {+ onEscape?: () => void;+ onHostEscape: () => void;+}) {+ const {listRef, handleKeyDown} = useListFocus<HTMLDivElement>({onEscape});+ return (+ <div+ data-testid="host"+ onKeyDown={e => {+ if (e.key === 'Escape' && !e.defaultPrevented) {+ onHostEscape();+ }+ }}>+ <div ref={listRef} role="menu" onKeyDown={handleKeyDown}>+ <div role="menuitem" tabIndex={-1} data-testid="One">+ One+ </div>+ <div role="menuitem" tabIndex={-1} data-testid="Two">+ Two+ </div>+ </div>+ </div>+ );+}++describe('useListFocus Escape', () => {+ it('leaves Escape to the host when no onEscape is supplied', () => {+ const onHostEscape = vi.fn();+ render(<EscapeHost onHostEscape={onHostEscape} />);++ fireEvent.keyDown(screen.getByRole('menu'), {key: 'Escape'});+ expect(onHostEscape).toHaveBeenCalledTimes(1);+ });++ it('consumes Escape and runs onEscape when one is supplied', () => {+ const onEscape = vi.fn();+ const onHostEscape = vi.fn();+ render(<EscapeHost onEscape={onEscape} onHostEscape={onHostEscape} />);++ fireEvent.keyDown(screen.getByRole('menu'), {key: 'Escape'});+ expect(onEscape).toHaveBeenCalledTimes(1);+ expect(onHostEscape).not.toHaveBeenCalled();+ });++ it('still consumes arrow keys with no onEscape (page-scroll suppression)', () => {+ render(<EscapeHost onHostEscape={() => {}} />);+ screen.getByTestId('One').focus();++ // fireEvent returns false when a handler cancelled the event.+ const wasCancelled = !fireEvent.keyDown(screen.getByRole('menu'), {+ key: 'ArrowDown',+ });+ expect(wasCancelled).toBe(true);+ expect(screen.getByTestId('Two')).toHaveFocus();+ });+});diff --git a/packages/core/src/hooks/useListFocus.ts b/packages/core/src/hooks/useListFocus.tsindex 388646bb75..cdb6a491e7 100644--- a/packages/core/src/hooks/useListFocus.ts+++ b/packages/core/src/hooks/useListFocus.ts@@ -14,6 +14,8 @@** SYNC: When modified, update:* - /packages/core/src/hooks/index.ts+ * - /packages/core/src/hooks/useListFocus.doc.mjs+ * - /packages/core/src/hooks/useListFocus.test.tsx*/import {useCallback, useRef} from 'react';@@ -64,7 +66,9 @@ export interface UseListFocusOptions {wrap?: boolean;/**- * Callback when Escape key is pressed.+ * Callback when Escape key is pressed. Supplying it also makes the list+ * consume the key (`preventDefault`); without it Escape passes through to+ * the surrounding layer.*/onEscape?: () => void;@@ -277,7 +281,8 @@ function shouldDeferToCaret(target: EventTarget | null, key: string): boolean {* - ArrowUp/ArrowLeft: Move to previous item (wraps to last)* - Home: Move to first item* - End: Move to last item- * - Escape: Custom callback (e.g., close menu)+ * - Escape: runs `onEscape` and consumes the key. With no `onEscape` the key+ * is left alone, so a surrounding layer can still dismiss on it.** By default the hook only *moves* focus and leaves `tabindex` management to* the caller. Opt into {@link UseListFocusOptions.hasRovingTabIndex} for a hook@@ -557,12 +562,15 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(return;}- // Escape is handled regardless of orientation. Preserve the historical- // behavior of always consuming Escape here (preventDefault) so consumers- // that relied on it are unaffected.+ // Escape is handled regardless of orientation, but only *consumed* when+ // a handler asked for it: a list with no dismissal to perform must leave+ // the key to whatever host layer does have one, and those defer to+ // `defaultPrevented` (see `useFocusTrap`) or to the native popover.if (e.key === 'Escape') {- e.preventDefault();- onEscape?.();+ if (onEscape) {+ e.preventDefault();+ onEscape();+ }return;}