Skip to content

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

TypeScript

fix(BottomSheet): a lone sheet focuses its data-autofocus field on open in every browser (#10156)

Cindy Zhangd9ea17921e39
diff --git a/.changeset/bottom-sheet-lone-autofocus.md b/.changeset/bottom-sheet-lone-autofocus.md
new file mode 100644
index 0000000000..4389f4a9e7
--- /dev/null
+++ b/.changeset/bottom-sheet-lone-autofocus.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A `BottomSheet` that opens, on its own or pushed over another sheet, modal or not, now focuses its `data-autofocus` field (a `TextInput` with `hasAutoFocus`) in every browser; for example, a pushed "Edit delivery note" sheet opens on its note field. A `BottomSheetSwitcher` step with such a field opens on it too. Before, Chromium left focus on the sheet's panel, so on Android a person had to tap the field before typing. A sheet with no such field still focuses where the browser's own dialog focusing puts it.
+
+@cixzhang
diff --git a/apps/storybook/stories/BottomSheet.stories.tsx b/apps/storybook/stories/BottomSheet.stories.tsx
index 4afb74297c..4c090f4ef0 100644
--- a/apps/storybook/stories/BottomSheet.stories.tsx
+++ b/apps/storybook/stories/BottomSheet.stories.tsx
@@ -927,8 +927,8 @@ export const NestedPopover: Story = {
};
/**
- * A no-scrim sheet with a `data-autofocus` field: focus on open follows the
- * native host, which lands on the panel; the field is not focused.
+ * A no-scrim sheet with a `data-autofocus` field: the field is focused when
+ * the sheet opens, in every browser.
*/
export const NoScrimAutofocus: Story = {
name: 'No scrim with a data-autofocus field',
@@ -963,7 +963,7 @@ export const NoScrimAutofocus: Story = {
/**
* A modal sheet with a `data-autofocus` field (a TextInput with hasAutoFocus):
- * what focus lands on when the sheet opens.
+ * the field is focused when the sheet opens, in every browser.
*/
export const ModalAutofocus: Story = {
name: 'Modal with a data-autofocus field',
diff --git a/docs/specs/components/BottomSheet/BottomSheet.spec.md b/docs/specs/components/BottomSheet/BottomSheet.spec.md
index d0d471d0e0..282be0d0e2 100644
--- a/docs/specs/components/BottomSheet/BottomSheet.spec.md
+++ b/docs/specs/components/BottomSheet/BottomSheet.spec.md
@@ -17,6 +17,7 @@ verified_by:
packages/core/src/BottomSheet/BottomSheetKeyboard.test.tsx,
packages/core/src/BottomSheet/BottomSheetStacking.test.tsx,
packages/core/src/BottomSheet/BottomSheetReplace.test.tsx,
+ packages/core/src/BottomSheet/__tests__/BottomSheetAutofocus.a11y.browser.spec.ts,
packages/core/src/BottomSheet/useSheetGestures.test.ts,
packages/core/src/Toast/ToastViewport.modalHost.test.tsx,
packages/core/src/BottomSheet/__tests__/BottomSheetNativeModal.a11y.browser.spec.ts,
@@ -76,15 +77,15 @@ gap note.
additive — no released contract described two presented sheets, so the stack
gives behavior to a state no contract covered — and as
implementation-equivalent for a sheet on its own: a modal sheet presented on
- its own behaves as released (focus on open wherever the engine's
- `showModal()` focusing steps put it — in Chromium the panel, a
- `data-autofocus` descendant notwithstanding; in Firefox the first focusable
- control in the content), and a non-modal sheet on its own keeps its
- documented contract (no scrim, no scroll lock, page interactive, dismissal
- by `purpose`, `finalFocusRef` focused after every close, the element focused
- when it was shown focused again when it closes while focus is inside it, and
- focus on open where that engine's `show()` focusing steps put it — the panel
- in Chromium, the first control in Firefox, likewise)
+ its own behaves as released, except that it focuses an eligible
+ `data-autofocus` descendant on open in every engine (AR4), a `[fix]` under
+ `component:TextInput` FR2 and `component:Dialog` FR2; and a non-modal sheet
+ on its own keeps its documented contract (no scrim, no scroll lock, page
+ interactive, dismissal by `purpose`, `finalFocusRef` focused after every
+ close, the element focused when it was shown focused again when it closes
+ while focus is inside it, and focus on open on an eligible
+ `data-autofocus` descendant, else where that engine's `show()` focusing
+ steps put it — the panel in Chromium, the first control in Firefox)
while its host changes from `show()` with a page-level `z-index` to the top
layer with none (FR11). One exception, visual only: under
`prefers-reduced-motion: reduce` a lone sheet's entrance and exit follow
@@ -160,7 +161,7 @@ remain documented in `BottomSheet.doc.mjs`.
| FR8 | A sheet rendered in another sheet's content is presented only while its host is open: it leaves the top layer with its host and is presented again, on top, if its own `isOpen` is still true when the host reopens. Its `isOpen` is never written by the host. | DEC-2 |
| FR9 | Closing the top sheet returns focus into the sheet it reveals: to the element that opened the closing sheet when that element is inside the revealed sheet, else to the revealed sheet's panel; an explicit `finalFocusRef` outside the revealed sheet yields to its panel in the same way. The last sheet of a stack keeps the standalone rule: `finalFocusRef`, else the opener. Closing every sheet of a stack in one update returns focus once, to the bottom sheet's `finalFocusRef` or opener, after the last dialog has closed. A close driven by the stack itself never moves focus. A standalone sheet (not a switcher step) that closes with focus inside it is neither `inert` nor `aria-hidden` while that focus stays, and takes no pointer or keyboard activation; when the exit ends, its dialog closes and focus returns in the same task, so focus never sits in a hidden subtree (`spec:AST-020` FR1; WCAG 2.2 SC 2.4.3 and 4.1.2). It becomes `inert` and `aria-hidden` as soon as focus leaves it. A sheet that closes with focus elsewhere is `inert` and `aria-hidden` from the close. | DEC-2 |
| FR10 | When exactly one standalone sheet closes and exactly one opens in the same update, both of one document and one modality, the closing sheet was the top sheet of its group — its document's modal stack, or, for non-modal sheets, the one open non-modal sheet (FR11) — with the opening sheet set aside, neither dialog contains the other, and the actor — the control last pressed, or, with no fresh press, the element focused when the update began — is inside the closing sheet's dialog or is none (no fresh press, and nothing or only the document body focused, as when code changes the step while focus has fallen to the body), the opening sheet replaces the closing one: it enters above the retained sheet; a retained sheet whose top edge is above the entering sheet's resting top edge moves down to meet it at the same time; the retained sheet fades only after both motions complete; it is `inert` and `aria-hidden` from the first frame and takes no dismissal request; the scrim owner is FR6's, the bottom open sheet: when the retained sheet is that owner (a replace at the bottom of the stack) its backdrop keeps the one visible scrim until it leaves and the entering sheet's backdrop takes over with no transition, and when the replace runs above a covered sheet that sheet stays the owner and the retained sheet's backdrop is transparent throughout, so it only fades; focus moves into the entering sheet; and the entering sheet adopts the retained sheet's focus-return target, so closing the flow returns focus to its first opener. A close and an open that fail any condition — different updates, a covered sheet closing, several sheets changing, a sheet closing with its host, or a control outside the closing sheet acting — keep the ordinary push and pop motion and their own focus return. | DEC-2 |
-| FR11 | A non-modal sheet (`hasScrim={false}`) is presented in the browser's top layer as a manual popover with no backdrop, no scroll lock, and no focus trap, and carries no page-level `z-index`; where the Popover API is absent it is presented with `show()` in page stacking order as a reduced fallback. A non-modal sheet shown while a modal dialog that does not contain it is open (a modal sheet, a `Dialog`) is inert under that modal, so it does not enter the top layer yet — there it would paint above the modal while a press on it lands on the modal — and is presented with `show()` beneath the modal, with no page-level `z-index`; a modal on its way out (inert and hidden, or holding focus under FR9) counts as gone. Once no such modal is open the sheet enters the top layer as a manual popover, a top-layer toast viewport re-entering above it (FR14), so page content never paints over an interactive non-modal sheet (`spec:AST-027` FR8). A non-modal sheet rendered inside the modal's content is not inert and enters the top layer at once. Non-modal sheets never stack, recede, or own a scrim, and never pair with a modal sheet; because they never stack, the one open non-modal sheet of a document is always the top of its own group, so two non-modal sheets replace each other under FR10 — the closing one being that top — with no backdrop. On a lone open, focus goes where the engine's own `show()` focusing steps would put it when they enter the sheet, and no `data-autofocus` preference is added over them (the released behavior, kept, and the same rule as a modal sheet's `showModal()`): in Chromium the panel, whose focusing steps take the first focusable area including a `tabindex="-1"` container; in Firefox the first focusable control in the content, which is the `data-autofocus` field only when it comes first; in WebKit wherever its `show()` lands. Where the manual-popover host's own focusing steps would land elsewhere than that engine's `show()` (Chromium's `showPopover()` lands on the first control), focus arrives where `show()` would have put it without passing through any control — no control receives a focus or a blur on the way, so a field validating on blur does not fire on open; when the sheet is replacing the sheet the person was in, it takes focus, and a `data-autofocus` descendant then wins (AR4). On close an explicit `finalFocusRef` is focused wherever focus is, and otherwise the element focused when the sheet was shown is focused again only while focus is still inside the sheet — the native dialog's own return rule, kept. | DEC-2; `spec:AST-027/FR8`; `architecture:layer-runtime` |
+| FR11 | A non-modal sheet (`hasScrim={false}`) is presented in the browser's top layer as a manual popover with no backdrop, no scroll lock, and no focus trap, and carries no page-level `z-index`; where the Popover API is absent it is presented with `show()` in page stacking order as a reduced fallback. A non-modal sheet shown while a modal dialog that does not contain it is open (a modal sheet, a `Dialog`) is inert under that modal, so it does not enter the top layer yet — there it would paint above the modal while a press on it lands on the modal — and is presented with `show()` beneath the modal, with no page-level `z-index`; a modal on its way out (inert and hidden, or holding focus under FR9) counts as gone. Once no such modal is open the sheet enters the top layer as a manual popover, a top-layer toast viewport re-entering above it (FR14), so page content never paints over an interactive non-modal sheet (`spec:AST-027` FR8). A non-modal sheet rendered inside the modal's content is not inert and enters the top layer at once. Non-modal sheets never stack, recede, or own a scrim, and never pair with a modal sheet; because they never stack, the one open non-modal sheet of a document is always the top of its own group, so two non-modal sheets replace each other under FR10 — the closing one being that top — with no backdrop. On a lone open, an eligible `data-autofocus` descendant — one inside the sheet's own dialog, neither hidden nor inert, that takes focus when asked — takes focus (AR4, the same rule as a modal sheet's); without one, focus goes where the engine's own `show()` focusing steps would put it when they enter the sheet: in Chromium the panel, whose focusing steps take the first focusable area including a `tabindex="-1"` container; in Firefox the first focusable control in the content; in WebKit wherever its `show()` lands. Where the manual-popover host's own focusing steps would land elsewhere than that engine's `show()` (Chromium's `showPopover()` lands on the first control), focus arrives where `show()` would have put it without passing through any control — no control receives a focus or a blur on the way, so a field validating on blur does not fire on open; when the sheet is replacing the sheet the person was in, it takes focus, and a `data-autofocus` descendant then wins (AR4). On close an explicit `finalFocusRef` is focused wherever focus is, and otherwise the element focused when the sheet was shown is focused again only while focus is still inside the sheet — the native dialog's own return rule, kept. | DEC-2; `spec:AST-027/FR8`; `architecture:layer-runtime` |
| FR12 | A modal `BottomSheetSwitcher` flow is one level of the stack: the dialog of its active step is the flow's level, keeps the flow's rank across the flow's own handoffs, recedes and is blocked when covered, yields its backdrop to the stack's scrim owner, stands down from dismissal while covered, and returns focus by FR9. A standalone sheet rendered in a step's content stacks above the flow and leaves with the step (FR8). A switcher step is never paired under FR10. | DEC-2; `component:BottomSheetSwitcher/DEC-1` |
| FR13 | Every open scrim sheet supplies its dialog as a passive global outlet for app-global surfaces such as toasts (`spec:AST-003` FR18: each active native modal, a covered sheet included), and a modal `BottomSheetSwitcher` flow supplies its active step's dialog — the one its host dialog resolves to, following each handoff; the retained step's dialog, inert and fading, never hosts. Among sheets, the latest outlet — the one a global host renders into — follows the stack's order, not the order the sheets were supplied in: the top sheet is the latest, so a toast lands in the top sheet and never in a covered, inert one, and when the top sheet closes the sheet it reveals is the latest again and takes the host back. A sheet is raised only among sheet outlets: an outlet supplied later by another modal (a `Dialog` opened from a sheet) stays above every sheet until it closes. A sheet, or a flow, stops supplying as soon as it starts closing, and a native `close` event that fires while its dialog is open again (the stack re-showing it, or a reopen during its exit) does not take its outlet away. | DEC-2; `spec:AST-003/FR16`, `/FR18`; `architecture:layer-runtime`; `component:BottomSheetSwitcher/FR10` |
| FR14 | When a non-modal sheet enters the top layer, a top-layer toast viewport shown before it leaves and re-enters the top layer in place, keeping focus inside it, so toasts paint above the sheet. | DEC-2; `architecture:layer-runtime` |
@@ -278,17 +279,20 @@ remain documented in `BottomSheet.doc.mjs`.
moves focus into it; a replace moves focus into the entering step whatever
the 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, and a sheet
- removed while open returns focus by FR20. A sheet opened on
- its own, modal or not, focuses wherever the engine's native focusing steps
- land when the released host presents it, with no `data-autofocus`
- preference added (the released behavior): in Chromium the panel, in Firefox
- the first focusable control in the content (a `data-autofocus` field when
- it comes first), in WebKit wherever its steps land; a non-modal sheet's
- manual-popover host lands where that engine's `show()` would have (FR11). The one deliberate
- exception is a sheet entering as a replacement (FR10), whose focus is
- placed after the native focusing steps because they may have left it in the
- replaced sheet, or on the entering panel: there a `data-autofocus` descendant is focused first, else
- the panel, so a step flow that opens on a field keeps the keyboard on it.
+ removed while open returns focus by FR20. A sheet that opens, on its own or
+ pushed over another sheet, modal or not, focuses its first eligible
+ `data-autofocus` descendant in every engine: one inside the sheet's own dialog, neither
+ hidden nor inert, that takes focus when asked (`component:Dialog` FR2's
+ eligibility). Where the engine's native focusing steps landed first (the
+ panel in Chromium, the first control in Firefox) does not count as placed.
+ Without an eligible descendant, focus stays where those steps landed: in
+ Chromium the panel, in Firefox the first focusable control in the content,
+ in WebKit wherever its steps land; a non-modal sheet's manual-popover host
+ lands where that engine's `show()` would have (FR11). A sheet entering as a
+ replacement (FR10) has its focus placed after the native focusing steps,
+ because they may have left it in the replaced sheet or on the entering
+ panel: there a `data-autofocus` descendant is focused first, else the
+ panel, so a step flow that opens on a field keeps the keyboard on it.
- **AR5 — What assistive technology perceives of a push, a pop, and a
replace.** The stack adds no announcement of its own to a push or a pop:
@@ -387,7 +391,7 @@ a decision that they must remain unthemeable.
| Element jobs | Open-sheet element count test against the named job list | modal and non-modal sheet, scrim and no scrim | An element in the open sheet's frame with no named job, or a named job with no element | |
| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target inventory | Missing, extra, prefixed, stale, or multiply assigned mappings fail repository validation. | `audit:BottomSheet/theming` |
| FR5–FR9, FR12–FR15, AR3–AR5 | Stacking unit suite (jsdom, native dialog methods stubbed); real-browser per-frame sampling of transforms, backdrop opacity, hit-testing, and focus on the stacking stories in Chromium, WebKit, and real Safari; a real-browser accessibility-tree check (`spec:AST-020`, `spec:AST-009` FR3) that a lone sheet, a stack of two and three, and a replace handoff expose exactly one `dialog`, the top or entering sheet, with its name, while covered and replaced sheets are hidden, that the stack renders no live region of its own, and that focus enters the entering step's `data-autofocus` field or panel on a replace; a real-browser run with reduced motion emulated on a fine and on a coarse pointer, sampling per frame that no transform animates, that the covered sheet is in its receded place from the frame the push lands, that on a coarse pointer the entering and leaving sheets change opacity only within 200 ms and on a fine pointer at once, that a swipe dismissal fades out in place on a fine pointer, that the dim is constant and that the handoff still completes; `BottomSheetCloseFocus.test.tsx` for FR9's close order | siblings, separate components, nested in content, inside a switcher step, a switcher flow as a level, out-of-tree-order opens, same-update deep link, depth 1–3, Escape/scrim/swipe/platform close, covered close, close of the whole stack, focus after each pop, two package copies, a second document | A covered or replaced sheet is exposed in the accessibility tree, the top sheet is exposed without role `dialog` or its name, a covered sheet stays interactive, a second backdrop paints, the dim dips or doubles on a handoff, a dismissal reaches a covered sheet, a nested sheet's state is written or it stays open invisibly, or focus lands on `body` after a pop or a close of the whole stack. | `audit:BottomSheet/behavior` |
-| FR10–FR11 | Replace unit suite (jsdom); real-browser parity of the standalone flow against the switcher's handoff — per-frame transforms, opacity, page dim, focus, settled pixels — in Chromium and WebKit, and real Safari for hosting, dim, toast order, and focus; a per-engine lone-open focus probe in Chromium, Firefox and WebKit comparing the sheet's focus on open against that engine's bare `show()` and `showModal()` on the same markup, and recording the focus and blur events the sheet's first control receives on open (none) | push, pop, different updates, covered close, nested, a replace above a covered sheet (the bottom sheet keeps the scrim, the retained sheet only fades), switcher flow, a lone sheet; handoff in both completion orders; reversal mid-handoff in both directions and both tree orders; unrelated owners from a page control; non-modal replace, reversal, `show()` fallback; a non-modal sheet opened from a modal sheet or a `Dialog` and rendered outside it (while the modal is open, and once it has closed, with positioned page content), one opened in the update that closes a modal sheet, and one rendered inside the modal's content | A replace is recognized for unrelated owners or missed for a real step flow, the retained sheet is exposed or dismissable, the scrim dips, the replaced step stays on screen after a reversal, focus does not enter the step or return to the flow's opener, a non-modal sheet carries a page-level `z-index`, a toast paints under a non-modal sheet, or a lone sheet's focus on open, modal or not, differs from where that engine's released native host (`showModal()`, or `show()` for a non-modal sheet) puts it — in Chromium the panel, with a ring only after keyboard input and a `data-autofocus` field left unfocused; in Firefox the first focusable control — a control inside the sheet receives a focus or a blur on a lone open that `show()` would not have given it, or a replacement entry fails to focus its `data-autofocus` field. A non-modal sheet rendered outside an open modal paints above it while a press lands on the modal, or stays beneath page content once that modal has gone. | `audit:BottomSheet/behavior` |
+| FR10–FR11 | Replace unit suite (jsdom); real-browser parity of the standalone flow against the switcher's handoff — per-frame transforms, opacity, page dim, focus, settled pixels — in Chromium and WebKit, and real Safari for hosting, dim, toast order, and focus; `BottomSheetAutofocus.a11y.browser.spec.ts` (a lone modal and non-modal sheet opened by a real pointer focus their `data-autofocus` field); a per-engine focus probe in Chromium, Firefox and WebKit for a sheet with no such field, against that engine's bare `show()` and `showModal()` on the same markup | push, pop, different updates, covered close, nested, a replace above a covered sheet (the bottom sheet keeps the scrim, the retained sheet only fades), switcher flow, a lone sheet; handoff in both completion orders; reversal mid-handoff in both directions and both tree orders; unrelated owners from a page control; non-modal replace, reversal, `show()` fallback; a non-modal sheet opened from a modal sheet or a `Dialog` and rendered outside it (while the modal is open, and once it has closed, with positioned page content), one opened in the update that closes a modal sheet, and one rendered inside the modal's content | A replace is recognized for unrelated owners or missed for a real step flow, the retained sheet is exposed or dismissable, the scrim dips, the replaced step stays on screen after a reversal, focus does not enter the step or return to the flow's opener, a non-modal sheet carries a page-level `z-index`, a toast paints under a non-modal sheet, or an opening sheet, lone or pushed, modal or not, leaves its first eligible `data-autofocus` field (AR4) unfocused (in Firefox, a control placed ahead of that field may get a focus and a blur first), or one with no such field lands elsewhere than its engine's native host (`showModal()`, or `show()`) puts it — in Chromium, its panel, with a ring only after keyboard input; in Firefox, the first focusable control — or a replacement entry fails to focus its `data-autofocus` field. A non-modal sheet rendered outside an open modal paints above it while a press lands on the modal, or stays beneath page content once that modal has gone. | `audit:BottomSheet/behavior` |
| FR13–FR14 | Toast viewport hosting suite (jsdom, native dialog methods and popover state stubbed); real-browser hit-testing of a toast raised from the top sheet, from a Dialog opened from a sheet after an inner sheet closed, from a sheet re-shown by a reversal, and over a non-modal sheet | a lone sheet; a stack of two; sheet → Dialog → sheet → close the inner sheet; a reversal and a reopen during exit, with the stale native `close`; a non-modal sheet shown after the viewport; a modal switcher flow alone, through a handoff and its close; a flow stacked over a standalone sheet and a standalone sheet over a flow; a non-modal flow | A toast renders in a covered or inert sheet, a Dialog opened from a sheet loses the toast to the sheet beneath it, a re-shown sheet loses its outlet to the stale `close`, a toast raised from a switcher step lands behind the flow or in its retained step, or a toast paints beneath a non-modal sheet. | `audit:BottomSheet/behavior` |
| 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` |
diff --git a/docs/specs/components/BottomSheet/BottomSheetSwitcher.spec.md b/docs/specs/components/BottomSheet/BottomSheetSwitcher.spec.md
index cac707ca21..acd70786dd 100644
--- a/docs/specs/components/BottomSheet/BottomSheetSwitcher.spec.md
+++ b/docs/specs/components/BottomSheet/BottomSheetSwitcher.spec.md
@@ -63,11 +63,14 @@ modality, identifier, and theming questions below stay open.
change under `spec:AST-017` FR3. The element the `ref` resolves
to, and that it changes on a handoff, is implementation rather than public
contract (DEC-2). A switcher flow presented on its own behaves as released,
- with two fixes: a toast raised from a step renders above the flow and can be
- pressed (FR10, `component:BottomSheet` FR13), where it rendered behind the
- flow before; and a flow whose active sheet is set on the server renders
- closed until hydration, then opens that sheet settled, with no entry motion
+ with three fixes: a toast raised from a step renders above the flow and can
+ be pressed (FR10, `component:BottomSheet` FR13), where it rendered behind the
+ flow before; a flow whose active sheet is set on the server renders closed
+ until hydration, then opens that sheet settled, with no entry motion
(`component:BottomSheet` FR17), where it painted open over a live page
+ before; and a step that opens with an eligible `data-autofocus` field (a
+ `TextInput` with `hasAutoFocus`) focuses that field in every engine
+ (`component:BottomSheet` AR4), where Chromium focused the step's panel
before.
A switcher flow presented while other sheets are open is one level of the
stack `component:BottomSheet` FR12 describes; that is behavior of the stack,
diff --git a/packages/core/src/BottomSheet/BottomSheet.doc.mjs b/packages/core/src/BottomSheet/BottomSheet.doc.mjs
index 8c20f980fb..0fb29c35f2 100644
--- a/packages/core/src/BottomSheet/BottomSheet.doc.mjs
+++ b/packages/core/src/BottomSheet/BottomSheet.doc.mjs
@@ -172,7 +172,7 @@ export const docs = {
usage: {
anatomy,
description:
- "A mobile touch surface for filters, actions, forms, and detail views that should rise from the bottom of the viewport. For a multi-step flow, give each step its own sheet and one state value that names the open step (see Replacing a sheet); open a second sheet over the first when a step should stay visible beneath it.\n\nStacking. Every sheet keeps its own isOpen. Open a sheet while another scrim sheet is open and it stacks on top: the sheet beneath stays mounted with its scroll position and inputs, recedes behind the new one (the nearest covered sheet shrinks to 0.96 and lifts 8px, deeper ones to 0.92 and 16px), and is blocked from pointer, keyboard, and assistive technology by the top sheet's modal dialog. The sheets can be siblings, live in separate components, sit inside another sheet's content, or sit inside a BottomSheetSwitcher step; a whole switcher is one level, and switching its step in place does not change its position. Nothing moves in the DOM: each sheet's dialog stays where it is written, and no wrapper component is needed.\n\nOrder is open order. The top sheet is the one presented most recently that is still open; a sheet that closes and reopens comes back on top. When several sheets open in one update (a deep link into a flow), there is no open order between them, so tree order decides: a sheet below the sheets rendered in its content, siblings in the order they are written. That order is right in the first painted frame.\n\nOne scrim. Only the bottom sheet's backdrop dims the page; the backdrops of the sheets above it are transparent, so a stack never darkens per level. The dim holds steady while sheets push and pop, and if the bottom sheet closes while sheets remain above it, the next sheet's backdrop takes over in the same frame.\n\nDismissal. Escape, a tap on the scrim, a downward swipe, and a platform close request (Android back, a close watcher) reach only the top sheet, through that sheet's own onOpenChange, and that sheet's purpose applies: required blocks all of them, form blocks the scrim and the swipe. Nothing closes a whole stack at once; set every sheet closed in one update when a flow is done and they leave together.\n\nClosing a covered sheet from code. Sheets rendered inside the closing sheet's content are part of it: they are presented only while it is open and leave with it. Their isOpen stays yours, as with a Dialog rendered in a closed Dialog: nothing is written to it, and a nested sheet that is still open when its host reopens is presented again, on top. Set it closed yourself when the flow is done. Sheets above the closing sheet that are not in its content stay open and keep their order; the closing sheet slides out from beneath them, and if it owned the scrim, the sheet above takes it over.\n\nReplacing a sheet. Close the top sheet and open another in the same update (one state value that names the open step does this) and the new sheet replaces it instead of stacking on it: the new sheet rises above the one it replaces; if the replaced sheet is taller it moves down to meet the new sheet's top edge at the same time; the replaced sheet fades only after both motions finish, and is inert and hidden from assistive technology from the start. The scrim holds steady throughout, with no dip; focus moves into the new sheet; and when the flow closes, focus returns to the element that opened its first sheet, whichever sheet closed last. This is the handoff the deprecated BottomSheetSwitcher ran between its steps; a multi-step flow needs no switcher: give each step its own BottomSheet and one state value. A replace happens only when exactly one sheet closes and one opens in the update, the closing sheet was the top sheet of its stack, and the move was made from inside it (the control last pressed, or with no recent press the focused element, was in the closing sheet, as a step's own Continue or Back button is); a covered sheet closing while a sheet opens, a close and an open in different updates, or a close and an open driven from a control outside the closing sheet (two unrelated owners acting at once) keep the ordinary push and pop motion and their own focus return. A replace over an open stack runs one level up and leaves the sheets beneath covered. Non-modal sheets (hasScrim={false}) replace each other the same way, with no scrim: they are hosted in the browser top layer as manual popovers, so the entering step orders above the retained one with no page-level z-index, and toasts raised before or while the sheet is open stay above it. Below the Popover API support floor (Tier 2 in the browser support guide) the sheet falls back to show() in page stacking order: usable, but with no promise over later page content. A non-modal sheet returns focus to its opener on close only while focus is still inside it; focus taken elsewhere on the live page stays there.\n\nFocus. Opening a sheet moves focus into it, wherever the engine's native dialog focusing steps land: the panel in Chromium, the first focusable control in Firefox (a data-autofocus field only when it comes first). A step entering as a replacement focuses a data-autofocus descendant first, so a flow that opens on a field keeps the keyboard on it. Closing the top sheet returns focus into the sheet it reveals: to the control that opened it when that control is still there, otherwise to the revealed sheet's panel. When the last sheet closes, the standalone rules apply: finalFocusRef, else the element that opened the sheet, with a focus ring only after keyboard input. When every sheet of a stack closes in one update, focus returns once, to the bottom sheet's finalFocusRef or opener, after the last dialog has closed.\n\nCaveats. A Dialog, AlertDialog, or Popover opened from a sheet paints above the sheet and does not make it recede; a sheet opened from inside that Dialog paints above the Dialog and stacks over the sheet beneath. Sheets with hasScrim={false} stay out of the stack entirely (they replace each other, but never stack, recede, or take the scrim). A sheet React hides (a suspended Suspense boundary, Activity mode=\"hidden\") leaves the stack and closes its dialog; when it is shown again it is presented again, on top. Only sheets rendered in the same document stack; a sheet inside an iframe is its own stack.",
+ "A mobile touch surface for filters, actions, forms, and detail views that should rise from the bottom of the viewport. For a multi-step flow, give each step its own sheet and one state value that names the open step (see Replacing a sheet); open a second sheet over the first when a step should stay visible beneath it.\n\nStacking. Every sheet keeps its own isOpen. Open a sheet while another scrim sheet is open and it stacks on top: the sheet beneath stays mounted with its scroll position and inputs, recedes behind the new one (the nearest covered sheet shrinks to 0.96 and lifts 8px, deeper ones to 0.92 and 16px), and is blocked from pointer, keyboard, and assistive technology by the top sheet's modal dialog. The sheets can be siblings, live in separate components, sit inside another sheet's content, or sit inside a BottomSheetSwitcher step; a whole switcher is one level, and switching its step in place does not change its position. Nothing moves in the DOM: each sheet's dialog stays where it is written, and no wrapper component is needed.\n\nOrder is open order. The top sheet is the one presented most recently that is still open; a sheet that closes and reopens comes back on top. When several sheets open in one update (a deep link into a flow), there is no open order between them, so tree order decides: a sheet below the sheets rendered in its content, siblings in the order they are written. That order is right in the first painted frame.\n\nOne scrim. Only the bottom sheet's backdrop dims the page; the backdrops of the sheets above it are transparent, so a stack never darkens per level. The dim holds steady while sheets push and pop, and if the bottom sheet closes while sheets remain above it, the next sheet's backdrop takes over in the same frame.\n\nDismissal. Escape, a tap on the scrim, a downward swipe, and a platform close request (Android back, a close watcher) reach only the top sheet, through that sheet's own onOpenChange, and that sheet's purpose applies: required blocks all of them, form blocks the scrim and the swipe. Nothing closes a whole stack at once; set every sheet closed in one update when a flow is done and they leave together.\n\nClosing a covered sheet from code. Sheets rendered inside the closing sheet's content are part of it: they are presented only while it is open and leave with it. Their isOpen stays yours, as with a Dialog rendered in a closed Dialog: nothing is written to it, and a nested sheet that is still open when its host reopens is presented again, on top. Set it closed yourself when the flow is done. Sheets above the closing sheet that are not in its content stay open and keep their order; the closing sheet slides out from beneath them, and if it owned the scrim, the sheet above takes it over.\n\nReplacing a sheet. Close the top sheet and open another in the same update (one state value that names the open step does this) and the new sheet replaces it instead of stacking on it: the new sheet rises above the one it replaces; if the replaced sheet is taller it moves down to meet the new sheet's top edge at the same time; the replaced sheet fades only after both motions finish, and is inert and hidden from assistive technology from the start. The scrim holds steady throughout, with no dip; focus moves into the new sheet; and when the flow closes, focus returns to the element that opened its first sheet, whichever sheet closed last. This is the handoff the deprecated BottomSheetSwitcher ran between its steps; a multi-step flow needs no switcher: give each step its own BottomSheet and one state value. A replace happens only when exactly one sheet closes and one opens in the update, the closing sheet was the top sheet of its stack, and the move was made from inside it (the control last pressed, or with no recent press the focused element, was in the closing sheet, as a step's own Continue or Back button is); a covered sheet closing while a sheet opens, a close and an open in different updates, or a close and an open driven from a control outside the closing sheet (two unrelated owners acting at once) keep the ordinary push and pop motion and their own focus return. A replace over an open stack runs one level up and leaves the sheets beneath covered. Non-modal sheets (hasScrim={false}) replace each other the same way, with no scrim: they are hosted in the browser top layer as manual popovers, so the entering step orders above the retained one with no page-level z-index, and toasts raised before or while the sheet is open stay above it. Below the Popover API support floor (Tier 2 in the browser support guide) the sheet falls back to show() in page stacking order: usable, but with no promise over later page content. A non-modal sheet returns focus to its opener on close only while focus is still inside it; focus taken elsewhere on the live page stays there.\n\nFocus. Opening a sheet, modal or not, focuses its data-autofocus field (a TextInput with hasAutoFocus) in every browser. Without one, focus goes wherever the engine's native dialog focusing steps land: the panel in Chromium, the first focusable control in Firefox. A step entering as a replacement also focuses a data-autofocus descendant first, so a flow that opens on a field keeps the keyboard on it. Closing the top sheet returns focus into the sheet it reveals: to the control that opened it when that control is still there, otherwise to the revealed sheet's panel. When the last sheet closes, the standalone rules apply: finalFocusRef, else the element that opened the sheet, with a focus ring only after keyboard input. When every sheet of a stack closes in one update, focus returns once, to the bottom sheet's finalFocusRef or opener, after the last dialog has closed.\n\nCaveats. A Dialog, AlertDialog, or Popover opened from a sheet paints above the sheet and does not make it recede; a sheet opened from inside that Dialog paints above the Dialog and stacks over the sheet beneath. Sheets with hasScrim={false} stay out of the stack entirely (they replace each other, but never stack, recede, or take the scrim). A sheet React hides (a suspended Suspense boundary, Activity mode=\"hidden\") leaves the stack and closes its dialog; when it is shown again it is presented again, on top. Only sheets rendered in the same document stack; a sheet inside an iframe is its own stack.",
bestPractices: [
{
guidance: true,
diff --git a/packages/core/src/BottomSheet/BottomSheet.test.tsx b/packages/core/src/BottomSheet/BottomSheet.test.tsx
index ebe168114c..a56e3c53ac 100644
--- a/packages/core/src/BottomSheet/BottomSheet.test.tsx
+++ b/packages/core/src/BottomSheet/BottomSheet.test.tsx
@@ -18,7 +18,7 @@ import {
afterEach,
onTestFinished,
} from 'vitest';
-import {act, render, screen, fireEvent} from '@testing-library/react';
+import {act, cleanup, render, screen, fireEvent} from '@testing-library/react';
import {Profiler, createRef, useState, type ReactNode} from 'react';
import {BottomSheet} from './BottomSheet';
import {BottomSheetEscapeContext} from './bottomSheetEscape';
@@ -4132,6 +4132,111 @@ describe('BottomSheet', () => {
});
});
+ describe('data-autofocus eligibility on open (AR4)', () => {
+ function openWith(content: ReactNode, hasScrim = true) {
+ render(
+ <BottomSheet
+ isOpen
+ onOpenChange={() => {}}
+ label="Filters"
+ hasScrim={hasScrim}>
+ {content}
+ </BottomSheet>,
+ );
+ }
+ const own = () => screen.getByRole('textbox', {name: 'Own'});
+
+ it('focuses the field over a control placed before it, modal or not', () => {
+ // Land on the first control, as Firefox's native focusing steps do, so
+ // the test shows that the native landing does not count as placed.
+ const landOnFirstControl = function (this: HTMLElement) {
+ this.setAttribute('open', '');
+ this.querySelector<HTMLElement>('button')?.focus();
+ };
+ HTMLDialogElement.prototype.showModal = vi.fn(landOnFirstControl);
+ HTMLElement.prototype.showPopover = vi.fn(landOnFirstControl);
+ for (const hasScrim of [true, false]) {
+ openWith(
+ <>
+ <button type="button">First action</button>
+ <input data-autofocus aria-label="Own" />
+ </>,
+ hasScrim,
+ );
+ expect(document.activeElement).toBe(own());
+ cleanup();
+ }
+ });
+
+ it('skips a field that belongs to a sheet nested in the content', () => {
+ openWith(
+ <>
+ <dialog>
+ <input data-autofocus aria-label="Nested" />
+ </dialog>
+ <input data-autofocus aria-label="Own" />
+ </>,
+ );
+ expect(document.activeElement).toBe(own());
+ });
+
+ it('skips an inert field', () => {
+ openWith(
+ <>
+ <div inert>
+ <input data-autofocus aria-label="Inert" />
+ </div>
+ <input data-autofocus aria-label="Own" />
+ </>,
+ );
+ expect(document.activeElement).toBe(own());
+ });
+
+ it('skips a field that is not rendered', () => {
+ // jsdom has no layout, so the visibility check reads `hidden` here.
+ const original = Object.getOwnPropertyDescriptor(
+ HTMLElement.prototype,
+ 'checkVisibility',
+ );
+ Object.defineProperty(HTMLElement.prototype, 'checkVisibility', {
+ configurable: true,
+ value(this: HTMLElement) {
+ return this.closest('[hidden]') == null;
+ },
+ });
+ try {
+ openWith(
+ <>
+ <input data-autofocus aria-label="Hidden" hidden />
+ <input data-autofocus aria-label="Own" />
+ </>,
+ );
+ expect(document.activeElement).toBe(own());
+ } finally {
+ if (original) {
+ Object.defineProperty(
+ HTMLElement.prototype,
+ 'checkVisibility',
+ original,
+ );
+ } else {
+ delete (HTMLElement.prototype as {checkVisibility?: unknown})
+ .checkVisibility;
+ }
+ }
+ });
+
+ it('moves on from a candidate that refuses focus', () => {
+ openWith(
+ <>
+ <div data-autofocus>Not focusable</div>
+ <input data-autofocus aria-label="Own" />
+ </>,
+ );
+ expect(document.activeElement).toBe(own());
+ });
+ });
+
describe('accessible name', () => {
it('warns in development when label is empty', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs b/packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs
index 56822dfbb2..600f3e6059 100644
--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs
+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs
@@ -147,7 +147,7 @@ export const docs = {
},
},
description:
- 'Deprecated: write each step as its own BottomSheet with isOpen, controlled by one state value that names the open step. Closing the top sheet and opening the next in the same update, from a control inside the open step, runs the same replace handoff (see BottomSheet, Replacing a sheet), with no sheetId and no switcher; a step changed from a control outside the flow (a page control, or code after focus left the step) closes and opens with ordinary push and pop motion. BottomSheetSwitcher keeps working until a future minor release removes it: a flow used on its own behaves as released (with two fixes: a toast raised from a step renders above the flow and can be pressed, and under reduced motion its steps follow the reduced-motion rule), and a flow stacked with other sheets is one level of the stack (it recedes and is blocked when covered, shares the one scrim, and stands down from dismissal while covered). Modal and hasScrim={false} flows migrate the same way. Coordinates multiple BottomSheets as a mutually exclusive flow. One activeSheet ID selects the only interactive sheet; during a handoff, the new sheet enters above the inert previous sheet. If the new sheet is shorter, the previous sheet simultaneously moves down until their top edges align, then fades after both transforms complete. Each child sheet renders its own native <dialog>: a modal flow presents each sheet with showModal(), as a standalone modal sheet does, so the browser supplies modality (the page is inert and focus stays in the top-layer dialog, so both hold across a handoff) and the switcher holds the shared body scroll lock once for the whole modal flow. A no-scrim flow presents each sheet with show() inside the isolated flow wrapper of the switcher, which orders the step dialogs with local values; this differs from a standalone hasScrim={false} sheet, which is hosted in the top layer as a manual popover with no page-level z-index, and it is one reason to migrate. The switcher coordinates the rest: one scrim paints at a time, focus returns to the element that opened the flow, its ref, id, and data-testid resolve to the dialog hosting the active sheet, and its other dialog props and handlers apply to every sheet dialog.',
+ 'Deprecated: write each step as its own BottomSheet with isOpen, controlled by one state value that names the open step. Closing the top sheet and opening the next in the same update, from a control inside the open step, runs the same replace handoff (see BottomSheet, Replacing a sheet), with no sheetId and no switcher; a step changed from a control outside the flow (a page control, or code after focus left the step) closes and opens with ordinary push and pop motion. BottomSheetSwitcher keeps working until a future minor release removes it: a flow used on its own behaves as released (with three fixes: a toast raised from a step renders above the flow and can be pressed, under reduced motion its steps follow the reduced-motion rule, and a step with a hasAutoFocus field opens on that field in every browser), and a flow stacked with other sheets is one level of the stack (it recedes and is blocked when covered, shares the one scrim, and stands down from dismissal while covered). Modal and hasScrim={false} flows migrate the same way. Coordinates multiple BottomSheets as a mutually exclusive flow. One activeSheet ID selects the only interactive sheet; during a handoff, the new sheet enters above the inert previous sheet. If the new sheet is shorter, the previous sheet simultaneously moves down until their top edges align, then fades after both transforms complete. Each child sheet renders its own native <dialog>: a modal flow presents each sheet with showModal(), as a standalone modal sheet does, so the browser supplies modality (the page is inert and focus stays in the top-layer dialog, so both hold across a handoff) and the switcher holds the shared body scroll lock once for the whole modal flow. A no-scrim flow presents each sheet with show() inside the isolated flow wrapper of the switcher, which orders the step dialogs with local values; this differs from a standalone hasScrim={false} sheet, which is hosted in the top layer as a manual popover with no page-level z-index, and it is one reason to migrate. The switcher coordinates the rest: one scrim paints at a time, focus returns to the element that opened the flow, its ref, id, and data-testid resolve to the dialog hosting the active sheet, and its other dialog props and handlers apply to every sheet dialog.',
props: [
{
name: 'ref',
@@ -192,7 +192,7 @@ export const docs = {
usage: {
anatomy,
description:
- "Deprecated: write each step as its own BottomSheet with isOpen, controlled by one state value that names the open step. Closing the top sheet and opening the next in the same update, from a control inside the open step, runs the same replace handoff (see BottomSheet, Replacing a sheet), with no sheetId and no switcher; a step changed from a control outside the flow (a page control, or code after focus left the step) closes and opens with ordinary push and pop motion. BottomSheetSwitcher keeps working until a future minor release removes it: a flow used on its own behaves as released (with two fixes: a toast raised from a step renders above the flow and can be pressed, and under reduced motion its steps follow the reduced-motion rule), and a flow stacked with other sheets is one level of the stack (it recedes and is blocked when covered, shares the one scrim, and stands down from dismissal while covered). Modal and hasScrim={false} flows migrate the same way. Set activeSheet to a nested BottomSheet's sheetId to open or switch steps, and to null to close.\n\nStacking. A scrim flow is one level in the stack of open sheets (see BottomSheet, Stacking). Open it while a standalone sheet is open and the flow sits on top of that sheet, which recedes and is blocked; open a standalone sheet while the flow is open, from a step's content or from anywhere else, and that sheet sits on top while the whole flow recedes as one. Switching the step in place never changes the flow's position. Escape, the scrim, a swipe, and a platform close request reach only the top level: the flow's onActiveSheetChange(null) when the flow is on top, the standalone sheet's onOpenChange(false) when that sheet is. A standalone sheet rendered inside a step's content is presented only while that step is the active one: it leaves when the flow switches step or closes, its isOpen stays yours, and it is presented again, on top, if the step returns while it is still open. Only the bottom level's backdrop dims the page. A no-scrim flow stays out of the stack.",
+ "Deprecated: write each step as its own BottomSheet with isOpen, controlled by one state value that names the open step. Closing the top sheet and opening the next in the same update, from a control inside the open step, runs the same replace handoff (see BottomSheet, Replacing a sheet), with no sheetId and no switcher; a step changed from a control outside the flow (a page control, or code after focus left the step) closes and opens with ordinary push and pop motion. BottomSheetSwitcher keeps working until a future minor release removes it: a flow used on its own behaves as released (with three fixes: a toast raised from a step renders above the flow and can be pressed, under reduced motion its steps follow the reduced-motion rule, and a step with a hasAutoFocus field opens on that field in every browser), and a flow stacked with other sheets is one level of the stack (it recedes and is blocked when covered, shares the one scrim, and stands down from dismissal while covered). Modal and hasScrim={false} flows migrate the same way. Set activeSheet to a nested BottomSheet's sheetId to open or switch steps, and to null to close.\n\nStacking. A scrim flow is one level in the stack of open sheets (see BottomSheet, Stacking). Open it while a standalone sheet is open and the flow sits on top of that sheet, which recedes and is blocked; open a standalone sheet while the flow is open, from a step's content or from anywhere else, and that sheet sits on top while the whole flow recedes as one. Switching the step in place never changes the flow's position. Escape, the scrim, a swipe, and a platform close request reach only the top level: the flow's onActiveSheetChange(null) when the flow is on top, the standalone sheet's onOpenChange(false) when that sheet is. A standalone sheet rendered inside a step's content is presented only while that step is the active one: it leaves when the flow switches step or closes, its isOpen stays yours, and it is presented again, on top, if the step returns while it is still open. Only the bottom level's backdrop dims the page. A no-scrim flow stays out of the stack.",
bestPractices: [
{
guidance: true,
diff --git a/packages/core/src/BottomSheet/__tests__/BottomSheetAutofocus.a11y.browser.spec.ts b/packages/core/src/BottomSheet/__tests__/BottomSheetAutofocus.a11y.browser.spec.ts
new file mode 100644
index 0000000000..9626447cc0
--- /dev/null
+++ b/packages/core/src/BottomSheet/__tests__/BottomSheetAutofocus.a11y.browser.spec.ts
@@ -0,0 +1,69 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file BottomSheetAutofocus.a11y.browser.spec.ts
+ * @input The `Core/BottomSheet` "Modal with a data-autofocus field" and "No
+ * scrim with a data-autofocus field" stories, and the stacking "Orders
+ * drill-in" story, in a built Storybook, opened with a real pointer.
+ * @output Browser evidence that a sheet that opens, lone or pushed, modal or
+ * not, focuses its `data-autofocus` field, in every engine, wherever the
+ * engine's own dialog focusing steps landed first.
+ * @position Cross-browser proof for focusSheetPanel's `open` placement
+ * (bottomSheetStack.ts); jsdom has no native dialog focusing steps, so it
+ * cannot show that the steps' landing on the panel is overridden.
+ */
+
+import {expect, test, 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();
+});
+
+async function openSheet(page: Page, story: string): Promise<void> {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-bottomsheet--${story}&viewMode=story`,
+ );
+ await page.getByRole('button', {name: 'Open sheet'}).click();
+}
+
+for (const {story, sheet, field} of [
+ {story: 'modal-autofocus', sheet: 'Edit note', field: 'Note'},
+ {story: 'no-scrim-autofocus', sheet: 'Filter places', field: 'Search'},
+]) {
+ test(`a lone sheet (${story}) focuses its data-autofocus field on open`, async ({
+ page,
+ }) => {
+ await openSheet(page, story);
+ const dialog = page.getByRole('dialog', {name: sheet});
+ await expect(dialog).toBeVisible();
+ await expect(dialog.getByRole('textbox', {name: field})).toBeFocused();
+ });
+}
+
+test('a sheet pushed over another sheet focuses its data-autofocus field on open', async ({
+ page,
+}) => {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-bottomsheetstacking--orders-drill-in&viewMode=story`,
+ );
+ await page.getByRole('button', {name: 'Open orders'}).click();
+ const orders = page.getByRole('dialog', {name: 'Orders'});
+ await orders.getByRole('button', {name: 'View'}).first().click();
+ await page.getByRole('button', {name: 'Edit note'}).click();
+ const editor = page.getByRole('dialog', {name: 'Edit delivery note'});
+ await expect(editor).toBeVisible();
+ await expect(
+ editor.getByRole('textbox', {name: 'Delivery note'}),
+ ).toBeFocused();
+});
diff --git a/packages/core/src/BottomSheet/bottomSheetStack.ts b/packages/core/src/BottomSheet/bottomSheetStack.ts
index 43ef887b16..51759ef3af 100644
--- a/packages/core/src/BottomSheet/bottomSheetStack.ts
+++ b/packages/core/src/BottomSheet/bottomSheetStack.ts
@@ -1884,15 +1884,37 @@ export function getBottomSheetBeneath(
// what it just focused. For an autofocused field that reveal is the mobile
// keyboard's, and it moves the document under a fixed sheet. useMobileKeyboard
// brings the field into view within the sheet instead.
+/** A field in a sheet nested in this content belongs to that sheet. */
+function focusFirstEligibleAutofocus(panel: HTMLElement): boolean {
+ const dialog = panel.closest('dialog');
+ for (const candidate of panel.querySelectorAll<HTMLElement>(
+ '[data-autofocus]',
+ )) {
+ if (
+ candidate.closest('dialog') !== dialog ||
+ candidate.closest('[inert]') != null ||
+ (typeof candidate.checkVisibility === 'function' &&
+ !candidate.checkVisibility())
+ ) {
+ continue;
+ }
+ candidate.focus({preventScroll: true});
+ if (candidate.ownerDocument.activeElement === candidate) {
+ return true;
+ }
+ }
+ return false;
+}
+
/**
- * Move focus into a sheet panel. Focus already inside the sheet stays put:
- * on `open` the native host has normally run its own focusing steps, which
- * land on the panel (`tabindex="-1"`), so a `data-autofocus` descendant is
- * reached only where the host moved nothing (a stubbed host, or a browser
- * whose focusing steps skipped the sheet) — the released behavior. On
- * `replace` the entering step takes focus whatever its modality and whatever
- * the host did, a `data-autofocus` descendant first; on `reveal` the panel
- * itself takes focus, with a ring only after keyboard input.
+ * Move focus into a sheet panel. On `reveal`, and on `replace` once a control
+ * inside has focus, focus stays put. On `open` and on `replace` the
+ * native host has run its own focusing steps, which may land on the panel
+ * (`tabindex="-1"`, as Chromium's do) or on the first control (Firefox); an
+ * eligible `data-autofocus` descendant then takes focus first, modal or not.
+ * Without one, an `open` keeps the native landing and a `replace` focuses the
+ * entering panel. On `reveal` the panel itself takes focus, with a ring only
+ * after keyboard input.
*/
export function focusSheetPanel(
panel: HTMLElement | null,
@@ -1916,26 +1938,32 @@ export function focusSheetPanel(
// Focus already inside this sheet's own content stays put. Focus inside a
// sheet rendered within this content (a closing nested sheet) does not
// count: that sheet's dialog is leaving, and this one is being revealed.
- // On a replace entry the native focusing steps have just run and may have
- // put focus on the panel itself; that is not a placement, so only focus on
- // a control inside the panel (the person's, or the field this placement
- // chose) stays put.
+ // On an open, the native focusing steps have just run. What they focused
+ // is not the person's choice. An eligible `data-autofocus` field takes
+ // focus over it. On a replace, focus the steps left on the entering panel
+ // is not a placement either, but focus on a control inside it stays put.
const activeElement = panel.ownerDocument.activeElement;
const isInsidePanel =
activeElement != null &&
panel.contains(activeElement) &&
activeElement.closest('dialog') === panel.closest('dialog');
- if (isInsidePanel && (reason !== 'replace' || activeElement !== panel)) {
+ if (
+ isInsidePanel &&
+ (reason === 'reveal' || (reason === 'replace' && activeElement !== panel))
+ ) {
return;
}
if (reason === 'reveal') {
focusForLastInput(panel);
return;
}
- const autofocus = panel.querySelector<HTMLElement>('[data-autofocus]');
- if (autofocus != null) {
- autofocus.focus({preventScroll: true});
- } else if (!isInsidePanel && (isModal || reason === 'replace')) {
+ if (
+ (isInsidePanel && activeElement?.hasAttribute('data-autofocus') === true) ||
+ focusFirstEligibleAutofocus(panel)
+ ) {
+ return;
+ }
+ if (!isInsidePanel && (isModal || reason === 'replace')) {
// A lone non-modal sheet takes no focus on open; the step replacing the
// one the person was in does, so the keyboard stays in the flow. Focus
// the native steps already put on the panel needs no second focus().