Skip to content

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

TypeScript

fix(Popover): an open popover no longer pulls in a Tab pressed elsewhere on the page (#8611)

Cindy Zhang81eeb6afad06
diff --git a/.changeset/popover-focus-region-outside-tab.md b/.changeset/popover-focus-region-outside-tab.md
new file mode 100644
index 0000000000..853cde19a1
--- /dev/null
+++ b/.changeset/popover-focus-region-outside-tab.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Popover: an open popover no longer pulls in a Tab pressed elsewhere on the page. Keyboard users can move through the rest of the page in order while a popover is open, for example a list next to a non-modal comment popover. Focus inside the popover still cycles with Tab and Shift+Tab, and Escape still closes it and returns focus to its trigger. `useFocusTrap` applies the same rule: it holds focus that is inside its container and leaves Tabs that start outside to the page. This meets `component:Popover` DEC-9. Fixes #7687.
+
+@cixzhang
diff --git a/packages/core/src/Popover/Popover.test.tsx b/packages/core/src/Popover/Popover.test.tsx
index d5c5597851..8d4b045563 100644
--- a/packages/core/src/Popover/Popover.test.tsx
+++ b/packages/core/src/Popover/Popover.test.tsx
@@ -1327,3 +1327,98 @@ describe('Popover', () => {
expect(screen.getByTestId('popover')).not.toHaveClass('consumer-popover');
});
});
+
+describe('Popover focus region (DEC-9)', () => {
+ function Page({isModal}: {isModal: boolean}) {
+ return (
+ <div>
+ <Popover
+ isModal={isModal}
+ hasCloseButton={false}
+ label="Details"
+ content={
+ <>
+ <button type="button">First inside</button>
+ <button type="button">Last inside</button>
+ </>
+ }>
+ <button type="button">Open details</button>
+ </Popover>
+ <button type="button">Elsewhere 1</button>
+ <button type="button">Elsewhere 2</button>
+ </div>
+ );
+ }
+
+ async function openDetails() {
+ const trigger = screen.getByRole('button', {name: 'Open details'});
+ // A pointer press focuses the trigger before its click opens the popover.
+ trigger.focus();
+ fireEvent.click(trigger);
+ await waitFor(() =>
+ expect(
+ screen.getByRole('button', {name: 'First inside', hidden: true}),
+ ).toHaveFocus(),
+ );
+ }
+
+ describe.each([
+ ['non-modal', false],
+ ['modal', true],
+ ])('%s', (_name, isModal) => {
+ it('leaves a Tab pressed outside the open popover to the page', async () => {
+ const user = userEvent.setup();
+ render(<Page isModal={isModal} />);
+ await openDetails();
+
+ screen.getByRole('button', {name: 'Elsewhere 1'}).focus();
+ await user.tab();
+
+ expect(screen.getByRole('button', {name: 'Elsewhere 2'})).toHaveFocus();
+ });
+
+ it('leaves a Shift+Tab pressed outside the open popover to the page', async () => {
+ const user = userEvent.setup();
+ render(<Page isModal={isModal} />);
+ await openDetails();
+
+ screen.getByRole('button', {name: 'Elsewhere 2'}).focus();
+ await user.tab({shift: true});
+
+ expect(screen.getByRole('button', {name: 'Elsewhere 1'})).toHaveFocus();
+ });
+
+ it('cycles Tab and Shift+Tab inside the open popover', async () => {
+ const user = userEvent.setup();
+ render(<Page isModal={isModal} />);
+ await openDetails();
+ const first = screen.getByRole('button', {
+ name: 'First inside',
+ hidden: true,
+ });
+ const last = screen.getByRole('button', {
+ name: 'Last inside',
+ hidden: true,
+ });
+
+ await user.tab();
+ expect(last).toHaveFocus();
+ await user.tab();
+ expect(first).toHaveFocus();
+ await user.tab({shift: true});
+ expect(last).toHaveFocus();
+ });
+
+ it('closes on Escape from inside and returns focus to the trigger', async () => {
+ const user = userEvent.setup();
+ render(<Page isModal={isModal} />);
+ await openDetails();
+
+ await user.keyboard('{Escape}');
+
+ const trigger = screen.getByRole('button', {name: 'Open details'});
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(trigger).toHaveFocus();
+ });
+ });
+});
diff --git a/packages/core/src/hooks/useFocusTrap.doc.mjs b/packages/core/src/hooks/useFocusTrap.doc.mjs
index c171432e98..8998866c02 100644
--- a/packages/core/src/hooks/useFocusTrap.doc.mjs
+++ b/packages/core/src/hooks/useFocusTrap.doc.mjs
@@ -39,7 +39,7 @@ export const docs = {
],
usage: {
description:
- 'Traps focus within a container element following the WAI-ARIA dialog focus trap pattern. Listens to focus events on the document and redirects focus back into the container if it escapes via keyboard navigation. Handles both Tab and Shift+Tab wrapping. When the trap deactivates or unmounts, focus is restored to the element that was focused before activation, unless focus was already moved elsewhere or never entered the trap (so popups that keep focus on their trigger, like comboboxes, are unaffected). Mouse clicks outside the container are not intercepted; use a light-dismiss handler for that.',
+ 'Traps focus within a container element following the WAI-ARIA dialog focus trap pattern. Listens to focus events on the document and redirects focus back into the container if a Tab from inside it moves focus out. Handles both Tab and Shift+Tab wrapping. A Tab pressed while focus is outside the container is left to the page, so an open non-modal surface never takes over the focus order of the page. When the trap deactivates or unmounts, focus is restored to the element that was focused before activation, unless focus was already moved elsewhere or never entered the trap (so popups that keep focus on their trigger, like comboboxes, are unaffected). Mouse clicks outside the container are not intercepted; use a light-dismiss handler for that.',
bestPractices: [
{ guidance: true, description: 'Call focusFirst() when opening a dialog/modal to move focus into the trapped region.' },
{ guidance: true, description: 'Provide an onEscape callback to close the dialog when Escape is pressed.' },
@@ -56,7 +56,7 @@ export const docs = {
/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
export const docsDense = {
description:
- 'Traps focus within container element following WAI-ARIA dialog focus trap pattern. Listens to document focus events + redirects focus back into container if it escapes via keyboard navigation. Handles both Tab + Shift+Tab wrapping. Mouse clicks outside container not intercepted; use light-dismiss handler for that.',
+ 'Traps focus within container element following WAI-ARIA dialog focus trap pattern. Listens to document focus events + redirects focus back into container if a Tab from inside moves focus out. Handles both Tab + Shift+Tab wrapping. Tab pressed while focus outside container left to the page. Mouse clicks outside container not intercepted; use light-dismiss handler for that.',
paramDescriptions: {
options: 'config for focus trap.',
'options.isActive': 'whether focus trap currently active.',
@@ -68,7 +68,7 @@ export const docsDense = {
},
usage: {
description:
- 'Traps focus within container element following WAI-ARIA dialog focus trap pattern. Listens to document focus events + redirects focus back into container if it escapes via keyboard navigation. Handles both Tab + Shift+Tab wrapping. On deactivate/unmount, restores focus to the element focused before activation unless focus already moved elsewhere or never entered the trap. Mouse clicks outside container not intercepted; use light-dismiss handler for that.',
+ 'Traps focus within container element following WAI-ARIA dialog focus trap pattern. Listens to document focus events + redirects focus back into container if a Tab from inside moves focus out. Handles both Tab + Shift+Tab wrapping. Tab pressed while focus outside container left to the page. On deactivate/unmount, restores focus to the element focused before activation unless focus already moved elsewhere or never entered the trap. Mouse clicks outside container not intercepted; use light-dismiss handler for that.',
bestPractices: [
{ guidance: true, description: 'Call focusFirst() when opening dialog/modal to move focus into trapped region.' },
{ guidance: true, description: 'Provide onEscape callback to close dialog when Escape pressed.' },
diff --git a/packages/core/src/hooks/useFocusTrap.test.tsx b/packages/core/src/hooks/useFocusTrap.test.tsx
index e40b340180..aa5622e051 100644
--- a/packages/core/src/hooks/useFocusTrap.test.tsx
+++ b/packages/core/src/hooks/useFocusTrap.test.tsx
@@ -256,6 +256,70 @@ describe('useFocusTrap tabbable model (infra-8)', () => {
expect(screen.getByTestId('outside')).not.toHaveFocus();
});
+ it('leaves Tab alone when focus is outside a trap with tabbable controls', () => {
+ render(
+ <Trap>
+ <button type="button" data-testid="inside">
+ Inside
+ </button>
+ </Trap>,
+ );
+ const outside = screen.getByTestId('outside');
+ const next = screen.getByTestId('focus-first');
+ outside.focus();
+
+ // The browser moves focus on to the next page control after an unhandled
+ // Tab; the trap must not pull that focus into itself.
+ expect(fireEvent.keyDown(outside, {key: 'Tab'})).toBe(true);
+ next.focus();
+
+ expect(next).toHaveFocus();
+ expect(screen.getByTestId('inside')).not.toHaveFocus();
+ });
+
+ it('wraps Tab from an SVG control that is the last tabbable inside the trap', () => {
+ render(
+ <Trap>
+ <button type="button" data-testid="first">
+ First
+ </button>
+ <svg tabIndex={0} data-testid="svg-control" aria-label="Chart point">
+ <circle r={4} />
+ </svg>
+ </Trap>,
+ );
+ const svgControl = screen.getByTestId('svg-control');
+ (svgControl as unknown as SVGElement).focus();
+ expect(svgControl).toHaveFocus();
+
+ expect(fireEvent.keyDown(svgControl, {key: 'Tab'})).toBe(false);
+ expect(screen.getByTestId('first')).toHaveFocus();
+ });
+
+ it('pulls focus back in when a Tab from inside leaves the trap', () => {
+ render(
+ <Trap>
+ <button type="button" data-testid="first">
+ First
+ </button>
+ <button type="button" data-testid="inside">
+ Inside
+ </button>
+ </Trap>,
+ );
+ const first = screen.getByTestId('first');
+ first.focus();
+
+ // A Tab the trap does not wrap itself, where focus still leaves the
+ // container: the escaped focus is redirected back inside.
+ fireEvent.keyDown(first, {key: 'Tab'});
+ screen.getByTestId('focus-first').focus();
+
+ expect(screen.getByTestId('trap')).toContainElement(
+ document.activeElement as HTMLElement,
+ );
+ });
+
it('leaves Tab alone when focus is outside a trap with no tabbable controls', () => {
render(
<Trap>
diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.ts
index ed30f086e7..fb0a22df24 100644
--- a/packages/core/src/hooks/useFocusTrap.ts
+++ b/packages/core/src/hooks/useFocusTrap.ts
@@ -425,18 +425,25 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(
}
if (event.key === 'Tab') {
- // Mark that keyboard navigation is happening
+ const active = doc.activeElement;
+ // Any focused node counts, not only HTML elements: an SVG control
+ // inside the container is still inside.
+ if (active == null || !container.contains(active)) {
+ // The trap contains focus that is inside it; it does not pull in a
+ // Tab pressed elsewhere on the page. A layer can be open while focus
+ // legitimately sits outside it — a listbox popup anchored to its own
+ // input, a non-modal popover beside the content it annotates — and
+ // capturing that Tab would take the rest of the page away from
+ // keyboard users.
+ return;
+ }
+
+ // Mark that keyboard navigation is leaving from inside the trap, so a
+ // focus that lands outside is redirected back in.
isKeyboardNavigationRef.current = true;
const focusable = getFocusableElements(container);
if (focusable.length === 0) {
- const active = doc.activeElement;
- if (!isHTMLElement(active) || !container.contains(active)) {
- // A layer can be open while focus legitimately sits outside it —
- // a listbox popup anchored to its own input. Cancelling there
- // would take Tab away from the whole page.
- return;
- }
// There is nowhere to advance to. Keep focus on the current
// programmatic target (for example a dialog panel with tabIndex=-1)
// rather than allowing the browser to move into background content.