An open source design system that's fully customizable and agent ready
TypeScript
fix(BottomSheet, Dialog): returning focus after an overlay closes no longer scrolls the page (#10022)
Xinzi Zhou5db61cc9b527
diff --git a/.changeset/overlay-focus-return-keeps-the-page.md b/.changeset/overlay-focus-return-keeps-the-page.mdnew file mode 100644index 0000000000..00d20c4117--- /dev/null+++ b/.changeset/overlay-focus-return-keeps-the-page.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] BottomSheet and Dialog: the page no longer jumps after a sheet or a dialog closes in Safari and on iOS. Returning focus to the control that opened the overlay asks the browser not to scroll. WebKit focuses the nearest focusable ancestor of a tapped button, such as an app's `tabindex="-1"` main region, and records it as the opener; the focus return then scrolled the page to that region's top edge. The focus ring still follows the last input.++@imdreamrunnerdiff --git a/docs/families/overlay-dismissal.md b/docs/families/overlay-dismissal.mdindex 18fa062823..6af60abcf5 100644--- a/docs/families/overlay-dismissal.md+++ b/docs/families/overlay-dismissal.md@@ -24,6 +24,8 @@ verified_by:packages/core/src/Popover/Popover.test.tsx,packages/core/src/Popover/__tests__/PopoverSecondDocument.a11y.chromium.spec.ts,packages/core/src/Dialog/__tests__/DialogSecondDocument.a11y.browser.spec.ts,+ packages/core/src/BottomSheet/__tests__/BottomSheetCloseScroll.a11y.browser.spec.ts,+ packages/core/src/Dialog/__tests__/DialogCloseScroll.a11y.browser.spec.ts,]members:[@@ -214,6 +216,11 @@ this record's current membership snapshot must be updated with it.target, in the opener's document, with the ring the last input in thatdocument calls for (`architecture:interaction-modality` INV1); a BottomSheet,BottomSheetSwitcher, or Lightbox does the same in a Picture-in-Picture window.+ The return does not scroll the page or any scroller to the return target. A+ browser may record a focusable ancestor of the pressed control as the return+ target (WebKit focuses the nearest focusable ancestor of a tapped button,+ such as a `tabindex="-1"` main region); a reveal of that ancestor would+ scroll the page to its top edge.- **FR10 — A backdrop press starts and ends on the backdrop.** Dialog with`purpose="info"`, Drawer's scrim, and CommandPalette through its Dialog@@ -226,7 +233,8 @@ this record's current membership snapshot must be updated with it.## Allowed component variation- **AV1 — Focus.** Members own focus entry, containment, movement, and the- return target. FR9 fixes the document focus returns in.+ return target. FR9 fixes the document focus returns in, and that the return+ does not scroll.- **AV2 — Modality.** Members may be modal or non-modal and own any inertness orbackdrop behavior.- **AV3 — Positioning and hosting.** Members may use native dialog placement,@@ -289,6 +297,7 @@ modality, positioning, outside-dismissal, and open-state contracts.| FR8 | `useLayerDismissal.test.tsx`; `Popover.test.tsx` | members in the page and a same-origin iframe; a Popover alone and inside a Dialog, in an iframe | A press in one document dismisses a member of another, or a host closes over its nested layer || FR8 | `PopoverSecondDocument.a11y.chromium.spec.ts` | a Popover in an iframe and in a Picture-in-Picture window, alone and with one open in the page | A press in the second document misses its own layer or dismisses the page's || FR9 | `DialogSecondDocument.a11y.browser.spec.ts` | a Dialog in an iframe and in a Picture-in-Picture window, closed by Escape or a control inside it, and a Dialog in an iframe opened from the page | Focus lands outside the opener's document, or its ring does not follow the closing input |+| FR9 | `BottomSheetCloseScroll.a11y.browser.spec.ts`; `DialogCloseScroll.a11y.browser.spec.ts` | a BottomSheet and a Dialog whose trigger sits in a tall focusable region of a scrolled page, closed by a control inside, by the backdrop, and by Escape, in Chromium and WebKit | The page's scroll offset or the trigger's place on screen changes across the close || FR8, FR9 | Real-browser second-document checks; implementation gap: only Dialog and Popover have them | Dialog, Popover, DropdownMenu, MoreMenu, ContextMenu, Selector, MultiSelector, TopNavHeading, TopNavMenu, TopNavMegaMenu, SideNavHeading, SideNavItem, Tooltip and HoverCard, each in a same-origin iframe and in a Picture-in-Picture window: opens and takes Escape in the document it renders in (an unpinned Tooltip only when no other member is present; a pinned Tooltip before the member beneath it), and returns focus in the opener's document | The member opens or ranks in another document, a pinned Tooltip lets Escape reach the member beneath it, or focus lands on the frame element, the page, or the body || FR8, FR9 | Real-browser second-document checks; implementation gap: none has them | BottomSheet, BottomSheetSwitcher, and Lightbox in a Picture-in-Picture window: opens, takes Escape, and returns focus to its return target there | The surface ranks in the page, or focus lands on the page or the body || FR8 | Source check over Drawer and MobileNav | Drawer and MobileNav rendered from a control in a second document | A page-level surface moves into the second document |@@ -333,7 +342,7 @@ Rejected: one order across documents, where a press in one window dismisses a suNone. Focus entry, containment, movement, and the return target, modality,positioning, outside dismissal, and open-state APIs are outside this family-contract; FR9 fixes only the document focus returns in. The mapped tests do not render a nested+contract; FR9 fixes only the document focus returns in and that the return does not scroll. The mapped tests do not render a nestedlayer through a real portal; a real portal fixture is required before thiscontract can claim verified portal coverage.diff --git a/packages/core/src/BottomSheet/BottomSheet.test.tsx b/packages/core/src/BottomSheet/BottomSheet.test.tsxindex e1426a874a..ebe168114c 100644--- a/packages/core/src/BottomSheet/BottomSheet.test.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.test.tsx@@ -4018,7 +4018,11 @@ describe('BottomSheet', () => {finishSheetExit();expect(opener).toHaveFocus();- expect(focus.mock.calls).toEqual([[{focusVisible: false}]]);+ // The return reveals nothing: the opener was on screen when the sheet+ // opened and the page has not moved since.+ expect(focus.mock.calls).toEqual([+ [{preventScroll: true, focusVisible: false}],+ ]);});it('leaves the ring to the browser after a keyboard close', () => {@@ -4027,7 +4031,7 @@ describe('BottomSheet', () => {finishSheetExit();expect(opener).toHaveFocus();- expect(focus.mock.calls).toEqual([[]]);+ expect(focus.mock.calls).toEqual([[{preventScroll: true}]]);});it('clears a ring the native close already drew before refocusing', () => {@@ -4055,7 +4059,9 @@ describe('BottomSheet', () => {finishSheetExit();expect(blur).toHaveBeenCalledTimes(1);- expect(focus.mock.calls.at(-1)).toEqual([{focusVisible: false}]);+ expect(focus.mock.calls.at(-1)).toEqual([+ {preventScroll: true, focusVisible: false},+ ]);expect(blur.mock.invocationCallOrder[0]).toBeLessThan(focus.mock.invocationCallOrder.at(-1) ?? 0,);@@ -4093,7 +4099,9 @@ describe('BottomSheet', () => {finishSheetExit();expect(target).toHaveFocus();- expect(focus.mock.calls).toEqual([[{focusVisible: false}]]);+ expect(focus.mock.calls).toEqual([+ [{preventScroll: true, focusVisible: false}],+ ]);});});});diff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsxindex dbdb5992ea..04396a9c32 100644--- a/packages/core/src/BottomSheet/BottomSheet.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.tsx@@ -82,7 +82,7 @@ import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';import {useModalOutlet} from '../Layer/modalOutlet';import {useLayerDismissal} from '../Layer/useLayerDismissal';import {useFocusRegionContainment} from '../hooks/useFocusTrap';-import {focusForLastInput} from '../utils/focusReturn';+import {returnFocusForLastInput} from '../utils/focusReturn';import {useInteractionModalityTracking} from '../utils/interactionModality';import {BottomSheetPanel,@@ -725,7 +725,7 @@ function StandaloneBottomSheet({) {revealed.focus();} else if (returnTarget != null) {- focusForLastInput(returnTarget);+ returnFocusForLastInput(returnTarget);}triggerRef.current = null;},diff --git a/packages/core/src/BottomSheet/__tests__/BottomSheetCloseScroll.a11y.browser.spec.ts b/packages/core/src/BottomSheet/__tests__/BottomSheetCloseScroll.a11y.browser.spec.tsnew file mode 100644index 0000000000..451b3c5b00--- /dev/null+++ b/packages/core/src/BottomSheet/__tests__/BottomSheetCloseScroll.a11y.browser.spec.ts@@ -0,0 +1,141 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y always++/**+ * @file BottomSheetCloseScroll.a11y.browser.spec.ts+ * @input The `Core/BottomSheet` showcase story in a built Storybook, placed+ * in a tall focusable main region of a scrolled page, as an app places a+ * sheet's trigger.+ * @output Real-engine proof that closing a modal sheet keeps the page where it+ * was: the scroll offset and the trigger's place on screen are the same+ * after a pointer close (Apply, the scrim) and after Escape.+ * @position Chromium and WebKit. The page focuses the region before a+ * programmatic click opens the sheet, as a tap leaves focus in Safari, where+ * a button is not mouse-focusable; the sheet then records the region as its+ * opener, and a focus return that reveals the region scrolls the page to its+ * top edge.+ */++import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++const HEADER_HEIGHT = 192;+const SCROLL_OFFSET = 129;++/**+ * Mounts the story in a tall page: a header, then a focusable main region+ * that holds the trigger and a long tail. Scrolls so that the region's top+ * edge sits below the viewport's top edge, the geometry in which a reveal of+ * the region moves the page.+ */+async function mountScrolled(page: Page) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-bottomsheet--showcase&viewMode=story`,+ );+ const opener = page.getByRole('button', {name: 'Open sheet', exact: true});+ await expect(opener).toBeVisible();+ await page.evaluate(+ ({headerHeight, scrollOffset}) => {+ const root = document.getElementById('storybook-root');+ if (root?.parentNode == null) {+ throw new Error('no story root');+ }+ const spacer = (height: number) => {+ const node = document.createElement('div');+ node.style.height = `${height}px`;+ return node;+ };+ const main = document.createElement('div');+ main.tabIndex = -1;+ root.parentNode.insertBefore(spacer(headerHeight), root);+ root.parentNode.insertBefore(main, root);+ main.append(spacer(400), root, spacer(3000));+ window.scrollTo(0, scrollOffset);+ // Where Safari puts focus on a tap inside the region: a button is not+ // mouse-focusable there, so its nearest focusable ancestor takes it.+ main.focus({preventScroll: true});+ },+ {headerHeight: HEADER_HEIGHT, scrollOffset: SCROLL_OFFSET},+ );+ await expect+ .poll(async () => page.evaluate(() => window.scrollY))+ .toBe(SCROLL_OFFSET);+ const openerTop = await opener.evaluate(+ node => node.getBoundingClientRect().top,+ );+ return {opener, openerTop};+}++async function openSheet(page: Page, opener: Locator): Promise<Locator> {+ // A programmatic click moves no focus, so the region stays the recorded+ // opener in every engine, as a tap leaves it in Safari.+ await opener.evaluate(node => (node as HTMLElement).click());+ const dialog = page.getByRole('dialog', {name: 'Filters'});+ await expect(dialog).toBeVisible();+ // A close during the entrance reverses it; let the sheet settle first so+ // that the close plays a full exit.+ await expect+ .poll(async () =>+ dialog.evaluate(node => node.getAnimations({subtree: true}).length),+ )+ .toBe(0);+ return dialog;+}++async function expectPageStill(+ page: Page,+ opener: Locator,+ openerTop: number,+): Promise<void> {+ await expect(page.getByRole('dialog')).toBeHidden();+ // The exit's last frame, the focus return and the lock's release are+ // spread over a few tasks, and a reveal scroll lands a rendering update+ // after the focus move.+ await page.waitForTimeout(250);+ expect(await page.evaluate(() => window.scrollY)).toBe(SCROLL_OFFSET);+ expect(await opener.evaluate(node => node.getBoundingClientRect().top)).toBe(+ openerTop,+ );+}++test('a close from a button in the sheet keeps the page where it was', async ({+ page,+}) => {+ const {opener, openerTop} = await mountScrolled(page);+ const dialog = await openSheet(page, opener);+ await dialog.getByRole('button', {name: 'Apply', exact: true}).click();+ await expectPageStill(page, opener, openerTop);+});++test('a scrim close keeps the page where it was', async ({page}) => {+ const {opener, openerTop} = await mountScrolled(page);+ await openSheet(page, opener);+ await page.mouse.click(20, 20);+ await expectPageStill(page, opener, openerTop);+});++test('an Escape close keeps the page where it was', async ({page}) => {+ const {opener, openerTop} = await mountScrolled(page);+ await openSheet(page, opener);+ await page.keyboard.press('Escape');+ await expectPageStill(page, opener, openerTop);+});diff --git a/packages/core/src/BottomSheet/bottomSheetStack.ts b/packages/core/src/BottomSheet/bottomSheetStack.tsindex c27ba6653c..43ef887b16 100644--- a/packages/core/src/BottomSheet/bottomSheetStack.ts+++ b/packages/core/src/BottomSheet/bottomSheetStack.ts@@ -4,7 +4,8 @@/*** @file bottomSheetStack.ts- * @input The DOM (dialog elements, document order) and focusForLastInput+ * @input The DOM (dialog elements, document order) and the focus-return+ * utilities* @output The private bottom-sheet stack registry: host registration,* open-order ranking, top-layer reconciliation, one view per host, the* replace handoff, and the shared native show/hide and focus helpers@@ -50,7 +51,7 @@// version keeps its own stack. Each document is its own stack.import {notifyTopLayerEntry} from '../Layer/modalOutlet';-import {focusForLastInput} from '../utils/focusReturn';+import {focusForLastInput, returnFocusForLastInput} from '../utils/focusReturn';export interface BottomSheetStackView {/** Another modal sheet is presented alongside this one. */@@ -458,7 +459,7 @@ function completeClosingGroup(group: ClosingGroup): void {group.reported = true;const target = group.returnTarget;if (target != null && target.isConnected) {- focusForLastInput(target);+ returnFocusForLastInput(target);}}diff --git a/packages/core/src/Dialog/Dialog.test.tsx b/packages/core/src/Dialog/Dialog.test.tsxindex f7b3e33420..9742761f43 100644--- a/packages/core/src/Dialog/Dialog.test.tsx+++ b/packages/core/src/Dialog/Dialog.test.tsx@@ -987,7 +987,7 @@ describe('Dialog', () => {focus.mock.calls.filter((_call, index) => focus.mock.contexts[index] === opener,),- ).toEqual([[]]);+ ).toEqual([[{preventScroll: true}]]);focus.mockRestore();});@@ -1016,7 +1016,7 @@ describe('Dialog', () => {focus.mock.calls.filter((_call, index) => focus.mock.contexts[index] === field,),- ).toEqual([[]]);+ ).toEqual([[{preventScroll: true}]]);expect(blur.mock.contexts).not.toContain(field);focus.mockRestore();blur.mockRestore();@@ -1109,7 +1109,11 @@ describe('Dialog', () => {fireEvent.pointerUp(cancel);fireEvent.click(cancel);expect(invoker).toHaveFocus();- expect(focusCallsOn(focus, invoker)).toEqual([[{focusVisible: false}]]);+ // The return reveals nothing: the opener was on screen when the dialog+ // opened and the page has not moved since.+ expect(focusCallsOn(focus, invoker)).toEqual([+ [{preventScroll: true, focusVisible: false}],+ ]);});it('keeps plain focus on both moves after keyboard input', () => {@@ -1126,7 +1130,7 @@ describe('Dialog', () => {fireEvent.keyDown(cancel, {key: 'Enter'});fireEvent.click(cancel);expect(invoker).toHaveFocus();- expect(focusCallsOn(focus, invoker)).toEqual([[]]);+ expect(focusCallsOn(focus, invoker)).toEqual([[{preventScroll: true}]]);});it('clears a ring the browser already drew before refocusing after pointer input', () => {@@ -1163,7 +1167,9 @@ describe('Dialog', () => {fireEvent.click(cancel);expect(blur).toHaveBeenCalledTimes(1);- expect(focus.mock.calls.at(-1)).toEqual([{focusVisible: false}]);+ expect(focus.mock.calls.at(-1)).toEqual([+ {preventScroll: true, focusVisible: false},+ ]);expect(blur.mock.invocationCallOrder[0]).toBeLessThan(focus.mock.invocationCallOrder.at(-1) ?? 0,);diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsxindex 74c6191112..288e178d18 100644--- a/packages/core/src/Dialog/Dialog.tsx+++ b/packages/core/src/Dialog/Dialog.tsx@@ -87,6 +87,7 @@ import {useInteractionModalityTracking} from '../utils/interactionModality';import {focusForLastInput,prepareFocusReturnOnRemoval,+ returnFocusForLastInput,} from '../utils/focusReturn';import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';@@ -661,7 +662,7 @@ export function Dialog({// the last input in that element's own document calls for.const trigger = triggerElementRef.current;if (trigger) {- focusForLastInput(trigger);+ returnFocusForLastInput(trigger);}triggerElementRef.current = null;}diff --git a/packages/core/src/Dialog/__tests__/DialogCloseScroll.a11y.browser.spec.ts b/packages/core/src/Dialog/__tests__/DialogCloseScroll.a11y.browser.spec.tsnew file mode 100644index 0000000000..dc46c64d6c--- /dev/null+++ b/packages/core/src/Dialog/__tests__/DialogCloseScroll.a11y.browser.spec.ts@@ -0,0 +1,138 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y always++/**+ * @file DialogCloseScroll.a11y.browser.spec.ts+ * @input The `Core/Dialog` default story in a built Storybook, placed in a+ * tall focusable main region of a scrolled page, as an app places a+ * dialog's trigger.+ * @output Real-engine proof that closing a modal dialog keeps the page where+ * it was: the scroll offset and the trigger's place on screen are the same+ * after a pointer close (Cancel, the backdrop) and after Escape.+ * @position Chromium and WebKit. The page focuses the region before a+ * programmatic click opens the dialog, as a tap leaves focus in Safari, where+ * a button is not mouse-focusable; the dialog then records the region as its+ * opener, and a focus return that reveals the region scrolls the page to its+ * top edge.+ */++import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++const HEADER_HEIGHT = 192;+const SCROLL_OFFSET = 129;++/**+ * Mounts the story in a tall page: a header, then a focusable main region+ * that holds the trigger and a long tail. Scrolls so that the region's top+ * edge sits below the viewport's top edge, the geometry in which a reveal of+ * the region moves the page.+ */+async function mountScrolled(page: Page) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-dialog--default&viewMode=story`,+ );+ const opener = page.getByRole('button', {name: 'Open Modal', exact: true});+ await expect(opener).toBeVisible();+ await page.evaluate(+ ({headerHeight, scrollOffset}) => {+ const root = document.getElementById('storybook-root');+ if (root?.parentNode == null) {+ throw new Error('no story root');+ }+ const spacer = (height: number) => {+ const node = document.createElement('div');+ node.style.height = `${height}px`;+ return node;+ };+ const main = document.createElement('div');+ main.tabIndex = -1;+ root.parentNode.insertBefore(spacer(headerHeight), root);+ root.parentNode.insertBefore(main, root);+ main.append(spacer(400), root, spacer(3000));+ window.scrollTo(0, scrollOffset);+ // Where Safari puts focus on a tap inside the region: a button is not+ // mouse-focusable there, so its nearest focusable ancestor takes it.+ main.focus({preventScroll: true});+ },+ {headerHeight: HEADER_HEIGHT, scrollOffset: SCROLL_OFFSET},+ );+ await expect+ .poll(async () => page.evaluate(() => window.scrollY))+ .toBe(SCROLL_OFFSET);+ const openerTop = await opener.evaluate(+ node => node.getBoundingClientRect().top,+ );+ return {opener, openerTop};+}++async function openDialog(page: Page, opener: Locator): Promise<Locator> {+ // A programmatic click moves no focus, so the region stays the recorded+ // opener in every engine, as a tap leaves it in Safari.+ await opener.evaluate(node => (node as HTMLElement).click());+ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeVisible();+ await expect+ .poll(async () =>+ dialog.evaluate(node => node.getAnimations({subtree: true}).length),+ )+ .toBe(0);+ return dialog;+}++async function expectPageStill(+ page: Page,+ opener: Locator,+ openerTop: number,+): Promise<void> {+ await expect(page.getByRole('dialog')).toBeHidden();+ // The close, the focus return and the lock's release are spread over a few+ // tasks, and a reveal scroll lands a rendering update after the focus move.+ await page.waitForTimeout(250);+ expect(await page.evaluate(() => window.scrollY)).toBe(SCROLL_OFFSET);+ expect(await opener.evaluate(node => node.getBoundingClientRect().top)).toBe(+ openerTop,+ );+}++test('a close from a button in the dialog keeps the page where it was', async ({+ page,+}) => {+ const {opener, openerTop} = await mountScrolled(page);+ const dialog = await openDialog(page, opener);+ await dialog.getByRole('button', {name: 'Cancel', exact: true}).click();+ await expectPageStill(page, opener, openerTop);+});++test('a backdrop close keeps the page where it was', async ({page}) => {+ const {opener, openerTop} = await mountScrolled(page);+ await openDialog(page, opener);+ await page.mouse.click(20, 20);+ await expectPageStill(page, opener, openerTop);+});++test('an Escape close keeps the page where it was', async ({page}) => {+ const {opener, openerTop} = await mountScrolled(page);+ await openDialog(page, opener);+ await page.keyboard.press('Escape');+ await expectPageStill(page, opener, openerTop);+});diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsxindex d1c36a7a37..5e170fe2a7 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx@@ -74,7 +74,7 @@ import {useDropdownMenuPress} from '../hooks/useMenuPress';import type {MenuPressPointerType} from '../hooks/menuPressGesture';import {useTypeahead} from '../hooks/useTypeahead';import {useFocusReturnVisibility} from '../hooks/useFocusReturnVisibility';-import {focusForLastInput} from '../utils/focusReturn';+import {returnFocusForLastInput} from '../utils/focusReturn';import {useMenuOverflow} from './useMenuOverflow';import {MenuRegionsContext} from './menuRegionsContext';import {moveRegionsTab} from './menuRegionStops';@@ -1033,7 +1033,7 @@ function DropdownMenuPopover({// reaches only the design system's own Button; the browser's focus option// also reaches a control the caller renders, which the browser would// otherwise ring (Chromium after a mouse pick, WebKit after a touch).- focusForLastInput(trigger, {preventScroll: true});+ returnFocusForLastInput(trigger);}, [hideOpenFlyouts, isControlled, onOpenChange, prepareFocusReturn]);// Defer item focus until the layer has committed open, so focus restorediff --git a/packages/core/src/utils/focusReturn.test.ts b/packages/core/src/utils/focusReturn.test.tsindex 2be7756c25..bd31609819 100644--- a/packages/core/src/utils/focusReturn.test.ts+++ b/packages/core/src/utils/focusReturn.test.ts@@ -6,6 +6,7 @@ import {isFocusLost,moveFocusLeftBehind,noteFocusWithin,+ returnFocusForLastInput,} from './focusReturn';import {isFocusDetached} from './isFocusDetached';import {@@ -125,6 +126,49 @@ describe('focusForLastInput', () => {});});+describe('returnFocusForLastInput', () => {+ beforeEach(() => {+ __startInteractionModalityTrackingForTest();+ __resetInteractionModalityForTest();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ document.body.innerHTML = '';+ });++ it('returns focus without a scroll after keyboard input', () => {+ const opener = document.createElement('button');+ document.body.appendChild(opener);+ const focus = vi.spyOn(opener, 'focus');+ returnFocusForLastInput(opener);+ expect(focus.mock.calls).toEqual([[{preventScroll: true}]]);+ expect(document.activeElement).toBe(opener);+ });++ it('returns focus without a scroll and without a ring after pointer input', () => {+ const opener = document.createElement('button');+ document.body.appendChild(opener);+ document.dispatchEvent(new Event('pointerdown'));+ const focus = vi.spyOn(opener, 'focus');+ returnFocusForLastInput(opener);+ expect(focus.mock.calls).toEqual([+ [{preventScroll: true, focusVisible: false}],+ ]);+ expect(document.activeElement).toBe(opener);+ });++ it('takes the ring from the modality it is given', () => {+ const opener = document.createElement('button');+ document.body.appendChild(opener);+ const focus = vi.spyOn(opener, 'focus');+ returnFocusForLastInput(opener, 'pointer');+ expect(focus.mock.calls).toEqual([+ [{preventScroll: true, focusVisible: false}],+ ]);+ });+});+describe('focusForLastInput in a second document', () => {it("follows the last input in the element's own document by default", () => {__startInteractionModalityTrackingForTest();diff --git a/packages/core/src/utils/focusReturn.ts b/packages/core/src/utils/focusReturn.tsindex 4da70689e9..2f94492d05 100644--- a/packages/core/src/utils/focusReturn.ts+++ b/packages/core/src/utils/focusReturn.ts@@ -5,8 +5,9 @@* @input The document's current active element and the shared interaction* modality.* @output Whether focus would be lost if a surface hid now; a focus move whose- * ring follows the last input; and the one path that moves focus out of- * content a change removed or hid (`noteFocusWithin`, `moveFocusLeftBehind`).+ * ring follows the last input; the focus return of a closed overlay, which+ * never scrolls the page; and the one path that moves focus out of content a+ * change removed or hid (`noteFocusWithin`, `moveFocusLeftBehind`).* @position Utility; used by overlays (BottomSheet, Dialog, DropdownMenu) that* move focus programmatically, and by disclosures that hide focused* content. isFocusDetached lives in isFocusDetached.ts, so the utils entry,@@ -129,6 +130,19 @@ export function focusForLastInput(element.focus({...options, focusVisible: false});}+/**+ * Returns focus to `opener` after an overlay closes, without a scroll and with+ * the ring the last input calls for. WebKit records the nearest focusable+ * ancestor of a tapped button as the opener, such as a `tabindex="-1"` main+ * region. A reveal of that region scrolls the page to its top edge.+ */+export function returnFocusForLastInput(+ opener: HTMLElement,+ modality?: InteractionModality,+): void {+ focusForLastInput(opener, {preventScroll: true}, modality);+}+/*** Prepares the focus return for an open surface that may be removed while* open (rendered only while open, or removed with its view). Removing a@@ -153,7 +167,7 @@ export function prepareFocusReturnOnRemoval(return;}if (isFocusLost(surface) && (host == null || isFocusLost(host))) {- focusForLastInput(opener as HTMLElement);+ returnFocusForLastInput(opener as HTMLElement);}});};