An open source design system that's fully customizable and agent ready
TypeScript
fix(Popover): cancel the auto-focus frame when the popover closes first (#8276)
Christopher Chedeaua6740a73880e
diff --git a/.changeset/popover-cancel-stale-autofocus.md b/.changeset/popover-cancel-stale-autofocus.mdnew file mode 100644index 0000000000..04ac4434bf--- /dev/null+++ b/.changeset/popover-cancel-stale-autofocus.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] usePopover: a popover that closes or unmounts before its first frame no longer moves focus into its hidden content. Auto-focus waits a frame for the content to mount, and that frame is now cancelled with the open, so pressing Escape right after opening a Popover or a collapsed SideNav submenu leaves focus on the trigger.++@vjeuxdiff --git a/packages/core/src/Popover/Popover.test.tsx b/packages/core/src/Popover/Popover.test.tsxindex 7b9c20729e..3cdfde58b2 100644--- a/packages/core/src/Popover/Popover.test.tsx+++ b/packages/core/src/Popover/Popover.test.tsx@@ -945,6 +945,54 @@ describe('Popover', () => {expect(trigger).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.+ 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" data-testid="inside-content">+ Inside+ </button>+ }+ label="Test">+ <button type="button">Open</button>+ </Popover>,+ );+ const trigger = screen.getByRole('button', {name: 'Open'});+ trigger.focus();++ fireEvent.click(trigger);+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ fireEvent.keyDown(document, {key: 'Escape'});+ expect(trigger).toHaveAttribute('aria-expanded', 'false');++ // The open's frame runs late, as on a busy machine.+ act(() => {+ const due = [...frames.values()];+ frames.clear();+ due.forEach(callback => callback(0));+ });+ expect(trigger).toHaveFocus();+ } finally {+ vi.unstubAllGlobals();+ }+ });+it('returns focus to the trigger on light dismiss', () => {render(<Popoverdiff --git a/packages/core/src/Popover/usePopover.tsx b/packages/core/src/Popover/usePopover.tsxindex 83b09d458e..c481d37209 100644--- a/packages/core/src/Popover/usePopover.tsx+++ b/packages/core/src/Popover/usePopover.tsx@@ -443,13 +443,17 @@ function usePopoverImplementation(// Auto-focus first element when popover opens (unless skipped)useEffect(() => {- if (layer.isOpen && hasAutoFocus && !skipAutoFocusRef.current) {- // Use requestAnimationFrame to ensure DOM is ready- requestAnimationFrame(focusInitialTarget);- }// Reset the per-open focus preference after the popover closes.if (!layer.isOpen) {skipAutoFocusRef.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);+ return () => cancelAnimationFrame(frame);}}, [layer.isOpen, hasAutoFocus, focusInitialTarget]);diff --git a/packages/core/src/SideNav/SideNav.test.tsx b/packages/core/src/SideNav/SideNav.test.tsxindex 6c980b109f..163999bdbb 100644--- a/packages/core/src/SideNav/SideNav.test.tsx+++ b/packages/core/src/SideNav/SideNav.test.tsx@@ -2399,7 +2399,37 @@ describe('SideNav keyboard operation', () => {// Focus management (audit §6 V7)// =============================================================================+/**+ * Holds requestAnimationFrame callbacks until `flush`, so a test decides when+ * a popover's auto-focus frame runs instead of racing a timer.+ */+function holdAnimationFrames() {+ 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);+ });+ return {+ flush() {+ act(() => {+ const due = [...frames.values()];+ frames.clear();+ due.forEach(callback => callback(performance.now()));+ });+ },+ };+}+describe('SideNav focus management', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });+it('keeps focus on the toggle when a group collapses', async () => {const user = userEvent.setup();render(@@ -2437,6 +2467,7 @@ describe('SideNav focus management', () => {});it('returns focus to the trigger when the collapsed submenu closes', async () => {+ const frames = holdAnimationFrames();const user = userEvent.setup();renderCollapsed(<SideNavItem label="Settings" icon={StubIcon} data-testid="parent">@@ -2447,10 +2478,33 @@ describe('SideNav focus management', () => {const trigger = screen.getByTestId('parent');await user.click(trigger);expect(trigger).toHaveAttribute('aria-expanded', 'true');+ // The submenu focuses its first link in the frame after it opens.+ frames.flush();+ expect(screen.getByText('General').closest('a')).toHaveFocus();+ // Closing restores focus as part of the close itself.await user.keyboard('{Escape}');- // The layer restores focus asynchronously after it closes.- await waitFor(() => expect(trigger).toHaveFocus());+ expect(trigger).toHaveFocus();+ });++ it('keeps focus on the trigger when the submenu closes before its first frame', async () => {+ const frames = holdAnimationFrames();+ const user = userEvent.setup();+ renderCollapsed(+ <SideNavItem label="Settings" icon={StubIcon} data-testid="parent">+ <SideNavItem label="General" href="/settings/general" />+ </SideNavItem>,+ );++ const trigger = screen.getByTestId('parent');+ await user.click(trigger);+ await user.keyboard('{Escape}');+ expect(trigger).toHaveAttribute('aria-expanded', 'false');++ // The open's auto-focus frame, late on a busy runner, must not land+ // focus in the closed submenu.+ frames.flush();+ expect(trigger).toHaveFocus();});});