Skip to content

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

TypeScript

fix(BottomSheet): join the shared layer dismissal stack (#7225)

Harjoth Khara516c4541c0c8
diff --git a/.changeset/bottom-sheet-shared-escape.md b/.changeset/bottom-sheet-shared-escape.md
new file mode 100644
index 0000000000..5a2090a7be
--- /dev/null
+++ b/.changeset/bottom-sheet-shared-escape.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A standalone `BottomSheet` now joins the shared layer dismissal stack, so one Escape press closes only the top-most layer. A Popover, Dialog, or menu opened inside the sheet closes first, and the next press closes the sheet. `purpose="required"` still blocks Escape without letting the press close a layer behind it, a sheet that is animating out keeps the press, and the native close request answers with the same top-most and IME composition rules.
+
+@harjothkhara
diff --git a/apps/storybook/stories/BottomSheet.stories.tsx b/apps/storybook/stories/BottomSheet.stories.tsx
index af6319b2a0..46e2d94cf5 100644
--- a/apps/storybook/stories/BottomSheet.stories.tsx
+++ b/apps/storybook/stories/BottomSheet.stories.tsx
@@ -3,7 +3,8 @@
/**
* @file BottomSheet.stories.tsx
* @input BottomSheet, content primitives, and controlled story state
- * @output BottomSheet examples and native keyboard delegation browser fixtures
+ * @output BottomSheet examples plus keyboard delegation and nested-layer
+ * Escape browser fixtures
* @position Storybook coverage for BottomSheet presentation and interaction
*/
@@ -22,6 +23,7 @@ import {Text} from '@astryxdesign/core/Text';
import {TextInput} from '@astryxdesign/core/TextInput';
import {TextArea} from '@astryxdesign/core/TextArea';
import {CheckboxInput} from '@astryxdesign/core/CheckboxInput';
+import {Popover} from '@astryxdesign/core/Popover';
const meta: Meta<typeof BottomSheet> = {
title: 'Core/BottomSheet',
@@ -732,3 +734,55 @@ export const KeyboardDelegation: Story = {
);
},
};
+
+/** Escape closes only the top-most layer: a Popover opened inside the sheet first. */
+export const NestedPopover: Story = {
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ const [hasScrim, setHasScrim] = useState(false);
+ const [purpose, setPurpose] = useState<'info' | 'form' | 'required'>(
+ 'info',
+ );
+ return (
+ <>
+ <label>
+ Sheet purpose
+ <select
+ value={purpose}
+ onChange={event =>
+ setPurpose(event.target.value as 'info' | 'form' | 'required')
+ }>
+ {['info', 'form', 'required'].map(value => (
+ <option key={value} value={value}>
+ {value}
+ </option>
+ ))}
+ </select>
+ </label>
+ <CheckboxInput
+ label="Show scrim"
+ value={hasScrim}
+ onChange={setHasScrim}
+ />
+ <Button label="Open sheet" onClick={() => setIsOpen(true)} />
+ <BottomSheet
+ label="Reference"
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ hasScrim={hasScrim}
+ purpose={purpose}
+ height="tall"
+ snapPoints={['96px', '50%']}
+ padding={6}>
+ <Popover
+ label="Details"
+ hasAutoFocus={false}
+ content={<p>Nested information</p>}>
+ <Button label="About" />
+ </Popover>
+ <Button label="Close sheet" onClick={() => setIsOpen(false)} />
+ </BottomSheet>
+ </>
+ );
+ },
+};
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index 750ffcc37d..34a120b91e 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -239,12 +239,13 @@ active-cycle registration sequence. `useFocusTrap` adapts an active trap with `o
that stack.
Tooltip, HoverCard, Dialog, Lab Drawer, 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, BottomSheetSwitcher, and
-Lab Drawer additionally ask `shouldDismissOnCloseRequest()` before acting on
-native platform close requests. Other family members still use local Escape
-handling as listed in `family:overlay-dismissal`.
+MobileNav, BottomSheet, and BottomSheetSwitcher all register with the shared
+stack. Tooltip and HoverCard report current DOM presence; Popover and
+DropdownMenu register through `useFocusTrap`; Dialog, Lightbox, MobileNav,
+BottomSheet, BottomSheetSwitcher, and Lab Drawer 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 ccbb97a7f7..af6a5410c4 100644
--- a/docs/families/overlay-dismissal.md
+++ b/docs/families/overlay-dismissal.md
@@ -199,14 +199,14 @@ this record's current membership snapshot must be updated with it.
## Adoption and exceptions
-| Components or surface | Adoption | Current deviation or limitation |
-| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Dialog, AlertDialog, Popover, DropdownMenu root, MoreMenu, Lightbox, MobileNav, Lab Drawer | shared owner | none |
-| 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 | shared owner | none |
-| BottomSheet, CommandPalette, ContextMenu, DropdownMenuSubMenu, PowerSearchEditPopover | local only | Must migrate from component-specific listeners or registries to the shared owner |
+| Components or surface | Adoption | Current deviation or limitation |
+| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Dialog, AlertDialog, Popover, DropdownMenu root, MoreMenu, Lightbox, MobileNav, Lab Drawer | shared owner | none |
+| 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 | Table filtering owns controlled Popover state and discards its draft on close; TourStep routes Popover close to the Tour; ChatEmojiPicker owns controlled Popover state |
+| BottomSheet, BottomSheetSwitcher | shared owner | none |
+| CommandPalette, ContextMenu, DropdownMenuSubMenu, PowerSearchEditPopover | 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
not approved exceptions. Migration must preserve each component's existing focus,
@@ -217,8 +217,8 @@ modality, positioning, outside-dismissal, and open-state contracts.
| 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 |
+| FR2, FR3, FR4, FR6 | `layerDismissalInvariants.test.tsx` | nested same-DOM Dialogs, Lightbox over Dialog, Dialog in BottomSheet, 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, BottomSheet, 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/packages/core/src/BottomSheet/BottomSheet.spec.md b/packages/core/src/BottomSheet/BottomSheet.spec.md
index 794fd67591..998e15b21b 100644
--- a/packages/core/src/BottomSheet/BottomSheet.spec.md
+++ b/packages/core/src/BottomSheet/BottomSheet.spec.md
@@ -200,9 +200,9 @@ a decision that they must remain unthemeable.
and records that sheets retain local scrim and swipe behavior.
- `spec:AST-025` owns effective scroll measurement, overflow and containment,
automatic keyboard-owner selection, and focus continuity.
-- `family:overlay-dismissal` owns shared Escape and platform-close ordering and
- records BottomSheet's current local-only adoption gap. This anatomy backfill
- does not migrate that runtime behavior.
+- `family:overlay-dismissal` owns shared Escape and platform-close ordering. A
+ standalone BottomSheet registers with the shared stack while it is presented;
+ a switcher-hosted sheet is covered by BottomSheetSwitcher's registration.
## Verification map
diff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsx
index 8cd2514120..f6996e6d09 100644
--- a/packages/core/src/BottomSheet/BottomSheet.tsx
+++ b/packages/core/src/BottomSheet/BottomSheet.tsx
@@ -4,13 +4,14 @@
/**
* @file BottomSheet.tsx
- * @input Uses React, StyleX, core hooks/utils, named BottomSheetPanel, BottomSheetSwitcherContext
+ * @input Uses React, StyleX, core hooks, shared layer dismissal, named BottomSheetPanel, BottomSheetSwitcherContext
* @output Exports BottomSheet component and BottomSheetProps
* @position Public BottomSheet router plus private standalone/switcher hosts
*
* BottomSheet selects one of two focused hosts. A standalone host owns its
- * native dialog lifecycle; a switcher item participates in the parent's shared
- * dialog and transition state machine. Both render the same BottomSheetPanel,
+ * native dialog lifecycle and joins the shared layer dismissal stack; a
+ * switcher item participates in the parent's shared dialog, transition state
+ * machine, and dismissal registration. Both render the same BottomSheetPanel,
* which owns sheet presentation, content padding, gestures, mobile-keyboard
* accommodation, and motion completion.
*
@@ -21,6 +22,8 @@
* - /packages/core/src/BottomSheet/BottomSheet.test.tsx
* - /packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
* - /packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx
+ * - /packages/core/src/Layer/layerDismissalFamilies.test.tsx
+ * - /packages/core/src/Layer/layerDismissalInvariants.test.tsx
* - /apps/storybook/stories/BottomSheet.stories.tsx
* - /packages/cli/assets/templates/blocks/components/BottomSheet/BottomSheetShowcase.tsx
*/
@@ -41,7 +44,8 @@ import type {DialogPurpose} from '../Dialog';
import type {SpacingStep} from '../utils/types';
import {colorVars, durationVars, easeVars} from '../theme/tokens.stylex';
import {useDevWarning, useScrollLock} from '../hooks';
-import {isImeKeyEvent} from '../utils';
+import {LayerDepthProvider} from '../Layer/LayerDepthContext';
+import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {
BottomSheetPanel,
type BottomSheetPanelMotion,
@@ -254,10 +258,10 @@ function StandaloneBottomSheet({
: {kind: 'hidden'};
const dismissOnEscape = useCallback(() => {
- if (purpose !== 'required') {
+ if (isOpen && purpose !== 'required') {
onOpenChange(false);
}
- }, [onOpenChange, purpose]);
+ }, [isOpen, onOpenChange, purpose]);
const dismissOnLightInteraction = useCallback(() => {
if (purpose === 'info') {
onOpenChange(false);
@@ -329,34 +333,35 @@ function StandaloneBottomSheet({
isOpen && !label,
);
+ // Join the shared layer dismissal stack. The stack owns the Escape listener
+ // and routes each press to the top-most layer, so a Popover or Dialog opened
+ // inside this sheet takes the press before the sheet does. It also claims a
+ // composing Escape without dismissing anything.
+ //
+ // The sheet stays registered while it is presented, including its exit
+ // animation: a closing sheet is still on screen, so it swallows the press
+ // rather than letting it close a layer behind it. `required` blocks too.
+ const {shouldDismissOnCloseRequest} = useLayerDismissal({
+ isActive: shouldPresent,
+ escapeBehavior: isOpen && purpose !== 'required' ? 'close' : 'block',
+ onDismiss: dismissOnEscape,
+ getContainer: () => dialogRef.current,
+ isPresent: () => dialogRef.current?.open ?? false,
+ });
+
+ // The native `cancel` event is a close request the stack never saw a press
+ // for (Android back, the platform close watcher). Always preventDefault so
+ // the browser cannot close the controlled <dialog>, then answer with the
+ // stack's rules: only the top-most layer dismisses, and nothing dismisses
+ // during an IME composition.
const handleCancel = useCallback(
(event: React.SyntheticEvent<HTMLDialogElement>) => {
- // No IME guard here: `cancel` is a plain Event carrying no composition
- // state, and handleKeyDown claims a composing Escape before the browser
- // can raise the close request that would arrive here.
- event.preventDefault();
- dismissOnEscape();
- },
- [dismissOnEscape],
- );
- const handleKeyDown = useCallback(
- (event: React.KeyboardEvent<HTMLDialogElement>) => {
- if (event.key !== 'Escape') {
- return;
- }
- // Claim the key before reading it: an unclaimed Escape lets the browser
- // raise its own close request, which lands on handleCancel and dismisses
- // on the same keypress.
event.preventDefault();
- // An IME fires this keydown to cancel an in-progress composition, ahead
- // of compositionend. It is a composition cancel, not a dismissal command
- // — see utils/ime; Dialog and BottomSheetSwitcher guard the same way.
- if (isImeKeyEvent(event.nativeEvent)) {
- return;
+ if (shouldDismissOnCloseRequest()) {
+ dismissOnEscape();
}
- dismissOnEscape();
},
- [dismissOnEscape],
+ [dismissOnEscape, shouldDismissOnCloseRequest],
);
const handleClick = useCallback(
(event: React.MouseEvent<HTMLDialogElement>) => {
@@ -383,8 +388,7 @@ function StandaloneBottomSheet({
role={purpose === 'required' ? 'alertdialog' : undefined}
inert={!isOpen && isPresented ? true : undefined}
onCancel={handleCancel}
- onClick={handleClick}
- onKeyDown={handleKeyDown}>
+ onClick={handleClick}>
<div {...stylex.props(styles.positioner)}>
<BottomSheetPanel
{...props}
@@ -400,7 +404,7 @@ function StandaloneBottomSheet({
onScrimOpacity={handleScrimOpacity}
onElementChange={handlePanelElementChange}
onMotionComplete={handleMotionComplete}>
- {children}
+ <LayerDepthProvider>{children}</LayerDepthProvider>
</BottomSheetPanel>
</div>
<BottomSheetEdgeTint />
diff --git a/packages/core/src/BottomSheet/__tests__/BottomSheetKeyboard.a11y.browser.spec.ts b/packages/core/src/BottomSheet/__tests__/BottomSheetKeyboard.a11y.browser.spec.ts
index c460f193cb..4ea75abfcc 100644
--- a/packages/core/src/BottomSheet/__tests__/BottomSheetKeyboard.a11y.browser.spec.ts
+++ b/packages/core/src/BottomSheet/__tests__/BottomSheetKeyboard.a11y.browser.spec.ts
@@ -3,7 +3,8 @@
/**
* @file BottomSheetKeyboard.a11y.browser.spec.ts
* @input Built BottomSheet stories and real Chromium/WebKit keyboard input
- * @output Browser evidence for shared focus delegation, traversal, and native scrolling
+ * @output Browser evidence for shared focus delegation, traversal, native
+ * scrolling, and Escape reaching a nested layer before the sheet
* @position Cross-browser proof for useScrollableArea's contentOrViewport policy
*/
@@ -342,3 +343,70 @@ test('does not skip an aria-hidden first tab stop to delegate to a later action'
await page.keyboard.press(tabKey(browserName));
await expect(viewport).toBeFocused();
});
+
+// Issue #7194: one Escape press closes only the top-most layer. A Popover
+// opened inside the sheet takes the first press; the sheet takes the next.
+async function openNestedPopover(
+ page: Page,
+ {hasScrim, purpose}: {hasScrim: boolean; purpose: string},
+) {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-bottomsheet--nested-popover&viewMode=story`,
+ );
+ await page.getByLabel('Sheet purpose').selectOption(purpose);
+ if (hasScrim) {
+ await page.getByRole('checkbox', {name: 'Show scrim'}).check();
+ }
+ await page.getByRole('button', {name: 'Open sheet', exact: true}).click();
+ const openSheets = page.locator('dialog[open]');
+ await expect(openSheets).toHaveCount(1);
+ const about = page.getByRole('button', {name: 'About', exact: true});
+ // WebKit does not focus a button on mouse click, so open from the keyboard.
+ await about.focus();
+ await page.keyboard.press('Enter');
+ const details = page.getByText('Nested information');
+ await expect(details).toBeVisible();
+ await expect(about).toBeFocused();
+ return {openSheets, details};
+}
+
+for (const hasScrim of [false, true]) {
+ test(`${hasScrim ? 'modal' : 'non-modal'}: Escape closes the nested Popover before the sheet`, async ({
+ page,
+ }) => {
+ const {openSheets, details} = await openNestedPopover(page, {
+ hasScrim,
+ purpose: 'info',
+ });
+
+ await page.keyboard.press('Escape');
+ await expect(details).toBeHidden();
+ await expect(openSheets).toHaveCount(1);
+ await expect(
+ page.getByRole('button', {name: 'Close sheet', exact: true}),
+ ).toBeVisible();
+
+ await page.keyboard.press('Escape');
+ await expect(openSheets).toHaveCount(0);
+ });
+}
+
+test('required: Escape closes the nested Popover and never the sheet', async ({
+ page,
+}) => {
+ const {openSheets, details} = await openNestedPopover(page, {
+ hasScrim: true,
+ purpose: 'required',
+ });
+
+ await page.keyboard.press('Escape');
+ await expect(details).toBeHidden();
+ await expect(openSheets).toHaveCount(1);
+
+ await page.keyboard.press('Escape');
+ await page.waitForTimeout(500);
+ await expect(openSheets).toHaveCount(1);
+ await expect(
+ page.getByRole('alertdialog', {name: 'Reference'}),
+ ).toBeVisible();
+});
diff --git a/packages/core/src/Layer/layerDismissalFamilies.test.tsx b/packages/core/src/Layer/layerDismissalFamilies.test.tsx
index b4b6495163..60826849f5 100644
--- a/packages/core/src/Layer/layerDismissalFamilies.test.tsx
+++ b/packages/core/src/Layer/layerDismissalFamilies.test.tsx
@@ -2,8 +2,8 @@
/**
* @file layerDismissalFamilies.test.tsx
- * @input Uses vitest, @testing-library/react, Dialog, Lightbox, MobileNav,
- * HoverCard, Tooltip
+ * @input Uses vitest, @testing-library/react, BottomSheet, Dialog, Lightbox,
+ * MobileNav, HoverCard, Tooltip
* @output Tests that every overlay family shares the one dismissal stack
* @position Colocated with layerStack; the families' own behavior is tested in
* their own files, this one only asks who takes the press
@@ -12,7 +12,9 @@
* preventDefault()s it, so a family that is not on the stack cannot be reached
* once anything else is. Lightbox and MobileNav were that gap: both closed via
* the native `cancel` event alone, and a `required` Dialog underneath swallowed
- * every press before it got there.
+ * every press before it got there. Standalone BottomSheet was the same gap from
+ * the other side: its own keydown handler closed the sheet before a layer
+ * opened inside it could take the press.
*
* SYNC: When a new overlay family joins the stack, add it here.
*/
@@ -27,8 +29,10 @@ import {
afterAll,
afterEach,
} from 'vitest';
-import {render, screen} from '@testing-library/react';
+import {act, fireEvent, render, screen} from '@testing-library/react';
+import {useState} from 'react';
+import {BottomSheet} from '../BottomSheet/BottomSheet';
import {Dialog} from '../Dialog/Dialog';
import {HoverCard} from '../HoverCard/HoverCard';
import {Lightbox} from '../Lightbox/Lightbox';
@@ -73,6 +77,9 @@ beforeEach(() => {
) {
this.setAttribute('open', '');
});
+ HTMLDialogElement.prototype.show = vi.fn(function (this: HTMLDialogElement) {
+ this.setAttribute('open', '');
+ });
HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
this.removeAttribute('open');
});
@@ -228,6 +235,127 @@ describe('overlay families on the shared dismissal stack', () => {
});
});
+ describe('BottomSheet', () => {
+ function SheetWithDialog({onSheetChange}: {onSheetChange: () => void}) {
+ const [isDialogOpen, setIsDialogOpen] = useState(true);
+ return (
+ <BottomSheet
+ isOpen={true}
+ onOpenChange={onSheetChange}
+ hasScrim={false}
+ label="Sheet">
+ <Dialog
+ isOpen={isDialogOpen}
+ onOpenChange={setIsDialogOpen}
+ aria-label="Nested">
+ Nested
+ </Dialog>
+ </BottomSheet>
+ );
+ }
+
+ it('lets a layer opened inside it take the first Escape', () => {
+ const onSheetChange = vi.fn();
+ render(<SheetWithDialog onSheetChange={onSheetChange} />);
+
+ let first: KeyboardEvent | undefined;
+ act(() => {
+ first = pressEscape();
+ });
+
+ expect(getDialog('Nested')).not.toHaveAttribute('open');
+ expect(onSheetChange).not.toHaveBeenCalled();
+ expect(first?.defaultPrevented).toBe(true);
+
+ act(() => {
+ pressEscape();
+ });
+
+ expect(onSheetChange).toHaveBeenCalledTimes(1);
+ expect(onSheetChange).toHaveBeenCalledWith(false);
+ });
+
+ it('swallows the press when required, so nothing behind it closes', () => {
+ const onSheetChange = vi.fn();
+ const onDialogChange = vi.fn();
+
+ render(
+ <Dialog isOpen={true} onOpenChange={onDialogChange} aria-label="Host">
+ <BottomSheet
+ isOpen={true}
+ onOpenChange={onSheetChange}
+ purpose="required"
+ label="Required sheet">
+ Choose one
+ </BottomSheet>
+ </Dialog>,
+ );
+
+ const event = pressEscape();
+
+ expect(onSheetChange).not.toHaveBeenCalled();
+ expect(onDialogChange).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('stays open on a browser-initiated cancel when it is not top-most', () => {
+ const onSheetChange = vi.fn();
+ render(<SheetWithDialog onSheetChange={onSheetChange} />);
+
+ const event = fireCancel(getDialog('Sheet'));
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(onSheetChange).not.toHaveBeenCalled();
+ });
+
+ it('closes on a browser-initiated cancel when it is top-most', () => {
+ const onSheetChange = vi.fn();
+ render(
+ <BottomSheet isOpen={true} onOpenChange={onSheetChange} label="Sheet">
+ Content
+ </BottomSheet>,
+ );
+
+ const event = fireCancel(getDialog('Sheet'));
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(onSheetChange).toHaveBeenCalledWith(false);
+ });
+
+ it('keeps the press while it animates out, then hands it to the layer below', () => {
+ const onDialogChange = vi.fn();
+ function ClosingSheet() {
+ const [isOpen, setIsOpen] = useState(true);
+ return (
+ <BottomSheet isOpen={isOpen} onOpenChange={setIsOpen} label="Sheet">
+ <button type="button" onClick={() => setIsOpen(false)}>
+ Close sheet
+ </button>
+ </BottomSheet>
+ );
+ }
+
+ render(
+ <Dialog isOpen={true} onOpenChange={onDialogChange} aria-label="Host">
+ <ClosingSheet />
+ </Dialog>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Close sheet'}));
+ expect(getDialog('Sheet')).toHaveAttribute('open');
+
+ pressEscape();
+ expect(onDialogChange).not.toHaveBeenCalled();
+
+ fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {
+ propertyName: 'transform',
+ });
+ expect(getDialog('Sheet')).not.toHaveAttribute('open');
+
+ pressEscape();
+ expect(onDialogChange).toHaveBeenCalledWith(false);
+ });
+ });
+
describe('required Dialog', () => {
it('still swallows an Escape when it is alone', () => {
const onDialogChange = vi.fn();
diff --git a/packages/core/src/Layer/layerDismissalInvariants.test.tsx b/packages/core/src/Layer/layerDismissalInvariants.test.tsx
index 4f5bdaaea5..2f2d1d4461 100644
--- a/packages/core/src/Layer/layerDismissalInvariants.test.tsx
+++ b/packages/core/src/Layer/layerDismissalInvariants.test.tsx
@@ -2,7 +2,7 @@
/**
* @file layerDismissalInvariants.test.tsx
- * @input Uses vitest, @testing-library/react, Dialog, Lightbox
+ * @input Uses vitest, @testing-library/react, BottomSheet, Dialog, Lightbox
* @output Tests the one invariant the shared stack exists to hold
* @position Colocated with layerStack. `useLayerDismissal.test.tsx` covers the
* hook's mechanics against synthetic layers; this file asks the user's
@@ -21,9 +21,10 @@
*/
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
-import {render, screen, act} from '@testing-library/react';
+import {render, screen, act, fireEvent} from '@testing-library/react';
import {useState} from 'react';
+import {BottomSheet} from '../BottomSheet/BottomSheet';
import {Dialog} from '../Dialog/Dialog';
import {Lightbox} from '../Lightbox/Lightbox';
import {resetLayerStackForTests} from './layerStack';
@@ -415,3 +416,77 @@ describe('presence is asked at press time', () => {
expect(onScreen()).toEqual([]);
});
});
+
+describe('a standalone BottomSheet is one more layer', () => {
+ function Sheet({children}: {children?: React.ReactNode}) {
+ const [isOpen, setIsOpen] = useState(true);
+ return (
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ hasScrim={false}
+ label="Sheet">
+ {children}
+ </BottomSheet>
+ );
+ }
+
+ // The sheet keeps its <dialog> open through the exit animation; jsdom never
+ // runs it, so end it the way the panel's transition would.
+ function finishSheetExit() {
+ fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {
+ propertyName: 'transform',
+ });
+ }
+
+ beforeEach(() => {
+ HTMLDialogElement.prototype.show = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ });
+
+ it('peels a Dialog opened inside the sheet before the sheet', () => {
+ render(
+ <Sheet>
+ <Modal label="Inner" />
+ </Sheet>,
+ );
+
+ pressEscape();
+ expect(onScreen()).toEqual(['Sheet']);
+
+ pressEscape();
+ finishSheetExit();
+ expect(onScreen()).toEqual([]);
+ });
+
+ it('declines a close request while an IME composition is running', () => {
+ render(
+ <Sheet>
+ <input aria-label="field" />
+ </Sheet>,
+ );
+ const field = screen.getByLabelText('field');
+
+ act(() => {
+ field.dispatchEvent(
+ new CompositionEvent('compositionstart', {bubbles: true}),
+ );
+ });
+ const composingRequest = fireCancel('Sheet');
+ expect(composingRequest.defaultPrevented).toBe(true);
+ finishSheetExit();
+ expect(onScreen()).toEqual(['Sheet']);
+
+ act(() => {
+ field.dispatchEvent(
+ new CompositionEvent('compositionend', {bubbles: true}),
+ );
+ });
+ fireCancel('Sheet');
+ finishSheetExit();
+ expect(onScreen()).toEqual([]);
+ });
+});
diff --git a/packages/core/src/Layer/useLayerDismissal.ts b/packages/core/src/Layer/useLayerDismissal.ts
index 2dc2b8fa1e..1cb3feb6e0 100644
--- a/packages/core/src/Layer/useLayerDismissal.ts
+++ b/packages/core/src/Layer/useLayerDismissal.ts
@@ -97,10 +97,10 @@ 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, MobileNav,
+ * the menus built on it, Tooltip, HoverCard, Lightbox, MobileNav, BottomSheet,
* BottomSheetSwitcher and lab's `Drawer` register today.
*
- * `BottomSheet`, `CommandPalette`, `ContextMenu`, `DropdownMenuSubMenu`, and
+ * `CommandPalette`, `ContextMenu`, `DropdownMenuSubMenu`, and
* `PowerSearchEditPopover` still run their own Escape listeners. They stay safe
* next to the stack only because each claims the press at element level, and the
* stack stands down on an already-`defaultPrevented` press — but a registered