Skip to content

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

TypeScript

fix(core): audit BottomSheetSwitcher (#6184)

Cindy Zhang65dedfe9d1dd
diff --git a/.changeset/bottom-sheet-switcher-dismissal-order.md b/.changeset/bottom-sheet-switcher-dismissal-order.md
new file mode 100644
index 0000000000..cac7cee550
--- /dev/null
+++ b/.changeset/bottom-sheet-switcher-dismissal-order.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] BottomSheetSwitcher: let the topmost nested layer handle Escape before a non-modal flow.
+
+@cixzhang
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index ec499cb6c8..af2a0913ac 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -48,6 +48,10 @@
"component": "core/BottomSheet",
"reason": "BottomSheet owns no inline axis to mirror. The sheet is a centered column inside an insetInline: 0 container; its borders and top corner radii are identical on both inline edges; and its handle spans both inline edges with a centered pill. Motion and scrolling are block-axis only, and header and close chrome come from caller content."
},
+ {
+ "component": "core/BottomSheetSwitcher",
+ "reason": "BottomSheetSwitcher owns no direction-sensitive visual or interaction. Its shared dialog spans both axes symmetrically; sheet handoff, close, swipe, and alignment motion use only the block axis; and it owns no directional glyph, inline ordering, horizontal scroll action, or arrow-key behavior. Each child BottomSheet retains its own independently verified logical layout."
+ },
{
"component": "unknown/ChartTooltip",
"reason": "ChartTooltip uses explicitly physical left/right/top viewport placement and clamping. It has no logical start/end placement, direction-dependent control order, horizontal scrolling action, or coarse form hit target; tooltip rows inherit bidi layout without component-specific directional logic."
diff --git a/apps/storybook/stories/BottomSheetSwitcher.stories.tsx b/apps/storybook/stories/BottomSheetSwitcher.stories.tsx
index e912e8196a..2fbbc1259c 100644
--- a/apps/storybook/stories/BottomSheetSwitcher.stories.tsx
+++ b/apps/storybook/stories/BottomSheetSwitcher.stories.tsx
@@ -22,6 +22,10 @@ const meta: Meta<typeof BottomSheetSwitcher> = {
story: {inline: false, height: '560px'},
},
},
+ argTypes: {
+ ref: {control: false},
+ onCancel: {control: false},
+ },
decorators: [
Story => (
<div style={{minHeight: 480, padding: 32}}>
@@ -236,16 +240,34 @@ function MultiStepSwitcherExample({
);
}
+const openFlow: NonNullable<Story['play']> = async ({canvasElement}) => {
+ const trigger = canvasElement.querySelector('button');
+ if (trigger instanceof HTMLElement) {
+ trigger.click();
+ await new Promise(resolve => setTimeout(resolve, 500));
+ }
+};
+
export const HugContent: Story = {
name: 'Hug content',
render: () => <MultiStepSwitcherExample height="hug" />,
+ play: openFlow,
};
export const Capped: Story = {
render: () => <MultiStepSwitcherExample height="capped" />,
+ play: openFlow,
};
export const NoScrim: Story = {
name: 'No scrim',
render: () => <MultiStepSwitcherExample height="hug" hasScrim={false} />,
+ play: openFlow,
+};
+
+export const NarrowViewport: Story = {
+ name: 'Narrow viewport',
+ parameters: {viewport: {defaultViewport: 'mobile1'}},
+ render: () => <MultiStepSwitcherExample height="hug" />,
+ play: openFlow,
};
diff --git a/apps/storybook/stories/LayerDismissal.stories.tsx b/apps/storybook/stories/LayerDismissal.stories.tsx
index 8c73c40414..0c5004f0b9 100644
--- a/apps/storybook/stories/LayerDismissal.stories.tsx
+++ b/apps/storybook/stories/LayerDismissal.stories.tsx
@@ -522,9 +522,9 @@ function MobileNavAloneExample() {
export const MobileNavAlone: Story = {render: () => <MobileNavAloneExample />};
/**
- * A hover tip inside a non-modal bottom sheet. `BottomSheet` handles Escape
- * itself rather than through the shared stack, so one press closes the sheet
- * and the tip goes with it. A tip being up does not stop the sheet closing.
+ * A hover tip inside a non-modal bottom sheet. Both surfaces participate in
+ * the shared dismissal stack, so the first Escape closes only the tip and the
+ * next Escape closes the sheet.
*/
function SheetWithHoverTipExample() {
const [activeSheet, setActiveSheet] = useState<string | null>(null);
@@ -543,9 +543,8 @@ function SheetWithHoverTipExample() {
<BottomSheet sheetId="details" label="Details" height="hug">
<VStack gap={3} xstyle={sheetStyles.body}>
<Text type="body">
- Hover the button to show the tip, then press Escape. BottomSheet
- handles Escape itself, so one press closes the sheet and the tip
- goes with it.
+ Hover the button to show the tip, then press Escape. The first
+ press closes only the tip; the next press closes the sheet.
</Text>
<Tooltip content="A hover tip, showing">
<Button label="Hover me" variant="secondary" />
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index c78cb823f0..b13fac61ac 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -32,6 +32,7 @@ verified_by:
packages/core/src/Popover/Popover.test.tsx,
packages/core/src/DropdownMenu/DropdownMenu.test.tsx,
packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx,
+ packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx,
packages/core/src/hooks/useFocusTrap.test.tsx,
packages/core/src/hooks/useMenuHover.test.tsx,
packages/core/src/Toast/ToastViewport.test.tsx,
@@ -152,12 +153,13 @@ contract. The current shared stack registers present layers with `close` or
registration sequence. `useFocusTrap` adapts an active trap with `onEscape` into
that stack.
-Tooltip, HoverCard, Dialog, Popover, DropdownMenu, Lightbox, and MobileNav all
-register with the shared stack. Tooltip and HoverCard report current DOM presence;
-Popover and DropdownMenu register through `useFocusTrap`; Dialog, Lightbox, and
-MobileNav additionally ask `shouldDismissOnCloseRequest()` before acting on native
-platform close requests. Other family members still use local Escape handling as
-listed in `family:overlay-dismissal`.
+Tooltip, HoverCard, Dialog, Popover, DropdownMenu, Lightbox, MobileNav, and
+BottomSheetSwitcher all register with the shared stack. Tooltip and HoverCard
+report current DOM presence; Popover and DropdownMenu register through
+`useFocusTrap`; Dialog, Lightbox, MobileNav, and BottomSheetSwitcher additionally
+ask `shouldDismissOnCloseRequest()` before acting on native platform close
+requests. Other family members still use local Escape handling as listed in
+`family:overlay-dismissal`.
Outside interaction is not coordinated by the shared stack. Current paths are
independent:
diff --git a/docs/families/overlay-dismissal.md b/docs/families/overlay-dismissal.md
index 2bbaf0e92f..a57899abbe 100644
--- a/docs/families/overlay-dismissal.md
+++ b/docs/families/overlay-dismissal.md
@@ -16,6 +16,7 @@ verified_by:
packages/core/src/Layer/layerDismissalInvariants.test.tsx,
packages/core/src/Layer/layerDismissalFamilies.test.tsx,
packages/core/src/hooks/useFocusTrap.test.tsx,
+ packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx,
]
members:
[
@@ -192,7 +193,7 @@ this record's current membership snapshot must be updated with it.
| Tooltip, HoverCard | shared owner with DOM presence reporting | Neither provides nesting depth to descendant layers |
| Focus traps with `onEscape` | shared owner through `useFocusTrap` | They provide DOM containment, not descendant depth |
| BreadcrumbItem, ChatComposerInput, ComplexSelector, DateInput, DateRangeInput, DateTimeInput, Selector, MultiSelector, PowerSearch, BaseTypeahead, Typeahead, Tokenizer, SideNavHeading, SideNavItem, TabMenu, TopNavHeading, TopNavMenu, TopNavMegaMenu, Table, Lab TourStep, Lab ChatEmojiPicker | shared owner through `usePopover` or a composed Popover owner | Adaptive BottomSheet paths inherit BottomSheet's adoption gap; Table filtering owns controlled Popover state and discards its draft on close; TourStep routes Popover close to the Tour; ChatEmojiPicker owns controlled Popover state |
-| BottomSheetSwitcher | partial | Modal mode registers through `useFocusTrap`; non-modal mode retains local Escape handling |
+| BottomSheetSwitcher | shared owner | none |
| BottomSheet, CommandPalette, ContextMenu, DropdownMenuSubMenu, PowerSearchEditPopover, Lab Drawer | local only | Must migrate from component-specific listeners or registries to the shared owner |
The rows marked partial or local are current adoption gaps against FR1. They are
@@ -201,12 +202,12 @@ modality, positioning, outside-dismissal, and open-state contracts.
## Verification map
-| Contract | Verification | Representative members and states | Mutation or failure expectation |
-| ------------------ | ----------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
-| FR1, FR2, FR4, FR5 | `useLayerDismissal.test.tsx` | synthetic provider depth, same-DOM containment, unrelated, blocking, content-handled, present/absent | Removing depth, presence filtering, or event deferral sends Escape to the wrong surface |
-| FR2, FR3, FR4, FR6 | `layerDismissalInvariants.test.tsx` | nested same-DOM Dialogs, Lightbox over Dialog, platform cancel, IME | One request closes two surfaces, closes a host before its child, or dismisses during composition |
-| FR1, FR2, FR3, FR7 | `layerDismissalFamilies.test.tsx` | Dialog, Lightbox, MobileNav, Tooltip, HoverCard; controlled and blocking states | A family bypasses the stack, a lower member handles a request, or controlled ownership is ignored |
-| FR1 | `useFocusTrap.test.tsx` | active, nested, and deactivated traps with `onEscape` | A dismissible trap stays off the shared stack or nested traps respond together |
+| Contract | Verification | Representative members and states | Mutation or failure expectation |
+| ------------------ | ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
+| FR1, FR2, FR4, FR5 | `useLayerDismissal.test.tsx`; `BottomSheetSwitcher.test.tsx` | synthetic provider depth, same-DOM containment, non-modal switcher nesting, unrelated, blocking, content-handled, present/absent | Removing depth, presence filtering, or event deferral sends Escape to the wrong surface |
+| FR2, FR3, FR4, FR6 | `layerDismissalInvariants.test.tsx` | nested same-DOM Dialogs, Lightbox over Dialog, platform cancel, IME | One request closes two surfaces, closes a host before its child, or dismisses during composition |
+| FR1, FR2, FR3, FR7 | `layerDismissalFamilies.test.tsx` | Dialog, Lightbox, MobileNav, Tooltip, HoverCard; controlled and blocking states | A family bypasses the stack, a lower member handles a request, or controlled ownership is ignored |
+| FR1 | `useFocusTrap.test.tsx` | active, nested, and deactivated traps with `onEscape` | A dismissible trap stays off the shared stack or nested traps respond together |
## Decision links
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index aa3f969bd6..09710c3041 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -1256,6 +1256,11 @@
"path": "examples/blockquote/with-attribution",
"aliases": []
},
+ {
+ "name": "example-bottom-sheet-switcher-review-flow",
+ "path": "examples/bottom-sheet-switcher/review-flow",
+ "aliases": []
+ },
{
"name": "example-bottom-sheet-height-variants",
"path": "examples/bottom-sheet/height-variants",
diff --git a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs
new file mode 100644
index 0000000000..9556267b71
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.doc.mjs
@@ -0,0 +1,23 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'BottomSheetSwitcher',
+ name: 'Bottom Sheet Switcher — Review flow',
+ displayName: 'Bottom Sheet Switcher — Review flow',
+ description:
+ 'A two-step form flow that lets a person review settings, confirm them, or move back without replacing the shared dialog.',
+ isReady: true,
+ isShowcase: false,
+ aspectRatio: 3 / 4,
+ componentsUsed: [
+ 'BottomSheet',
+ 'BottomSheetSwitcher',
+ 'Button',
+ 'Heading',
+ 'Section',
+ 'Stack',
+ 'Text',
+ ],
+};
diff --git a/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.tsx b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.tsx
new file mode 100644
index 0000000000..09cb79db51
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetSwitcherReviewFlow.tsx
@@ -0,0 +1,75 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import {BottomSheet, BottomSheetSwitcher} from '@astryxdesign/core/BottomSheet';
+import {Button} from '@astryxdesign/core/Button';
+import {Heading} from '@astryxdesign/core/Heading';
+import {Section} from '@astryxdesign/core/Section';
+import {HStack, VStack} from '@astryxdesign/core/Stack';
+import {Text} from '@astryxdesign/core/Text';
+
+export default function BottomSheetSwitcherReviewFlow() {
+ const [activeSheet, setActiveSheet] = useState<string | null>(null);
+
+ return (
+ <>
+ <Button
+ label="Review settings"
+ onClick={() => setActiveSheet('review')}
+ />
+ <BottomSheetSwitcher
+ activeSheet={activeSheet}
+ onActiveSheetChange={setActiveSheet}>
+ <BottomSheet
+ sheetId="review"
+ label="Review notification settings"
+ height="hug"
+ purpose="form">
+ <Section padding={4}>
+ <VStack gap={4}>
+ <VStack gap={1}>
+ <Heading level={3}>Review settings</Heading>
+ <Text type="supporting" color="secondary">
+ Daily summaries will be sent by email.
+ </Text>
+ </VStack>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Cancel"
+ variant="secondary"
+ onClick={() => setActiveSheet(null)}
+ />
+ <Button
+ label="Continue"
+ onClick={() => setActiveSheet('confirm')}
+ />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ <BottomSheet sheetId="confirm" label="Confirm settings" height="hug">
+ <Section padding={4}>
+ <VStack gap={4}>
+ <VStack gap={1}>
+ <Heading level={3}>Confirm settings</Heading>
+ <Text type="supporting" color="secondary">
+ Your notification settings are ready to save.
+ </Text>
+ </VStack>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Back"
+ variant="secondary"
+ onClick={() => setActiveSheet('review')}
+ />
+ <Button label="Save" onClick={() => setActiveSheet(null)} />
+ </HStack>
+ </VStack>
+ </Section>
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ </>
+ );
+}
diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs b/packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs
index ad0ccc9164..840f31295d 100644
--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs
+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs
@@ -1,6 +1,28 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+/** @type {import('@astryxdesign/cli/authoring').ComponentAnatomyElement[]} */
+
+const anatomy = [
+ {
+ name: 'Shared dialog',
+ required: true,
+ description:
+ 'One native dialog that owns modality, focus, dismissal, and lifecycle for the complete flow.',
+ },
+ {
+ name: 'Sheet panels',
+ required: true,
+ description:
+ 'Direct BottomSheet children; exactly one is interactive while a previous panel may remain visible and inert during a handoff.',
+ },
+ {
+ name: 'Scrim',
+ required: false,
+ description:
+ 'Native dialog backdrop shown by the default scrim-backed modal presentation.',
+ },
+];
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
export const docs = {
name: 'BottomSheetSwitcher',
displayName: 'Bottom Sheet Switcher',
@@ -122,6 +144,17 @@ export const docs = {
description:
'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. The switcher owns one shared native <dialog>: modal flows call showModal() once for one top-layer boundary and one ::backdrop across the whole flow, while no-scrim flows use a non-modal show() shell. Its ref and shared DOM props target that dialog.',
props: [
+ {
+ name: 'ref',
+ type: 'Ref<HTMLDialogElement>',
+ description: 'Ref forwarded to the one shared native dialog.',
+ },
+ {
+ name: 'onCancel',
+ type: '(event: SyntheticEvent<HTMLDialogElement>) => void',
+ description:
+ 'Called before the switcher handles a native dialog cancel request. Calling preventDefault() keeps the controlled flow open.',
+ },
{
name: 'activeSheet',
type: 'string | null',
@@ -151,6 +184,7 @@ export const docs = {
},
],
usage: {
+ anatomy,
description:
"Coordinates a multi-step bottom-sheet flow in one shared dialog; set activeSheet to a nested BottomSheet's sheetId to open or switch steps, and to null to close.",
bestPractices: [
@@ -159,11 +193,21 @@ export const docs = {
description:
'Use when each step depends on the previous one and only one step needs attention at a time.',
},
+ {
+ guidance: true,
+ description:
+ 'Give every child a unique sheetId and non-empty label, choose its purpose to match dismissal requirements, and follow the WAI-ARIA Dialog (Modal) pattern for scrim-backed flows: https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/.',
+ },
{
guidance: false,
description:
"Don't split information across sheets when people need to compare it; use a full-page layout that keeps the relevant content visible together instead.",
},
+ {
+ guidance: false,
+ description:
+ "Don't use the switcher when multiple panels must stay interactive or visible together; activeSheet intentionally selects one interactive step.",
+ },
],
},
examples: [
@@ -201,6 +245,7 @@ export const docsDense = {
description:
'controller with one shared native dialog for mutually exclusive multi-step BottomSheets',
usage: {
+ anatomy,
description:
"Coordinates a multi-step bottom-sheet flow in one shared dialog; set activeSheet to a nested BottomSheet's sheetId to open or switch steps, and to null to close.",
bestPractices: [
@@ -209,11 +254,21 @@ export const docsDense = {
description:
'Use when each step depends on the previous one and only one step needs attention at a time.',
},
+ {
+ guidance: true,
+ description:
+ 'Give every child a unique sheetId and non-empty label, choose its purpose to match dismissal requirements, and follow the WAI-ARIA Dialog (Modal) pattern for scrim-backed flows: https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/.',
+ },
{
guidance: false,
description:
"Don't split information across sheets when people need to compare it; use a full-page layout that keeps the relevant content visible together instead.",
},
+ {
+ guidance: false,
+ description:
+ "Don't use the switcher when multiple panels must stay interactive or visible together; activeSheet intentionally selects one interactive step.",
+ },
],
},
};
diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.spec.md b/packages/core/src/BottomSheet/BottomSheetSwitcher.spec.md
new file mode 100644
index 0000000000..e3d8db27b1
--- /dev/null
+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.spec.md
@@ -0,0 +1,211 @@
+---
+schema_version: 3
+template_version: 4
+kind: component
+id: component:BottomSheetSwitcher
+authority: draft
+archive_reason: null
+superseded_by: null
+approved_by: null
+approved_at: null
+owners: [cixzhang]
+review_triggers: [public-api, behavior, layout, theming, accessibility]
+verified_by:
+ [
+ packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx,
+ apps/storybook/stories/BottomSheetSwitcher.stories.tsx,
+ scripts/check-knowledge.mjs,
+ ]
+modules: []
+families: [family:overlay-dismissal]
+design_specs: []
+architecture:
+ [
+ architecture:component-theming-surface,
+ architecture:layer-runtime,
+ architecture:public-component-api,
+ ]
+contributing: []
+system_specs: [spec:AST-002, spec:AST-027]
+---
+
+# BottomSheetSwitcher component contract
+
+## Intent
+
+BottomSheetSwitcher coordinates a mutually exclusive sequence of BottomSheet
+children inside one shared native dialog. This draft records verified shipped and
+remediated behavior without adding a prop, changing a default, or settling the
+open modality, hosting, identifier, or theming decisions below.
+
+## Compatibility and migration
+
+- Released default preserved: `yes`
+- Compatibility class: observational backfill plus a shared-dismissal conformance
+ fix; public props, defaults, exports, DOM ownership, and transition behavior stay
+ unchanged
+- Controlled/uncontrolled behavior: `activeSheet` remains fully controlled
+- Migration decision: none
+
+Consumer migration instructions belong in consumer docs and release notes.
+
+## Ownership boundary
+
+**Owns**
+
+- One shared native dialog for all directly nested BottomSheet children.
+- Which child sheet is active, retained during a handoff, or hidden.
+- Shared scrim, focus containment, scroll lock, Escape/platform-close routing,
+ and final focus return for the flow.
+
+**Does not own / non-goals**
+
+- A child sheet's panel, content, handle, height, snap points, swipe mechanics, or
+ local visual styling — owned by `component:BottomSheet`.
+- Page-level stacking or clipping escape — owned by
+ `architecture:layer-runtime` and `spec:AST-027`.
+- An ordered visible sheet stack — proposed separately by open `BottomSheetStack`
+ work and not part of this component.
+
+## Public concepts
+
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ------------------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | -------------------------------------- | ------------------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------ |
+| Active sheet | `null` or one nested BottomSheet `sheetId` | Selects the only interactive child, or closes the flow | All presentations | `null` is closed; the prop is required | `component:BottomSheetSwitcher` | released | A non-matching or duplicate id is not given a safe public fallback by the current contract |
+| Shared presentation | `true` / `false` through `hasScrim` | Selects the current modal scrim-backed host or non-modal no-scrim host | Entire flow | `true` | `component:BottomSheetSwitcher` | released | Boolean only |
+| Child identity | Non-empty `sheetId` on each direct BottomSheet child | Associates controlled selection, labeling, purpose, and transition state with a child | Direct nested BottomSheet children | none | `component:BottomSheet` | released | Empty ids warn and stay hidden; duplicate-id behavior is not specified |
+| Dismissal request | `onActiveSheetChange(null)` | Reports an allowed implicit close without taking control from the caller | Escape/platform close, scrim click, or swipe according to active child purpose | none | `component:BottomSheetSwitcher`; `family:overlay-dismissal` owns ordering | released | The caller may retain its controlled value |
+| Dialog surface | inherited dialog props plus `ref` and `onCancel` | Reaches the one shared native dialog | Entire flow | none | `component:BottomSheetSwitcher` | released | Component-owned semantics and handlers retain precedence |
+
+## Behavioral and layout contract
+
+Draft requirements identify their basis so observed code is not mistaken for an
+intentional decision. This draft cannot clear the gaps it records.
+
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------------------------------------- |
+| FR1 | Zero or one child sheet is interactive for each controlled `activeSheet` value; all other children are hidden or retained inert and `aria-hidden` during a transition. | Current source, docs, and tests | Verified shipped behavior |
+| FR2 | All child sheets share one native dialog. Opening the first sheet opens that dialog once; handoffs do not replace it. | Current source, docs, and tests | Verified shipped behavior |
+| FR3 | During a handoff, the entering sheet is above the retained sheet. A taller retained sheet aligns down to a shorter entering sheet, and the retained sheet fades only after required transform motion completes. | Current source and transition tests | Verified shipped behavior; exact visual treatment remains human-reviewed |
+| FR4 | Closing retains the outgoing sheet through its exit, then closes the dialog. A modal flow restores focus to the element captured when that modal flow opened. | Current source and focus tests | Verified shipped behavior |
+| FR5 | `hasScrim=true` uses `showModal()`, a native backdrop, focus containment, and page scroll lock. `hasScrim=false` uses `show()` without a backdrop or scroll lock and leaves the page interactive. | Current source, docs, tests, and Chromium evidence | Verified shipped behavior; the non-modal host remains a `spec:AST-027` conformance gap |
+| FR6 | The active child purpose governs implicit dismissal: `info` allows Escape, scrim click, and swipe; `form` allows Escape; `required` blocks all three and exposes `alertdialog`. | Current BottomSheet docs and switcher tests | Verified shipped behavior |
+| FR7 | While visible, the switcher participates in `family:overlay-dismissal`; one Escape or platform close request reaches only the topmost present layer, and descendants receive a deeper logical layer scope. | `family:overlay-dismissal` and the audit regression test | Settled remediation in this audit |
+| FR8 | A stale gesture from an outgoing sheet cannot change the shared scrim, and unmounting a retained sheet cannot keep the shared dialog open. | Current tests | Verified shipped behavior |
+| FR9 | The switcher forwards its ref, neutral dialog attributes, styling inputs, and composed handlers to the shared dialog while preserving its owned ARIA and dismissal behavior. | Current source, public API architecture, and tests | Verified shipped behavior |
+
+### Allowed variation
+
+- **AV1 — Child content and panel geometry.** Child content, height, snap points,
+ and panel styling vary under `component:BottomSheet` without changing the
+ switcher's one-active-child protocol.
+- **AV2 — Transition timing.** Theme motion tokens may vary timing while preserving
+ the ordering and inertness in FR3.
+
+### Representative states
+
+| State | Required invariant | Allowed variation |
+| ---------- | --------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
+| Closed | Shared dialog is closed and no child is interactive. | Child panels may remain mounted but hidden. |
+| First open | Matching child is visible and interactive in one shared dialog. | Child-owned height and content. |
+| Handoff | Entering child is interactive; retained child is visible but inert and hidden from accessibility APIs until it fades. | Alignment offset depends on measured panel geometry. |
+| Closing | Outgoing child is retained inert while exit motion completes; modal focus and scroll ownership remain until close. | Theme-controlled duration. |
+| Modal | Native modal host, backdrop, focus containment, and scroll lock are active. | Active child's `purpose` controls implicit dismissal. |
+| Non-modal | Native non-modal host has no backdrop or scroll lock and background content remains interactive. | The current clipping/stacking limitation is a conformance gap, not an allowed exception. |
+
+### Transformation and precedence order
+
+- **ORD1 — Handoff completion.** Select next child → mark previous child retained
+ and inert → start entering transform and any required retained alignment → wait
+ for both transforms → fade retained child → hide it.
+- **ORD2 — Label precedence.** Consumer `aria-label` wins; otherwise consumer
+ `aria-labelledby` wins; otherwise the active or retained child label names the
+ dialog.
+
+### Performance and resources
+
+- **PR1 — One shared host.** A flow keeps one dialog, focus boundary, scroll lock,
+ and backdrop across child handoffs rather than mounting a host for every child.
+- **PR2 — Stable child registration.** Parent rerenders and changing consumer ref
+ identities do not unregister a mounted child or cancel an active handoff.
+
+## Accessibility contract
+
+- **AR1 — Dialog semantics.** Modal presentations expose `aria-modal`; a required
+ child changes the implicit dialog role to `alertdialog`; every visible flow has
+ a consumer-provided or active-child-derived accessible name.
+- **AR2 — Focus and inertness.** Modal focus remains inside the dialog, retained
+ children are inert and `aria-hidden`, and focus returns after the final exit.
+- **AR3 — Ordered dismissal.** Escape and platform close follow
+ `family:overlay-dismissal`, including IME protection and topmost-layer ordering.
+
+## Design relationships
+
+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
+| ---------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------ | -------------- | ------------------ |
+| Shared dialog | Transparent host for the flow's interaction and accessibility boundary | Current source and public docs | Structural | FR2, FR5, AR1 |
+| Sheet panels | Delegate visible panel, content, handle, and gesture presentation to BottomSheet | `component:BottomSheet` draft as observational context | Prominent | FR1, FR3 |
+| Scrim | Optional native backdrop that dims and blocks the page in modal presentation | Current source and public docs | Supporting | FR5 |
+
+### Theming anatomy
+
+<!-- anatomy-theming:v1 -->
+
+```json
+{
+ "Shared dialog": {
+ "none": {
+ "reason": "intentional: The transparent dialog is hosting, positioning, event, and focus machinery rather than a stable painted part."
+ }
+ },
+ "Sheet panels": {
+ "delegatesTo": {"owner": "component:BottomSheet", "target": "bottom-sheet"}
+ },
+ "Scrim": {
+ "none": {
+ "reason": "reachability-gap: The switcher-owned native backdrop paints the scrim but has no current public theming target."
+ }
+ }
+}
+```
+
+## Family and system relationships
+
+- `family:overlay-dismissal` owns topmost Escape and platform-close ordering; the
+ switcher adopts that shared owner while visible.
+- `architecture:layer-runtime` owns native dialog behavior and current hosting.
+- `architecture:component-theming-surface` owns anatomy qualification and target
+ disposition.
+- `architecture:public-component-api` and `spec:AST-002` own the released prop,
+ DOM, ref, and compatibility surface.
+- `spec:AST-027` identifies the non-modal `show()` plus page-level `z-index` path
+ as a migration gap; this draft does not treat it as an exception.
+
+## Verification map
+
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ---------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |
+| FR1–FR4, FR8 | `BottomSheetSwitcher.test.tsx` | closed, first open, handoffs in either completion order, rapid replacement, unmount, close | A child becomes interactive at the wrong time, a retained child disappears early, or the shared host lifecycle breaks. | `audit:BottomSheetSwitcher/behavior` |
+| FR5–FR7, AR1–AR3 | `BottomSheetSwitcher.test.tsx`; Chromium evidence | modal/non-modal, info/form/required, nested layer, IME, focus return | Modality, dismissal order, naming, inertness, scroll lock, or focus behavior diverges. | `audit:BottomSheetSwitcher/accessibility` |
+| FR9 | `BottomSheetSwitcher.test.tsx`; export checks | ref, DOM/ARIA/data/events, class, style, xstyle | A supported input is dropped or overrides component-owned semantics accidentally. | `audit:BottomSheetSwitcher/api` |
+| Theming anatomy | `scripts/check-knowledge.mjs`; theming tests | dialog, delegated sheet panel, scrim | A non-painting host gains a target, a delegated panel loses its owner, or the scrim gap disappears without review. | `audit:BottomSheetSwitcher/theming` |
+
+## Decision log
+
+None. This draft records observed behavior and one remediation already required by
+current shared authority; it introduces no component-local design or API decision.
+
+## Open questions
+
+- **OQ1 — Should modality and scrim paint remain coupled behind `hasScrim`, or
+ become independent public concepts?** (`human-api`)
+- **OQ2 — What safe behavior should a non-matching or duplicate child `sheetId`
+ have?** (`human-api`)
+- **OQ3 — Should the switcher-owned scrim gain a public theming target?**
+ (`human-api`)
+
+## Content boundary
+
+This file does not duplicate consumer prop tables, audit scores, screenshots,
+BottomSheet panel mechanics, shared dismissal rules, or layer-hosting migration
+steps. It links to their owners.
diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx b/packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx
index ecb53f7f81..e5e4900beb 100644
--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx
@@ -11,9 +11,14 @@
*/
import {fireEvent, render, screen} from '@testing-library/react';
-import {createRef, useState} from 'react';
+import {
+ createRef,
+ useState,
+ type KeyboardEvent as ReactKeyboardEvent,
+} from 'react';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-import {useFocusTrap} from '../hooks';
+import {hasActiveFocusTrapEscape, useFocusTrap} from '../hooks';
+import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {BottomSheet} from './BottomSheet';
import {BottomSheetSwitcher} from './BottomSheetSwitcher';
@@ -131,6 +136,22 @@ function NestedEscapeTrap({onEscape}: {onEscape: () => void}) {
);
}
+function NestedDismissibleLayer({onDismiss}: {onDismiss: () => void}) {
+ const [isOpen, setIsOpen] = useState(true);
+ useLayerDismissal({
+ isActive: isOpen,
+ onDismiss: () => {
+ setIsOpen(false);
+ onDismiss();
+ },
+ });
+ return (
+ <button type="button">
+ {isOpen ? 'Nested layer open' : 'Nested layer closed'}
+ </button>
+ );
+}
+
const panelRefA = (_element: HTMLDivElement | null) => {};
const panelRefB = (_element: HTMLDivElement | null) => {};
@@ -798,6 +819,117 @@ describe('BottomSheetSwitcher', () => {
expect(onActiveSheetChange).not.toHaveBeenCalled();
});
+ it('preserves the exported focus-trap Escape signal for a modal switcher', () => {
+ expect(hasActiveFocusTrapEscape()).toBe(false);
+
+ const {unmount} = render(
+ <BottomSheetSwitcher activeSheet="details" onActiveSheetChange={() => {}}>
+ <BottomSheet sheetId="details" label="Details">
+ Content
+ </BottomSheet>
+ </BottomSheetSwitcher>,
+ );
+
+ expect(hasActiveFocusTrapEscape()).toBe(true);
+ unmount();
+ expect(hasActiveFocusTrapEscape()).toBe(false);
+ });
+
+ it('dismisses a non-modal flow when a consumer stops Escape propagation', () => {
+ const onActiveSheetChange = vi.fn();
+ const onKeyDown = vi.fn((event: ReactKeyboardEvent) => {
+ event.stopPropagation();
+ });
+ render(
+ <BottomSheetSwitcher
+ activeSheet="details"
+ onActiveSheetChange={onActiveSheetChange}
+ hasScrim={false}
+ onKeyDown={onKeyDown}>
+ <BottomSheet sheetId="details" label="Details">
+ Content
+ </BottomSheet>
+ </BottomSheetSwitcher>,
+ );
+
+ fireEvent.keyDown(getSharedDialog(), {key: 'Escape'});
+
+ expect(onKeyDown).toHaveBeenCalledTimes(1);
+ expect(onActiveSheetChange).toHaveBeenCalledWith(null);
+ });
+
+ it('honors a consumer that prevents the default Escape dismissal', () => {
+ const onActiveSheetChange = vi.fn();
+ const onKeyDown = vi.fn((event: ReactKeyboardEvent) => {
+ event.preventDefault();
+ });
+ render(
+ <BottomSheetSwitcher
+ activeSheet="details"
+ onActiveSheetChange={onActiveSheetChange}
+ hasScrim={false}
+ onKeyDown={onKeyDown}>
+ <BottomSheet sheetId="details" label="Details">
+ Content
+ </BottomSheet>
+ </BottomSheetSwitcher>,
+ );
+
+ fireEvent.keyDown(getSharedDialog(), {key: 'Escape'});
+
+ expect(onKeyDown).toHaveBeenCalledTimes(1);
+ expect(onActiveSheetChange).not.toHaveBeenCalled();
+ });
+
+ it('lets a nested registered layer handle Escape before a non-modal switcher', () => {
+ const onActiveSheetChange = vi.fn();
+ const onNestedDismiss = vi.fn();
+ render(
+ <BottomSheetSwitcher
+ activeSheet="details"
+ onActiveSheetChange={onActiveSheetChange}
+ hasScrim={false}>
+ <BottomSheet sheetId="details" label="Details">
+ <NestedDismissibleLayer onDismiss={onNestedDismiss} />
+ </BottomSheet>
+ </BottomSheetSwitcher>,
+ );
+
+ const trigger = screen.getByRole('button', {name: 'Nested layer open'});
+ trigger.focus();
+ fireEvent.keyDown(trigger, {key: 'Escape'});
+
+ expect(onNestedDismiss).toHaveBeenCalledTimes(1);
+ expect(onActiveSheetChange).not.toHaveBeenCalled();
+
+ fireEvent.keyDown(document, {key: 'Escape'});
+
+ expect(onNestedDismiss).toHaveBeenCalledTimes(1);
+ expect(onActiveSheetChange).toHaveBeenCalledWith(null);
+ });
+
+ it('keeps a non-modal switcher open when a platform close targets it under a nested layer', () => {
+ const onActiveSheetChange = vi.fn();
+ const onNestedDismiss = vi.fn();
+ render(
+ <BottomSheetSwitcher
+ activeSheet="details"
+ onActiveSheetChange={onActiveSheetChange}
+ hasScrim={false}>
+ <BottomSheet sheetId="details" label="Details">
+ <NestedDismissibleLayer onDismiss={onNestedDismiss} />
+ </BottomSheet>
+ </BottomSheetSwitcher>,
+ );
+
+ const event = new Event('cancel', {cancelable: true});
+ getSharedDialog().dispatchEvent(event);
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(onNestedDismiss).not.toHaveBeenCalled();
+ expect(onActiveSheetChange).not.toHaveBeenCalled();
+ });
+
it('returns focus to the original opener after a multi-sheet flow ends', () => {
render(<Flow />);
const opener = screen.getByRole('button', {name: 'Start flow'});
diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx b/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
index d3366f7044..cf8bfc472c 100644
--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
@@ -4,7 +4,7 @@
/**
* @file BottomSheetSwitcher.tsx
- * @input Uses React context, StyleX, theme tokens, focus/scroll-lock hooks, BottomSheetSwitcherContext
+ * @input Uses React context, StyleX, theme tokens, shared layer dismissal, focus/scroll-lock hooks, BottomSheetSwitcherContext
* @output Exports BottomSheetSwitcher and BottomSheetSwitcherProps
* @position Core switcher for mutually exclusive BottomSheet flows
*
@@ -24,6 +24,7 @@
* - /packages/core/src/BottomSheet/BottomSheet.tsx
* - /packages/core/src/BottomSheet/BottomSheetEdgeTint.tsx
* - /packages/core/src/BottomSheet/BottomSheetSwitcher.doc.mjs
+ * - /packages/core/src/BottomSheet/BottomSheetSwitcher.spec.md
* - /packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx
* - /packages/core/src/BottomSheet/index.ts
* - /apps/storybook/stories/BottomSheetSwitcher.stories.tsx
@@ -45,8 +46,15 @@ import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '../BaseProps';
import type {DialogPurpose} from '../Dialog';
import {colorVars, durationVars, easeVars} from '../theme/tokens.stylex';
-import {hasActiveFocusTrapEscape, useFocusTrap, useScrollLock} from '../hooks';
-import {composeEventHandlers, isImeKeyEvent, mergeProps} from '../utils';
+import {useScrollLock} from '../hooks';
+import {
+ useFocusTrap,
+ useFocusTrapEscapeCompatibilitySignal,
+} from '../hooks/useFocusTrap';
+import {LayerDepthProvider} from '../Layer/LayerDepthContext';
+import {dispatchLayerEscapeKeyDown} from '../Layer/layerStack';
+import {useLayerDismissal} from '../Layer/useLayerDismissal';
+import {composeEventHandlers, mergeProps} from '../utils';
import {BottomSheetEdgeTint} from './BottomSheetEdgeTint';
import {
BottomSheetSwitcherContext,
@@ -203,6 +211,16 @@ export interface BottomSheetSwitcherProps extends BaseProps<HTMLDialogElement> {
* Coordinates a set of BottomSheets so zero or one is active at a time inside
* one shared native dialog. During a handoff the previous panel stays visible
* and inert beneath the entering panel, then fades after motion completes.
+ *
+ * @example
+ * ```
+ * <BottomSheetSwitcher
+ * activeSheet={activeSheet}
+ * onActiveSheetChange={setActiveSheet}>
+ * <BottomSheet sheetId="details" label="Details">…</BottomSheet>
+ * <BottomSheet sheetId="confirm" label="Confirm">…</BottomSheet>
+ * </BottomSheetSwitcher>
+ * ```
*/
export function BottomSheetSwitcher({
activeSheet,
@@ -282,7 +300,17 @@ export function BottomSheetSwitcher({
}, [allowsLightDismiss, onActiveSheetChange]);
const {containerRef} = useFocusTrap<HTMLDialogElement>({
isActive: isModal,
- onEscape: dismissOnEscape,
+ });
+ // Before the shared dismissal stack, this modal trap supplied `onEscape`, so
+ // the released compatibility shim reported it as active. Keep that signal
+ // without registering the switcher twice in the one shared stack.
+ useFocusTrapEscapeCompatibilitySignal(isModal);
+ const {shouldDismissOnCloseRequest} = useLayerDismissal({
+ isActive: isFlowVisible,
+ escapeBehavior: allowsEscapeDismiss ? 'close' : 'block',
+ onDismiss: dismissOnEscape,
+ getContainer: () => dialogRef.current,
+ isPresent: () => dialogRef.current?.open ?? false,
});
useScrollLock(isModal);
@@ -565,26 +593,21 @@ export function BottomSheetSwitcher({
const handleCancel = useCallback(
(event: SyntheticEvent<HTMLDialogElement>) => {
event.preventDefault();
- dismissOnEscape();
+ if (shouldDismissOnCloseRequest()) {
+ dismissOnEscape();
+ }
},
- [dismissOnEscape],
+ [dismissOnEscape, shouldDismissOnCloseRequest],
);
const handleKeyDown = useCallback(
(event: ReactKeyboardEvent<HTMLDialogElement>) => {
- // Modal Escape is owned by useFocusTrap so nested traps can win. A
- // non-modal switcher has no outer trap, so retain local dismissal while
- // deferring to an active nested layer and ignoring IME cancellation.
- if (
- !isModal &&
- event.key === 'Escape' &&
- !isImeKeyEvent(event.nativeEvent) &&
- !hasActiveFocusTrapEscape()
- ) {
- event.preventDefault();
- dismissOnEscape();
- }
+ // A consumer may stop propagation without claiming Escape. Route that
+ // unprevented press now so the shared stack still chooses the top layer;
+ // its preventDefault marker makes the document listener a no-op if the
+ // event does continue bubbling.
+ dispatchLayerEscapeKeyDown(event.nativeEvent);
},
- [dismissOnEscape, isModal],
+ [],
);
const handleClick = useCallback(
(event: ReactMouseEvent<HTMLDialogElement>) => {
@@ -626,7 +649,7 @@ export function BottomSheetSwitcher({
{...(activeSheetPurpose === 'required'
? {role: 'alertdialog'}
: undefined)}>
- {children}
+ <LayerDepthProvider>{children}</LayerDepthProvider>
<BottomSheetEdgeTint />
</dialog>
</BottomSheetSwitcherContext>
diff --git a/packages/core/src/Layer/layerStack.ts b/packages/core/src/Layer/layerStack.ts
index b1842d305d..5f998f73bf 100644
--- a/packages/core/src/Layer/layerStack.ts
+++ b/packages/core/src/Layer/layerStack.ts
@@ -6,7 +6,8 @@
* @file layerStack.ts
* @input Uses the isImeKeyEvent predicate from utils/ime
* @output Exports the shared layer dismissal stack: registration, top-most
- * ordering, and the single document-level Escape listener
+ * ordering, the document-level Escape listener, and its internal local-event
+ * dispatcher
* @position Internal to the Layer system; consumed by useLayerDismissal, which
* is what overlays actually call. Not exported from the package root.
*
@@ -34,11 +35,12 @@
* ## Bubble phase, not capture
*
* The listener is on the BUBBLE phase so content inside a layer can claim the
- * press first, either by `stopPropagation()` (the press never reaches us) or by
- * `preventDefault()` (we see it and stand down). Editors are the motivating
- * case: Monaco and the rich-text editor use Escape to close their own find
- * widget or autocomplete, and that must win over dismissing the Dialog they sit
- * in. A capture-phase listener would take the press away from them.
+ * press first, either by `stopPropagation()` (the press never reaches the
+ * document listener) or by `preventDefault()` (we see it and stand down).
+ * A host whose public event prop can stop propagation may route the still-
+ * unprevented event through `dispatchLayerEscapeKeyDown` at its own boundary;
+ * the same stack still chooses the owner. Editors are why `preventDefault()`
+ * remains the explicit cancellation signal: their own Escape action must win.
*
* ## The stack, not the browser, decides
*
@@ -275,7 +277,16 @@ function dispatchEscape(): boolean {
return true;
}
-function handleKeyDown(event: KeyboardEvent): void {
+/**
+ * Resolve a keydown through the shared stack immediately.
+ *
+ * The document listener is the normal path. A host may call this at its own
+ * element boundary after a consumer handler when that handler can stop
+ * propagation before the event reaches `document`. The same stack still picks
+ * the owner, and `preventDefault()` records the decision so a bubbling event is
+ * not handled twice.
+ */
+export function dispatchLayerEscapeKeyDown(event: KeyboardEvent): void {
if (event.key !== 'Escape') {
return;
}
@@ -309,7 +320,7 @@ function startListening(): void {
if (isListening || typeof document === 'undefined') {
return;
}
- document.addEventListener('keydown', handleKeyDown);
+ document.addEventListener('keydown', dispatchLayerEscapeKeyDown);
document.addEventListener('compositionstart', handleCompositionStart, true);
document.addEventListener('compositionend', handleCompositionEnd, true);
document.addEventListener('blur', handleCompositionEnd, true);
@@ -320,7 +331,7 @@ function stopListening(): void {
if (!isListening || typeof document === 'undefined') {
return;
}
- document.removeEventListener('keydown', handleKeyDown);
+ document.removeEventListener('keydown', dispatchLayerEscapeKeyDown);
document.removeEventListener(
'compositionstart',
handleCompositionStart,
diff --git a/packages/core/src/Layer/useLayerDismissal.ts b/packages/core/src/Layer/useLayerDismissal.ts
index 60a913f944..626c0a3f87 100644
--- a/packages/core/src/Layer/useLayerDismissal.ts
+++ b/packages/core/src/Layer/useLayerDismissal.ts
@@ -97,9 +97,8 @@ export interface UseLayerDismissalReturn {
* The layer does NOT attach a key listener — the stack owns one listener and
* routes each Escape press to the top-most REGISTERED layer, so one press
* dismisses exactly one of them. Dialog (and what is built on it), Popover and
- * the menus built on it, Tooltip, HoverCard, Lightbox and MobileNav register
- * today; `BottomSheetSwitcher` registers through its focus trap when modal and
- * still handles its own press when not.
+ * the menus built on it, Tooltip, HoverCard, Lightbox, MobileNav and
+ * BottomSheetSwitcher register today.
*
* `BottomSheet`, `CommandPalette`, `ContextMenu`, `DropdownMenuSubMenu`,
* `PowerSearchEditPopover` and lab's `Drawer` still run their own Escape
diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.ts
index 7d460f1469..8e89f16ac9 100644
--- a/packages/core/src/hooks/useFocusTrap.ts
+++ b/packages/core/src/hooks/useFocusTrap.ts
@@ -5,8 +5,8 @@
/**
* @file useFocusTrap.ts
* @input Uses React useCallback, useEffect, useRef
- * @output Exports useFocusTrap hook for trapping focus within a container and
- * restoring focus to the previously-focused element on deactivation
+ * @output Exports useFocusTrap, the deprecated Escape-state shim, and an
+ * internal compatibility-signal hook
* @position Core hook; used by dialogs, modals, date pickers
*
* Based on WAI-ARIA dialog pattern:
@@ -41,6 +41,25 @@ export function hasActiveFocusTrapEscape(): boolean {
return activeEscapeTrapCount > 0;
}
+/**
+ * Keep the deprecated `hasActiveFocusTrapEscape` signal accurate for a focus
+ * trap whose Escape is coordinated by another registration in the shared
+ * stack. This hook is intentionally internal (not re-exported from `hooks`): it
+ * preserves the released read-only compatibility signal without creating a
+ * second dismissal owner.
+ */
+export function useFocusTrapEscapeCompatibilitySignal(isActive: boolean): void {
+ useEffect(() => {
+ if (!isActive) {
+ return;
+ }
+ activeEscapeTrapCount += 1;
+ return () => {
+ activeEscapeTrapCount -= 1;
+ };
+ }, [isActive]);
+}
+
/**
* Whether an element is currently perceivable/focusable — excludes ones hidden
* via `display:none`/`visibility:hidden` or inside an `inert`/`hidden` subtree,
@@ -213,15 +232,7 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(
getContainer: () => containerRef.current,
});
- useEffect(() => {
- if (!isEscapeTrap) {
- return;
- }
- activeEscapeTrapCount += 1;
- return () => {
- activeEscapeTrapCount -= 1;
- };
- }, [isEscapeTrap]);
+ useFocusTrapEscapeCompatibilitySignal(isEscapeTrap);
/**
* Focus the first focusable element.
diff --git a/packages/core/src/hooks/useFocusTrapEscapeShim.test.tsx b/packages/core/src/hooks/useFocusTrapEscapeShim.test.tsx
index 27624b41e9..fbf7fe62f4 100644
--- a/packages/core/src/hooks/useFocusTrapEscapeShim.test.tsx
+++ b/packages/core/src/hooks/useFocusTrapEscapeShim.test.tsx
@@ -9,9 +9,10 @@
* @position Testing; guards the deprecated public shim in useFocusTrap.ts
*
* The shim is public API. Its answer must not change now that Escape moved to
- * the shared stack: `BottomSheetSwitcher` gates its own dismissal on it, so a
- * shim that also counts tooltips, hover cards and dialogs tells the sheet a
- * trap is above it when none is, and the sheet stops closing.
+ * the shared stack: existing consumers still observe whether an
+ * Escape-participating focus trap is active. Families that never trapped focus
+ * stay out of this count; BottomSheetSwitcher preserves its historical modal
+ * signal without registering a second dismissal owner.
*
* SYNC: When useFocusTrap.ts changes, update tests to match new behavior
*/