Skip to content

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

TypeScript

fix(Popover): initial focus lands within the opening tap, and focus set in onShow is kept (#9606)

Cindy Zhange70d5dc7a305
diff --git a/.changeset/popover-initial-focus-in-gesture.md b/.changeset/popover-initial-focus-in-gesture.md
new file mode 100644
index 0000000000..c11f40e19f
--- /dev/null
+++ b/.changeset/popover-initial-focus-in-gesture.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `Popover` and `usePopover`: in the anchored presentation, initial focus now lands within the tap or click that opens the popover, so on iOS a text or number field in it raises the on-screen keyboard at once. Focus that `onShow` moves inside the popover is no longer pulled back to the first control.
+
+@cixzhang @HelloOjasMutreja
diff --git a/docs/specs/components/Popover/Popover.spec.md b/docs/specs/components/Popover/Popover.spec.md
index 704d1f568e..a92a2cca5c 100644
--- a/docs/specs/components/Popover/Popover.spec.md
+++ b/docs/specs/components/Popover/Popover.spec.md
@@ -347,18 +347,19 @@ consumers that need distinct theme reachability provide and document an owned
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
-| Public boundary, FR1 | `Popover.test.tsx` compile-time public-surface assertions plus package/barrel inspection | Unchanged public signatures and same-gesture rejection across Popover-family openings | A public type changes or a same-gesture request reaches visibility state. | `audit:Popover/api` |
-| FR2, AR2–AR4 | `Popover.test.tsx` focus/role suites and `useFocusTrap.test.tsx` container-entry suites | Pointer, keyboard/AT-style, read-only, neutral role, no autofocus, controlled, Tab/Shift+Tab, Escape, focus return | Changing semantic destination by modality, selecting fallback close initially, losing shared indication, or allowing focus escape fails assertions. | `audit:Popover/accessibility` |
-| AR3, DEC-9 | `useFocusTrap.test.tsx` and `Popover.test.tsx` focus-region suites | Modal and non-modal; Tab and Shift+Tab inside the popup and from a control outside it | A Tab outside that the popup pulls into itself, or a Tab inside that leaves it, fails assertions. | `audit:Popover/accessibility` |
-| ORD2, FR4 | `Popover.test.tsx` sizing/overflow suites; `Popover.stories.tsx` match-trigger and overflow scenarios; geometry under `Core/Layer` viewport-inset stories | Explicit width clamped to the viewport, trigger matching, fitting and overflowing content | Reversing width precedence, capping to the span beside the trigger, or always enabling scroll fails emitted-style or overflow assertions. | `audit:Popover/layout` |
-| FR8 | `Popover.test.tsx` surface-padding suite | Default rung, `0`, an explicit rung, a direct hook composition with and without a rung | A default other than step 3, a rung landing on a box inside the surface, or the hook painting a rung it was not given fails the suite. | `audit:Popover/theming` |
-| FR9 | `spec:AST-094` verification for FR31 and FR35 | Under a finger: open, close, a touch during growth; a mouse | A Popover that does not grow from and shrink into its trigger, a changed dismissal, or a changed mouse path fails. | `audit:Popover/behavior` |
-| FR5 | `Popover.test.tsx` scheduling and observer-lifecycle suites | Closed, opened, repeated signals, cleanup | Constructing observers while closed or measuring more than once per pending frame fails lifecycle assertions. | `audit:Popover/resources` |
-| FR6, FR7 and theming anatomy | `Popover.test.tsx`, `Popover.doc.mjs`, `usePopover.doc.mjs`, `astryx theme targets Popover --json`, and `scripts/check-knowledge.mjs` | One real surface with canonical `popover` plus composed-component refinements | A fake anatomy part, missing canonical output, or an active target without a real owner fails review or validation. | `audit:Popover/theming` |
-| AR5 | `Popover.stories.tsx` manual-AT fixture and PR #5373 test record | Read-only dialog manual-AT fixture; no recorded NVDA/VoiceOver announcement result | A fixture without recorded AT/browser observations cannot be cited as announcement proof. | `audit:Popover/at-evidence` |
-| Presentation (DEC-6, DEC-8) | `PopoverPresentation.test.tsx` | Default on a phone, adaptive on a phone and a desktop, forced sheet, close, controlled, dismissal mapping | A sheet on a default phone popover, an anchored popover where the sheet is asked for, or a trigger state that ignores the sheet fails. | `audit:Popover/api` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
+| Public boundary, FR1 | `Popover.test.tsx` compile-time public-surface assertions plus package/barrel inspection | Unchanged public signatures and same-gesture rejection across Popover-family openings | A public type changes or a same-gesture request reaches visibility state. | `audit:Popover/api` |
+| FR2, AR2–AR4 | `Popover.test.tsx` focus/role suites and `useFocusTrap.test.tsx` container-entry suites | Pointer, keyboard/AT-style, read-only, neutral role, no autofocus, controlled, Tab/Shift+Tab, Escape, focus return | Changing semantic destination by modality, selecting fallback close initially, losing shared indication, or allowing focus escape fails assertions. | `audit:Popover/accessibility` |
+| FR2, user activation | `Popover.test.tsx` "focuses the first content control within the click that opens it" and "keeps focus that onShow moves inside the popover"; real Chromium with mobile (touch) emulation | A tap or click opens a popover whose content is mounted: initial focus lands within that event (iOS raises its on-screen keyboard only for a focus made while the tap is handled); focus that `onShow` or a press placed inside is kept | Initial focus that waits for a later frame, or a frame that moves focus already inside the popover, fails assertions. | `audit:Popover/accessibility` |
+| AR3, DEC-9 | `useFocusTrap.test.tsx` and `Popover.test.tsx` focus-region suites | Modal and non-modal; Tab and Shift+Tab inside the popup and from a control outside it | A Tab outside that the popup pulls into itself, or a Tab inside that leaves it, fails assertions. | `audit:Popover/accessibility` |
+| ORD2, FR4 | `Popover.test.tsx` sizing/overflow suites; `Popover.stories.tsx` match-trigger and overflow scenarios; geometry under `Core/Layer` viewport-inset stories | Explicit width clamped to the viewport, trigger matching, fitting and overflowing content | Reversing width precedence, capping to the span beside the trigger, or always enabling scroll fails emitted-style or overflow assertions. | `audit:Popover/layout` |
+| FR8 | `Popover.test.tsx` surface-padding suite | Default rung, `0`, an explicit rung, a direct hook composition with and without a rung | A default other than step 3, a rung landing on a box inside the surface, or the hook painting a rung it was not given fails the suite. | `audit:Popover/theming` |
+| FR9 | `spec:AST-094` verification for FR31 and FR35 | Under a finger: open, close, a touch during growth; a mouse | A Popover that does not grow from and shrink into its trigger, a changed dismissal, or a changed mouse path fails. | `audit:Popover/behavior` |
+| FR5 | `Popover.test.tsx` scheduling and observer-lifecycle suites | Closed, opened, repeated signals, cleanup | Constructing observers while closed or measuring more than once per pending frame fails lifecycle assertions. | `audit:Popover/resources` |
+| FR6, FR7 and theming anatomy | `Popover.test.tsx`, `Popover.doc.mjs`, `usePopover.doc.mjs`, `astryx theme targets Popover --json`, and `scripts/check-knowledge.mjs` | One real surface with canonical `popover` plus composed-component refinements | A fake anatomy part, missing canonical output, or an active target without a real owner fails review or validation. | `audit:Popover/theming` |
+| AR5 | `Popover.stories.tsx` manual-AT fixture and PR #5373 test record | Read-only dialog manual-AT fixture; no recorded NVDA/VoiceOver announcement result | A fixture without recorded AT/browser observations cannot be cited as announcement proof. | `audit:Popover/at-evidence` |
+| Presentation (DEC-6, DEC-8) | `PopoverPresentation.test.tsx` | Default on a phone, adaptive on a phone and a desktop, forced sheet, close, controlled, dismissal mapping | A sheet on a default phone popover, an anchored popover where the sheet is asked for, or a trigger state that ignores the sheet fails. | `audit:Popover/api` |
## Decision log
diff --git a/packages/core/src/Popover/Popover.test.tsx b/packages/core/src/Popover/Popover.test.tsx
index 25d8ed8424..13369c1547 100644
--- a/packages/core/src/Popover/Popover.test.tsx
+++ b/packages/core/src/Popover/Popover.test.tsx
@@ -33,7 +33,7 @@ import {
import userEvent from '@testing-library/user-event';
import * as stylex from '@stylexjs/stylex';
import {readFileSync} from 'node:fs';
-import React, {useRef} from 'react';
+import React, {useRef, useState} from 'react';
import {createPortal} from 'react-dom';
import {Popover} from './Popover';
import {usePopover} from './usePopover';
@@ -874,6 +874,119 @@ describe('Popover', () => {
);
});
+ // iOS raises its keyboard only for a focus made while the browser still
+ // handles the tap, so initial focus lands within the opening event, not a
+ // frame later.
+ it('focuses the first content control within the click that opens it', () => {
+ const frames: FrameRequestCallback[] = [];
+ vi.stubGlobal(
+ 'requestAnimationFrame',
+ (callback: FrameRequestCallback) => {
+ frames.push(callback);
+ return frames.length;
+ },
+ );
+ vi.stubGlobal('cancelAnimationFrame', () => {});
+ try {
+ render(
+ <Popover content={<input aria-label="Discount" />} label="Discount">
+ <button type="button">Open discount</button>
+ </Popover>,
+ );
+
+ act(() => {
+ fireEvent.click(screen.getByRole('button', {name: 'Open discount'}), {
+ detail: 1,
+ });
+ });
+
+ // No frame has run.
+ expect(
+ screen.getByRole('textbox', {name: 'Discount', hidden: true}),
+ ).toHaveFocus();
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it('still focuses the content when the opening handler swaps it in', async () => {
+ function Swapped() {
+ const [mode, setMode] = useState<'view' | 'edit'>('view');
+ const popover = usePopover({dialogLabel: 'Details'});
+ return (
+ <>
+ <button
+ type="button"
+ ref={popover.triggerRef}
+ {...popover.triggerProps}
+ onClick={() => {
+ setMode('edit');
+ popover.show();
+ }}>
+ Edit details
+ </button>
+ {popover.render(
+ mode === 'view' ? (
+ <button type="button">View</button>
+ ) : (
+ <input aria-label="Name" />
+ ),
+ )}
+ </>
+ );
+ }
+ render(<Swapped />);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Edit details'}), {
+ detail: 1,
+ });
+
+ await waitFor(() =>
+ expect(
+ screen.getByRole('textbox', {name: 'Name', hidden: true}),
+ ).toHaveFocus(),
+ );
+ });
+
+ it('keeps focus that onShow moves inside the popover', async () => {
+ function Fields() {
+ const secondRef = useRef<HTMLInputElement>(null);
+ const popover = usePopover({
+ dialogLabel: 'Fields',
+ onShow: () => secondRef.current?.focus(),
+ });
+ return (
+ <>
+ <button
+ type="button"
+ ref={popover.triggerRef}
+ {...popover.triggerProps}
+ onClick={popover.toggle}>
+ Open fields
+ </button>
+ {popover.render(
+ <>
+ <input aria-label="First" />
+ <input aria-label="Second" ref={secondRef} />
+ </>,
+ )}
+ </>
+ );
+ }
+ render(<Fields />);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Open fields'}), {
+ detail: 1,
+ });
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 50));
+ });
+
+ expect(
+ screen.getByRole('textbox', {name: 'Second', hidden: true}),
+ ).toHaveFocus();
+ });
+
it('focuses the dialog container when content has no controls', async () => {
render(
<Popover content={<span>Read-only content</span>} label="Read only">
@@ -964,6 +1077,76 @@ describe('Popover', () => {
expect(trigger).toHaveFocus();
});
+ it('leaves focus on a control inside that took it before the first frame', () => {
+ // Auto-focus waits a frame for content that is not mounted yet. Focus an
+ // app or a press put on a later control in that frame is not the first
+ // control's to take back.
+ const frames = new Map<number, FrameRequestCallback>();
+ let nextFrame = 0;
+ vi.stubGlobal(
+ 'requestAnimationFrame',
+ (callback: FrameRequestCallback) => {
+ nextFrame += 1;
+ frames.set(nextFrame, callback);
+ return nextFrame;
+ },
+ );
+ vi.stubGlobal('cancelAnimationFrame', (frame: number) => {
+ frames.delete(frame);
+ });
+ try {
+ render(
+ <Popover
+ content={
+ <>
+ <button type="button">First</button>
+ <button type="button" data-testid="second">
+ Second
+ </button>
+ </>
+ }
+ label="Test">
+ <button type="button">Open</button>
+ </Popover>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Open'}));
+
+ const second = screen.getByTestId('second');
+ second.focus();
+ for (const callback of [...frames.values()]) {
+ callback(0);
+ }
+
+ expect(second).toHaveFocus();
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it('still moves focus to the first control when focus is not inside', async () => {
+ render(
+ <Popover
+ content={
+ <>
+ <button type="button">First</button>
+ <button type="button">Second</button>
+ </>
+ }
+ label="Test">
+ <button type="button">Open</button>
+ </Popover>,
+ );
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ trigger.focus();
+ fireEvent.click(trigger);
+
+ await waitFor(() =>
+ expect(
+ screen.getByRole('button', {name: 'First', hidden: true}),
+ ).toHaveFocus(),
+ );
+ });
+
it('does not move focus into a popover that closed before its first frame', () => {
// Auto-focus waits a frame for the content to mount. A popover dismissed
// within that frame must not pull focus into its hidden content.
diff --git a/packages/core/src/Popover/usePopover.tsx b/packages/core/src/Popover/usePopover.tsx
index 79ad089a6e..8a2ac8db62 100644
--- a/packages/core/src/Popover/usePopover.tsx
+++ b/packages/core/src/Popover/usePopover.tsx
@@ -19,7 +19,7 @@
import React, {useCallback, useEffect, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {useLayer, type ContextRenderProps} from '../Layer/useLayer';
-import {useFocusTrap} from '../hooks/useFocusTrap';
+import {useFocusTrapInternal} from '../hooks/useFocusTrap';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
import type {StyleXStyles} from '@stylexjs/stylex';
import {
@@ -34,6 +34,7 @@ import {rtlStyles} from '../utils';
import {useDevWarning} from '../hooks/useDevWarning';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {mergeProps} from '../utils/mergeProps';
+import {isFocusDetached} from '../utils/focusReturn';
import {themeProps} from '../utils/themeProps';
import {paddingStyles} from '../Layout/padding.stylex';
import type {SpacingStep} from '../utils/types';
@@ -422,28 +423,51 @@ function usePopoverImplementation(
// Track whether to skip auto-focus for the current open event
const skipAutoFocusRef = useRef(false);
+ // Whether `show` focused a content control within the opening event.
+ const hasFocusedInGestureRef = useRef(false);
+
+ // Set when the layer reports it has shown, so `show` can tell a popover
+ // that opened within the call from one whose content mounts later.
+ const hasShownRef = useRef(false);
+ const handleLayerShow = useCallback(() => {
+ hasShownRef.current = true;
+ onShow?.();
+ }, [onShow]);
// Core layer for popover positioning
const layer = useLayer({
mode: 'context',
lightDismiss: hasLightDismiss,
- onShow,
+ onShow: handleLayerShow,
onHide,
});
// Focus trap for the popover content. Escape stays registered while light
// dismiss is on (native popover="auto" closes on Escape regardless), so a
// host Dialog keeps deferring to this trap instead of double-dismissing.
- const {containerRef: contentRef, focusFirst} = useFocusTrap<HTMLDivElement>({
- isActive: layer.isOpen,
- onEscape: hasEscapeDismiss || hasLightDismiss ? layer.hide : undefined,
- });
+ // The element focused when `show` ran: initial focus may move inside before
+ // the trap activates, so the trap restores focus here instead.
+ const openerRef = useRef<HTMLElement | null>(null);
+ const getRestoreTarget = useCallback(() => openerRef.current, []);
+ const {containerRef: contentRef, focusFirst} =
+ useFocusTrapInternal<HTMLDivElement>({
+ isActive: layer.isOpen,
+ onEscape: hasEscapeDismiss || hasLightDismiss ? layer.hide : undefined,
+ getRestoreTarget,
+ });
const focusInitialTarget = useCallback(() => {
const container = contentRef.current;
if (!container) {
return;
}
+ // Focus already on a control inside (set in `onShow`, or a press in the
+ // content) is where the user or the caller wants it; moving it would
+ // undo that.
+ const active = container.ownerDocument.activeElement;
+ if (active != null && active !== container && container.contains(active)) {
+ return;
+ }
if (focusFirstContentControl(container)) {
return;
}
@@ -459,16 +483,23 @@ function usePopoverImplementation(
// Reset the per-open focus preference after the popover closes.
if (!layer.isOpen) {
skipAutoFocusRef.current = false;
+ hasFocusedInGestureRef.current = false;
return;
}
if (hasAutoFocus && !skipAutoFocusRef.current) {
// Wait a frame so the content is mounted. A popover that closes or
// unmounts first cancels it: the frame would otherwise move focus into
// content that is no longer shown, after the close had left it alone.
- const frame = requestAnimationFrame(focusInitialTarget);
+ const frame = requestAnimationFrame(() => {
+ const doc = contentRef.current?.ownerDocument ?? document;
+ if (hasFocusedInGestureRef.current && !isFocusDetached(doc)) {
+ return;
+ }
+ focusInitialTarget();
+ });
return () => cancelAnimationFrame(frame);
}
- }, [layer.isOpen, hasAutoFocus, focusInitialTarget]);
+ }, [layer.isOpen, hasAutoFocus, focusInitialTarget, contentRef]);
// Combined ref for trigger element (layer anchor + our ref). It is keyed on
// the layer's own ref, not the whole layer: the layer object changes with
@@ -490,9 +521,40 @@ function usePopoverImplementation(
const show = useCallback(
(showOptions?: {skipAutoFocus?: boolean}) => {
skipAutoFocusRef.current = showOptions?.skipAutoFocus ?? false;
+ hasShownRef.current = false;
+ const activeElement = (
+ triggerElementRef.current?.ownerDocument ?? document
+ ).activeElement as HTMLElement | null;
+ openerRef.current =
+ activeElement != null && !contentRef.current?.contains(activeElement)
+ ? activeElement
+ : null;
layer.show();
+ // When the content is already mounted, the layer shows it within this
+ // call, so initial focus lands within the event that opened it: iOS
+ // raises its keyboard only for a focus made while the tap is still
+ // being handled. The frame in the effect above stays for content that
+ // mounts later.
+ // Only a content control already rendered takes focus here; content
+ // that renders on open (and the dialog-surface fallback) waits for the
+ // effect's frame.
+ const container = contentRef.current;
+ if (
+ hasShownRef.current &&
+ hasAutoFocus &&
+ !skipAutoFocusRef.current &&
+ container != null &&
+ !container.contains(container.ownerDocument.activeElement) &&
+ focusFirstContentControl(container)
+ ) {
+ // Initial focus is done. The effect's frame stays only as a fallback
+ // for focus lost to the page (content swapped in the same handler
+ // unmounts the control just focused); it must not move focus the user
+ // has since moved elsewhere.
+ hasFocusedInGestureRef.current = true;
+ }
},
- [layer],
+ [layer, hasAutoFocus, contentRef],
);
// Toggle function. Opening delegates to show so every route inherits the
diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.ts
index 5a82d4e40f..9e9203f116 100644
--- a/packages/core/src/hooks/useFocusTrap.ts
+++ b/packages/core/src/hooks/useFocusTrap.ts
@@ -228,7 +228,29 @@ export interface UseFocusTrapReturn<T extends HTMLElement = HTMLElement> {
export function useFocusTrap<T extends HTMLElement = HTMLElement>(
options: UseFocusTrapOptions,
): UseFocusTrapReturn<T> {
- const {isActive, onEscape} = options;
+ return useFocusTrapInternal<T>(options);
+}
+
+/**
+ * Package-internal options. Not re-exported from the package entry point.
+ */
+interface InternalFocusTrapOptions extends UseFocusTrapOptions {
+ /**
+ * The element to restore focus to on deactivation, read at activation. For
+ * an overlay that may move focus inside before the trap activates (initial
+ * focus within the opening event), the element focused at activation is
+ * already inside, so the overlay names its opener instead. Returning `null`
+ * falls back to the element focused at activation.
+ */
+ getRestoreTarget?: () => HTMLElement | null;
+}
+
+export function useFocusTrapInternal<T extends HTMLElement = HTMLElement>(
+ options: InternalFocusTrapOptions,
+): UseFocusTrapReturn<T> {
+ const {isActive, onEscape, getRestoreTarget} = options;
+ const getRestoreTargetRef = useRef(getRestoreTarget);
+ getRestoreTargetRef.current = getRestoreTarget;
const containerRef = useRef<T | null>(null);
const lastFocusRef = useRef<Element | null>(null);
@@ -302,7 +324,9 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(
// Snapshot the container now; by cleanup it may be detached or unmounted.
const container = containerRef.current;
const doc = trapDocument(container);
- const previouslyFocused = doc.activeElement as HTMLElement | null;
+ const previouslyFocused =
+ getRestoreTargetRef.current?.() ??
+ (doc.activeElement as HTMLElement | null);
// Whether focus ever entered the trap container while it was active.
// Initialized from the current active element in case focus was already