An open source design system that's fully customizable and agent ready
TypeScript
fix(BottomSheet): a sheet removed while open returns focus where a close would (#10061)
Cindy Zhang8fdf6be377e2
diff --git a/.changeset/bottom-sheet-unmount-returns-focus.md b/.changeset/bottom-sheet-unmount-returns-focus.mdnew file mode 100644index 0000000000..c4205c849b--- /dev/null+++ b/.changeset/bottom-sheet-unmount-returns-focus.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] BottomSheet: a standalone sheet (not a `BottomSheetSwitcher` step) removed while it is open (rendered only while open, or removed with the rest of a view) returns focus where a close would send it, while that place is still on the page: to `finalFocusRef`, else the control that opened it, or into the sheet beneath. A whole stack of standalone sheets removed at once returns focus to the first sheet's `finalFocusRef` or opener. When none of these is left on the page, for example when the opener is removed with the sheet, focus stays where the browser leaves it. Focus the person had already moved out of a sheet, to the page body, stays where it is. A sheet that opens in the same update keeps focus, and removing a covered sheet under a top sheet that stays moves no focus.++@cixzhangdiff --git a/apps/storybook/stories/BottomSheet.stories.tsx b/apps/storybook/stories/BottomSheet.stories.tsxindex cfc1437b93..4afb74297c 100644--- a/apps/storybook/stories/BottomSheet.stories.tsx+++ b/apps/storybook/stories/BottomSheet.stories.tsx@@ -1044,3 +1044,36 @@ export const ExitFocusControlDisabled: Story = {tags: ['!autodocs'],render: () => <ExitFocusChangeFixture change="disable" />,};++/**+ * A sheet rendered only while it is open. "Done" removes the sheet while it is+ * still open; focus returns to "Edit filters" (FR20).+ */+export const RenderedWhileOpen: Story = {+ render: () => {+ const [isOpen, setIsOpen] = useState(false);+ const [hasScrim, setHasScrim] = useState(true);+ return (+ <VStack gap={2}>+ <CheckboxInput+ label="Modal (scrim)"+ value={hasScrim}+ onChange={setHasScrim}+ />+ <Button label="Edit filters" onClick={() => setIsOpen(true)} />+ {isOpen && (+ <BottomSheet+ isOpen+ onOpenChange={setIsOpen}+ hasScrim={hasScrim}+ label="Filters">+ <VStack gap={2}>+ <Text>Removing this sheet while it is open returns focus.</Text>+ <Button label="Done" onClick={() => setIsOpen(false)} />+ </VStack>+ </BottomSheet>+ )}+ </VStack>+ );+ },+};diff --git a/docs/specs/components/BottomSheet/BottomSheet.spec.md b/docs/specs/components/BottomSheet/BottomSheet.spec.mdindex adabfb4af7..964e302071 100644--- a/docs/specs/components/BottomSheet/BottomSheet.spec.md+++ b/docs/specs/components/BottomSheet/BottomSheet.spec.md@@ -167,6 +167,7 @@ remain documented in `BottomSheet.doc.mjs`.| FR16 | An open modal sheet is a focus region through Core's shared focus-region module (`component:Dialog/DEC-2`): in the top sheet, Tab from the last tabbable control moves focus to the first and Shift+Tab from the first moves focus to the last, so focus never leaves the sheet for the browser's own interface. A covered or closing sheet does not answer Tab, and a non-modal sheet contains nothing (FR11). A switcher step (the deprecated BottomSheetSwitcher) is the exception to DEC-2, as `component:Dialog` DEC-2 states. | `component:Dialog/DEC-2` || FR17 | A BottomSheet open on the server, by its own `isOpen` or as a `BottomSheetSwitcher`'s active sheet, renders closed until hydration (no open styles, no `aria-modal`, the markup of a closed sheet) and opens in the render after hydration, the first that can enter its native host; it never claims a modality it does not have (`spec:AST-020` FR1, WCAG 2.2 SC 4.1.2). The server and hydrating renders produce the same markup (`spec:AST-013` FR9), and the open after hydration is settled, with no entry motion; later opens and closes animate as usual (`spec:AST-013` FR13). | `spec:AST-020` FR1 || FR18 | A finger's pull up past the tallest detent stretches the sheet on `spec:AST-094` FR3's rubber band, the same on every pull, with no hold. The sheet's surface reaches below the screen far enough for the whole stretch and the release, so the page under it never shows. A pull on the sheet's body stretches it as a pull on the grabber does, once the content has no room left to scroll that way: content that fits stretches at once, and a long list scrolls to its end first, then holds still while the sheet stretches. At every detent, a list that reaches its end mid-pull holds still while the sheet takes the rest of the pull. A sheet the caller sizes or styles keeps 48 px below the screen, and its stretch stops there. An inline block size, any `xstyle` and any class name count, because the sheet cannot read their rules. A mouse or a pen keeps its own resisted stretch, at most 48 px (`spec:AST-017` FR59). | DEC-3; `spec:AST-094` FR3 |+| FR20 | A standalone sheet (not a switcher step) removed while open is closed for focus: when it was the standalone or top sheet and focus was inside it, or fell to the body with its removal, focus returns as FR9 (modal) or FR11 (non-modal) state, to `finalFocusRef`, else the opener while it is still connected; with a sheet open beneath, focus goes into that revealed sheet by FR9. An FR10 replace keeps its handoff to the entering sheet, and a switcher step's change keeps FR12's handoff. Removing a whole stack in one update returns focus once, as FR9 closes it: to the bottom sheet's `finalFocusRef` or opener. Removing a covered sheet under a top sheet that stays moves no focus, because focus is in the top sheet. A removed opener moves no focus and raises no error. Implementation gap: a `BottomSheetSwitcher` flow removed while open, alone or as the bottom level of a stack, returns no focus. | `spec:AST-020/FR1` (WCAG 2.2 SC 2.4.3); FR9; FR11 |### Allowed variation@@ -274,7 +275,8 @@ remain documented in `BottomSheet.doc.mjs`.- **AR4 — Focus follows the person through a stack.** Opening the top sheetmoves focus into it; a replace moves focus into the entering step whateverthe native host did; a pop returns focus into the revealed sheet; the last- close and a close of the whole stack return focus by FR9. A sheet opened on+ close and a close of the whole stack return focus by FR9, and a sheet+ removed while open returns focus by FR20. A sheet opened onits own, modal or not, focuses wherever the engine's native focusing stepsland when the released host presents it, with no `data-autofocus`preference added (the released behavior): in Chromium the panel, in Firefox@@ -388,6 +390,7 @@ a decision that they must remain unthemeable.| FR16 | `BottomSheet.test.tsx` focus-region suite | Modal and non-modal sheets; Tab and Shift+Tab at the sheet's edge | Tab from the last control leaves a modal sheet, or a non-modal sheet captures Tab | `audit:BottomSheet/accessibility` || FR17 | `BottomSheet.ssr.test.tsx`; `BottomSheetSwitcher.test.tsx` flow that mounts open | Open on the server; hydration; a closed sheet's markup | An open server render with `aria-modal`, open styles, or markup unlike a closed one, a hydration error, no `showModal()` after hydration, an entry motion on the open right after hydration, or none on a later open fails. | `audit:BottomSheet/accessibility` || FR18 | `useSheetGestures.test.ts` stretch suites; `BottomSheetPanel.test.tsx` reserve cases; `BottomSheetDrag.a11y.chromium.spec.ts` | Three finger pulls past the top; short content pulled up on its body at five points, the first pull and every one after it; a long list pulled past its end; a mouse pull and a pen pull | A capped or held stretch, a pull that stretches less than the one before it, a body pull on short content that moves nothing, a long list that never stretches the sheet once at its end or rubber-bands itself while the sheet stretches, or a reserve under 40% of the viewport on a device with a touch pointer fails, unless the caller sizes or styles the sheet (48 px). | `audit:BottomSheet/behavior` |+| FR20 | `BottomSheetCloseFocus.test.tsx` "BottomSheet removed while open" suite; real-browser focus check in Chromium | A modal and a non-modal sheet removed from inside; `finalFocusRef`; the top sheet of a stack removed; a covered sheet removed under a top sheet that stays; a whole stack removed in one update; a sheet removed in the update that opens another; an opener removed with the sheet | Focus on `body` after a removal from inside, focus on `body` after a whole stack is removed, focus moved out of the top sheet when a covered sheet is removed, focus pulled out of a sheet that opened in the same update, or an error when the opener is gone, fails. | `audit:BottomSheet/behavior` |Existing tests directly assert the Sheet panel target, Content area placement,Handle structure, and scrim behavior. Source and public target metadata confirmdiff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsxindex 04396a9c32..57a801bc2e 100644--- a/packages/core/src/BottomSheet/BottomSheet.tsx+++ b/packages/core/src/BottomSheet/BottomSheet.tsx@@ -82,7 +82,10 @@ import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';import {useModalOutlet} from '../Layer/modalOutlet';import {useLayerDismissal} from '../Layer/useLayerDismissal';import {useFocusRegionContainment} from '../hooks/useFocusTrap';-import {returnFocusForLastInput} from '../utils/focusReturn';+import {+ prepareFocusRepairOnRemoval,+ returnFocusForLastInput,+} from '../utils/focusReturn';import {useInteractionModalityTracking} from '../utils/interactionModality';import {BottomSheetPanel,@@ -553,7 +556,15 @@ function StandaloneBottomSheet({return;}const key = stackKeyRef.current;- return registerBottomSheet(+ const dialog = dialogRef.current;+ // Removing an open dialog runs no close, so focus would drop to the page.+ // After the commit, the repair sends focus where a close would, if the+ // removal lost focus.+ const repairOnRemoval =+ dialog == null+ ? null+ : prepareFocusRepairOnRemoval(dialog, {keepRestingFocus: true});+ const leave = registerBottomSheet({key,getElement: () => dialogRef.current,@@ -611,6 +622,32 @@ function StandaloneBottomSheet({isOpenRef.current,hasScrim,);+ return () => {+ // Read before the registry lets go of the sheet beneath. Focus the+ // person had already moved out of the sheet to the page body stays+ // there: the removal did not lose it.+ if (repairOnRemoval != null && isSheetHostPresented(dialog)) {+ const returnTarget =+ finalFocusRefRef.current?.current ?? triggerRef.current;+ const revealed = hasScrim ? getBottomSheetBeneath(key) : null;+ repairOnRemoval(() => {+ // The sheet beneath left too. Its own repair returns focus for the+ // stack.+ if (revealed != null && !revealed.element.isConnected) {+ return;+ }+ if (+ revealed != null &&+ (returnTarget == null || !revealed.element.contains(returnTarget))+ ) {+ revealed.focus();+ } else if (returnTarget != null && returnTarget.isConnected) {+ returnFocusForLastInput(returnTarget);+ }+ });+ }+ leave();+ };}, [hasScrim, shouldPresent, writeScrim]);useLayoutEffect(() => {if (!isOpen) {diff --git a/packages/core/src/BottomSheet/BottomSheetCloseFocus.test.tsx b/packages/core/src/BottomSheet/BottomSheetCloseFocus.test.tsxindex c137d1b101..f6e2456728 100644--- a/packages/core/src/BottomSheet/BottomSheetCloseFocus.test.tsx+++ b/packages/core/src/BottomSheet/BottomSheetCloseFocus.test.tsx@@ -12,7 +12,7 @@*/import {act, fireEvent, render, screen} from '@testing-library/react';-import {useState} from 'react';+import {useRef, useState} from 'react';import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';import {BottomSheet} from './BottomSheet';import {resetBottomSheetStackForTests} from './bottomSheetStack';@@ -268,3 +268,386 @@ describe('BottomSheet close order for focus', () => {expect(sheet()).toHaveAttribute('aria-hidden', 'true');});});++describe('BottomSheet removed while open', () => {+ // A non-modal sheet is a manual popover; jsdom's stand-ins keep the same+ // `open` marker the dialog paths use, as the other BottomSheet tests do.+ beforeEach(() => {+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {+ this.setAttribute('open', '');+ });+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {+ this.removeAttribute('open');+ });+ });++ // Lets the removal's focus repair run: it waits for the commit to finish.+ async function settle() {+ await act(async () => {+ await Promise.resolve();+ });+ }++ function sheetNamed(label: string): HTMLDialogElement | null {+ return document.querySelector<HTMLDialogElement>(+ `dialog[aria-label="${label}"]`,+ );+ }++ function RenderedWhileOpen({+ hasScrim,+ withFinalFocus = false,+ }: {+ hasScrim: boolean;+ withFinalFocus?: boolean;+ }) {+ const [isOpen, setIsOpen] = useState(false);+ const searchRef = useRef<HTMLInputElement>(null);+ return (+ <>+ <input aria-label="Search" ref={searchRef} />+ <button type="button" onClick={() => setIsOpen(true)}>+ Filters+ </button>+ {isOpen && (+ <BottomSheet+ isOpen+ onOpenChange={setIsOpen}+ label="Filters"+ hasScrim={hasScrim}+ finalFocusRef={withFinalFocus ? searchRef : undefined}>+ <button type="button" onClick={() => setIsOpen(false)}>+ Done+ </button>+ </BottomSheet>+ )}+ </>+ );+ }++ function openAndPressDone(element: React.ReactElement) {+ render(element);+ const opener = screen.getByRole('button', {name: 'Filters'});+ act(() => opener.focus());+ fireEvent.click(opener);+ const done = screen.getByRole('button', {name: 'Done', hidden: true});+ act(() => done.focus());+ fireEvent.click(done);+ return opener;+ }++ it.each([+ ['a modal', true],+ ['a non-modal', false],+ ])(+ 'returns focus to the opener when %s sheet is removed from inside',+ async (_label, hasScrim) => {+ const opener = openAndPressDone(+ <RenderedWhileOpen hasScrim={hasScrim} />,+ );+ await settle();++ expect(sheetNamed('Filters')).toBeNull();+ expect(opener).toHaveFocus();+ },+ );++ it('leaves focus on the body when it rested there before a non-modal sheet was removed', async () => {+ function NonModal() {+ const [isOpen, setIsOpen] = useState(false);+ return (+ <>+ <button type="button" onClick={() => setIsOpen(true)}>+ Filters+ </button>+ <button type="button" onClick={() => setIsOpen(false)}>+ Remove+ </button>+ {isOpen && (+ <BottomSheet+ isOpen+ onOpenChange={setIsOpen}+ label="Filters"+ hasScrim={false}>+ <button type="button">Done</button>+ </BottomSheet>+ )}+ </>+ );+ }+ render(<NonModal />);+ const opener = screen.getByRole('button', {name: 'Filters'});+ act(() => opener.focus());+ fireEvent.click(opener);+ // The person clicked the page behind the sheet: focus rests on the body.+ act(() => (document.activeElement as HTMLElement | null)?.blur());+ expect(document.activeElement).toBe(document.body);++ fireEvent.click(screen.getByRole('button', {name: 'Remove'}));+ await settle();++ expect(sheetNamed('Filters')).toBeNull();+ expect(document.activeElement).toBe(document.body);+ });++ it('returns focus to finalFocusRef when one is given', async () => {+ openAndPressDone(<RenderedWhileOpen hasScrim withFinalFocus />);+ await settle();++ expect(screen.getByRole('textbox', {name: 'Search'})).toHaveFocus();+ });++ it('moves no focus when the opener was removed too', async () => {+ function View() {+ const [isShown, setIsShown] = useState(true);+ const [isOpen, setIsOpen] = useState(false);+ return isShown ? (+ <div>+ <button type="button" onClick={() => setIsOpen(true)}>+ Filters+ </button>+ {isOpen && (+ <BottomSheet isOpen onOpenChange={setIsOpen} label="Filters">+ <button type="button" onClick={() => setIsShown(false)}>+ Done+ </button>+ </BottomSheet>+ )}+ </div>+ ) : null;+ }+ openAndPressDone(<View />);+ await settle();++ expect(sheetNamed('Filters')).toBeNull();+ expect(document.activeElement).toBe(document.body);+ });++ it('returns focus into the revealed sheet when the top sheet is removed', async () => {+ function Stack() {+ const [isOpen, setIsOpen] = useState(false);+ const [isSortOpen, setIsSortOpen] = useState(false);+ return (+ <>+ <button type="button" onClick={() => setIsOpen(true)}>+ Filters+ </button>+ <BottomSheet isOpen={isOpen} onOpenChange={setIsOpen} label="Filters">+ <button type="button" onClick={() => setIsSortOpen(true)}>+ Sort+ </button>+ {isSortOpen && (+ <BottomSheet isOpen onOpenChange={setIsSortOpen} label="Sort by">+ <button type="button" onClick={() => setIsSortOpen(false)}>+ Done+ </button>+ </BottomSheet>+ )}+ </BottomSheet>+ </>+ );+ }+ render(<Stack />);+ fireEvent.click(screen.getByRole('button', {name: 'Filters'}));+ const sort = screen.getByRole('button', {name: 'Sort', hidden: true});+ act(() => sort.focus());+ fireEvent.click(sort);+ const done = screen.getByRole('button', {name: 'Done', hidden: true});+ act(() => done.focus());++ fireEvent.click(done);+ await settle();++ expect(sheetNamed('Sort by')).toBeNull();+ expect(sort).toHaveFocus();+ });++ it('returns focus to the first opener when a whole stack is removed', async () => {+ function Stack() {+ const [isOpen, setIsOpen] = useState(false);+ const [isSortOpen, setIsSortOpen] = useState(false);+ return (+ <>+ <button type="button" onClick={() => setIsOpen(true)}>+ Filters+ </button>+ {isOpen && (+ <BottomSheet isOpen onOpenChange={setIsOpen} label="Filters">+ <button type="button" onClick={() => setIsSortOpen(true)}>+ Sort+ </button>+ {isSortOpen && (+ <BottomSheet+ isOpen+ onOpenChange={setIsSortOpen}+ label="Sort by">+ <button type="button" onClick={() => setIsOpen(false)}>+ Apply all+ </button>+ </BottomSheet>+ )}+ </BottomSheet>+ )}+ </>+ );+ }+ render(<Stack />);+ const opener = screen.getByRole('button', {name: 'Filters'});+ act(() => opener.focus());+ fireEvent.click(opener);+ const sort = screen.getByRole('button', {name: 'Sort', hidden: true});+ act(() => sort.focus());+ fireEvent.click(sort);+ const applyAll = screen.getByRole('button', {+ name: 'Apply all',+ hidden: true,+ });+ act(() => applyAll.focus());++ fireEvent.click(applyAll);+ await settle();++ expect(sheetNamed('Filters')).toBeNull();+ expect(sheetNamed('Sort by')).toBeNull();+ expect(opener).toHaveFocus();+ });++ it('returns focus to the bottom sheet opener when a sibling stack declared top first is removed', async () => {+ function Siblings() {+ const [isOpen, setIsOpen] = useState(false);+ const [isSortOpen, setIsSortOpen] = useState(false);+ const searchRef = useRef<HTMLInputElement>(null);+ return (+ <>+ <input aria-label="Search" ref={searchRef} />+ <button type="button" onClick={() => setIsOpen(true)}>+ Filters+ </button>+ {isOpen && isSortOpen && (+ <BottomSheet+ isOpen+ onOpenChange={setIsSortOpen}+ label="Sort by"+ finalFocusRef={searchRef}>+ <button type="button" onClick={() => setIsOpen(false)}>+ Apply all+ </button>+ </BottomSheet>+ )}+ {isOpen && (+ <BottomSheet isOpen onOpenChange={setIsOpen} label="Filters">+ <button type="button" onClick={() => setIsSortOpen(true)}>+ Sort+ </button>+ </BottomSheet>+ )}+ </>+ );+ }+ render(<Siblings />);+ const opener = screen.getByRole('button', {name: 'Filters'});+ act(() => opener.focus());+ fireEvent.click(opener);+ const sort = screen.getByRole('button', {name: 'Sort', hidden: true});+ act(() => sort.focus());+ fireEvent.click(sort);+ const applyAll = screen.getByRole('button', {+ name: 'Apply all',+ hidden: true,+ });+ act(() => applyAll.focus());++ fireEvent.click(applyAll);+ await settle();++ expect(sheetNamed('Filters')).toBeNull();+ expect(sheetNamed('Sort by')).toBeNull();+ expect(opener).toHaveFocus();+ });++ it('moves no focus when a covered sheet is removed under a top sheet that stays', async () => {+ function Siblings() {+ const [isFiltersShown, setIsFiltersShown] = useState(true);+ const [isSortOpen, setIsSortOpen] = useState(false);+ return (+ <>+ {isFiltersShown && (+ <BottomSheet isOpen onOpenChange={() => {}} label="Filters">+ <button type="button" onClick={() => setIsSortOpen(true)}>+ Sort+ </button>+ </BottomSheet>+ )}+ <BottomSheet+ isOpen={isSortOpen}+ onOpenChange={setIsSortOpen}+ label="Sort by">+ <button type="button" onClick={() => setIsFiltersShown(false)}>+ Remove filters+ </button>+ </BottomSheet>+ </>+ );+ }+ render(<Siblings />);+ const sort = screen.getByRole('button', {name: 'Sort', hidden: true});+ act(() => sort.focus());+ fireEvent.click(sort);+ const remove = screen.getByRole('button', {+ name: 'Remove filters',+ hidden: true,+ });+ act(() => remove.focus());++ fireEvent.click(remove);+ await settle();++ expect(sheetNamed('Filters')).toBeNull();+ expect(remove).toHaveFocus();+ });++ it('leaves focus in a sheet that opens in the update that removes this one', async () => {+ function Flow() {+ const [step, setStep] = useState<'none' | 'filters' | 'sort'>('none');+ return (+ <>+ <button type="button" onClick={() => setStep('filters')}>+ Filters+ </button>+ {step === 'filters' && (+ <BottomSheet+ isOpen+ onOpenChange={() => setStep('none')}+ label="Filters">+ <button type="button" onClick={() => setStep('sort')}>+ Next+ </button>+ </BottomSheet>+ )}+ {step === 'sort' && (+ <BottomSheet+ isOpen+ onOpenChange={() => setStep('none')}+ label="Sort by">+ <button type="button">Apply</button>+ </BottomSheet>+ )}+ </>+ );+ }+ render(<Flow />);+ const opener = screen.getByRole('button', {name: 'Filters'});+ act(() => opener.focus());+ fireEvent.click(opener);+ const next = screen.getByRole('button', {name: 'Next', hidden: true});+ act(() => next.focus());++ fireEvent.click(next);+ await settle();++ const sortSheet = sheetNamed('Sort by');+ expect(sortSheet).not.toBeNull();+ expect(sortSheet?.contains(document.activeElement)).toBe(true);+ expect(opener).not.toHaveFocus();+ });+});diff --git a/packages/core/src/utils/focusReturn.ts b/packages/core/src/utils/focusReturn.tsindex 2f94492d05..3a8d062201 100644--- a/packages/core/src/utils/focusReturn.ts+++ b/packages/core/src/utils/focusReturn.ts@@ -144,29 +144,75 @@ export function returnFocusForLastInput(}/**- * 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- * `<dialog>` runs no close and no browser focus return. Call this while the- * surface is mounted: it reads the frame that hosts the surface now, because a- * removed frame's document has no window. Call the returned function from the- * effect cleanup with the opener.+ * Prepares a focus repair for an open surface that may be removed while open+ * (rendered only while open, or removed with its view). Removing a `<dialog>`+ * runs no close and no browser focus return. Call this while the surface is+ * mounted: it reads the frame that hosts the surface now, because a removed+ * frame's document has no window. Call the returned function from the effect+ * cleanup with the repair to run.*- * Once the commit has finished, focus moves to the opener only when the- * surface really left the document (StrictMode's simulated unmount keeps it),- * the opener is still on the page, and the removal lost focus, both in the- * surface's document and in the document that hosts its frame. A control the- * user pressed outside the surface, or outside its frame, keeps its focus.+ * Once the commit has finished, the repair runs only when the surface really+ * left the document (StrictMode's simulated unmount keeps it) and the removal+ * lost focus, both in the surface's document and in the document that hosts+ * its frame. A control the user pressed outside the surface, or outside its+ * frame, keeps its focus, and so does a surface that took focus in the same+ * commit.*/-export function prepareFocusReturnOnRemoval(+export function prepareFocusRepairOnRemoval(surface: Element,-): (opener: Element | null) => void {+ options?: {+ /**+ * Skip the repair when focus already rested on the page body before the+ * commit's first removal: the removal did not lose that focus.+ */+ keepRestingFocus?: boolean;+ },+): (repair: () => void) => void {const host = surface.ownerDocument.defaultView?.frameElement ?? null;- return opener => {+ return repair => {+ if (+ options?.keepRestingFocus === true &&+ wasFocusDetachedBeforeRemoval(surface.ownerDocument)+ ) {+ return;+ }queueMicrotask(() => {- if (surface.isConnected || opener == null || !opener.isConnected) {+ if (surface.isConnected) {return;}if (isFocusLost(surface) && (host == null || isFocusLost(host))) {+ repair();+ }+ });+ };+}++// Whether focus rested on the page body when the current commit began+// removing surfaces, per document. One removal can drop focus before a later+// surface's cleanup runs, so every cleanup of the commit reads the first value.+const focusDetachedAtRemovalStart = new WeakMap<Document, boolean>();+function wasFocusDetachedBeforeRemoval(doc: Document): boolean {+ let wasDetached = focusDetachedAtRemovalStart.get(doc);+ if (wasDetached === undefined) {+ wasDetached = isFocusDetached(doc);+ focusDetachedAtRemovalStart.set(doc, wasDetached);+ queueMicrotask(() => focusDetachedAtRemovalStart.delete(doc));+ }+ return wasDetached;+}++/**+ * The focus repair above that returns focus to `opener` while the opener is+ * still on the page. Call the returned function from the effect cleanup with+ * the opener.+ */+export function prepareFocusReturnOnRemoval(+ surface: Element,+): (opener: Element | null) => void {+ const repairOnRemoval = prepareFocusRepairOnRemoval(surface);+ return opener => {+ repairOnRemoval(() => {+ if (opener != null && opener.isConnected) {returnFocusForLastInput(opener as HTMLElement);}});