Skip to content

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

TypeScript

fix(Dialog, Drawer): a backdrop press dismisses only when it starts and ends on the backdrop (#9613)

Cindy Zhangce667be4dd5a
diff --git a/.changeset/backdrop-press-start-end.md b/.changeset/backdrop-press-start-end.md
new file mode 100644
index 0000000000..4594e88aa6
--- /dev/null
+++ b/.changeset/backdrop-press-start-end.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A `Dialog` with `purpose="info"`, a `Drawer`'s scrim, and `CommandPalette` now close on a backdrop press only when the press both starts and ends on the backdrop. Selecting text in a field and releasing past the edge no longer closes it and loses the input. A press on the backdrop alone still closes it, with a mouse, a pen, or a finger.
+
+@cixzhang @duytbp
diff --git a/apps/storybook/stories/BackdropPressA11y.stories.tsx b/apps/storybook/stories/BackdropPressA11y.stories.tsx
new file mode 100644
index 0000000000..43fe6331db
--- /dev/null
+++ b/apps/storybook/stories/BackdropPressA11y.stories.tsx
@@ -0,0 +1,78 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file BackdropPressA11y.stories.tsx
+ * @input Dialog, Drawer and CommandPalette, each with a text field, opened
+ * from a button
+ * @output Fixtures for the Chromium check that a backdrop press dismisses only
+ * when it starts and ends on the backdrop; excluded from the visual matrix
+ * @position Browser fixtures for the shared backdrop-press rule
+ */
+
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {Button} from '@astryxdesign/core/Button';
+import {CommandPalette} from '@astryxdesign/core/CommandPalette';
+import {Dialog} from '@astryxdesign/core/Dialog';
+import {Drawer} from '@astryxdesign/core/Drawer';
+import {createStaticSource} from '@astryxdesign/core/Typeahead';
+
+const meta: Meta = {
+ title: 'A11y/BackdropPress',
+ tags: ['no-visual'],
+};
+
+export default meta;
+
+const NOTE = 'A long note to select with the pointer and release past the edge';
+
+const commands = createStaticSource([
+ {id: 'open', label: 'Open file'},
+ {id: 'save', label: 'Save file'},
+]);
+
+export const Members: StoryObj = {
+ render: function MembersStory() {
+ const [open, setOpen] = useState<'dialog' | 'drawer' | 'palette' | null>(
+ null,
+ );
+ const close = (isOpen: boolean) => {
+ if (!isOpen) {
+ setOpen(null);
+ }
+ };
+ return (
+ <>
+ <Button label="Open dialog" onClick={() => setOpen('dialog')} />
+ <Button label="Open drawer" onClick={() => setOpen('drawer')} />
+ <Button label="Open palette" onClick={() => setOpen('palette')} />
+ <Dialog
+ isOpen={open === 'dialog'}
+ onOpenChange={close}
+ aria-label="Note dialog">
+ <input
+ aria-label="Note"
+ defaultValue={NOTE}
+ style={{width: '100%'}}
+ />
+ </Dialog>
+ <Drawer
+ isOpen={open === 'drawer'}
+ onOpenChange={close}
+ label="Note drawer">
+ <input
+ aria-label="Note"
+ defaultValue={NOTE}
+ style={{width: '100%'}}
+ />
+ </Drawer>
+ <CommandPalette
+ isOpen={open === 'palette'}
+ onOpenChange={close}
+ aria-label="Commands"
+ searchSource={commands}
+ />
+ </>
+ );
+ },
+};
diff --git a/docs/families/overlay-dismissal.md b/docs/families/overlay-dismissal.md
index 6711a65a28..65addd6bb0 100644
--- a/docs/families/overlay-dismissal.md
+++ b/docs/families/overlay-dismissal.md
@@ -15,6 +15,7 @@ verified_by:
packages/core/src/Layer/useLayerDismissal.test.tsx,
packages/core/src/Layer/layerDismissalInvariants.test.tsx,
packages/core/src/Layer/layerDismissalFamilies.test.tsx,
+ packages/core/src/Layer/useBackdropPress.test.tsx,
packages/core/src/Drawer/Drawer.test.tsx,
packages/core/src/hooks/useFocusTrap.test.tsx,
packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx,
@@ -214,6 +215,14 @@ this record's current membership snapshot must be updated with it.
document calls for (`architecture:interaction-modality` INV1); a BottomSheet,
BottomSheetSwitcher, or Lightbox does the same in a Picture-in-Picture window.
+- **FR10 — A backdrop press starts and ends on the backdrop.** Dialog with
+ `purpose="info"`, Drawer's scrim, and CommandPalette through its Dialog
+ dismiss on a backdrop press only when the press both started and ended on
+ the backdrop. A press that crosses the member's edge either way, such as a
+ text selection or a slider drag released past the edge, does not dismiss
+ it, and a cancelled pointer ends the press. The rule is the same for a
+ mouse, a pen, and a finger, and these members share one implementation.
+
## Allowed component variation
- **AV1 — Focus.** Members own focus entry, containment, movement, and the
@@ -223,7 +232,8 @@ this record's current membership snapshot must be updated with it.
- **AV3 — Positioning and hosting.** Members may use native dialog placement,
CSS anchor positioning, fixed coordinates, or a component-owned host.
- **AV4 — Outside dismissal.** Members own whether and how pointer, hover,
- focus-loss, backdrop, touch, or gesture interaction dismisses them.
+ focus-loss, backdrop, touch, or gesture interaction dismisses them; the
+ backdrop press of the members FR10 names follows FR10.
- **AV5 — Open-state API.** Members own controlled and uncontrolled state,
defaults, callback names, and imperative commands.
- **AV6 — Presentation.** Members own animation, visual treatment, and theming
@@ -282,6 +292,7 @@ modality, positioning, outside-dismissal, and open-state contracts.
| FR8, FR9 | Real-browser second-document checks; implementation gap: only Dialog and Popover have them | Dialog, Popover, DropdownMenu, MoreMenu, ContextMenu, Selector, MultiSelector, TopNavHeading, TopNavMenu, TopNavMegaMenu, SideNavHeading, SideNavItem, Tooltip and HoverCard, each in a same-origin iframe and in a Picture-in-Picture window: opens and takes Escape in the document it renders in (an unpinned Tooltip only when no other member is present; a pinned Tooltip or HoverCard before the member beneath it), and returns focus in the opener's document | The member opens or ranks in another document, a pinned Tooltip lets Escape reach the member beneath it, or focus lands on the frame element, the page, or the body |
| FR8, FR9 | Real-browser second-document checks; implementation gap: none has them | BottomSheet, BottomSheetSwitcher, and Lightbox in a Picture-in-Picture window: opens, takes Escape, and returns focus to its return target there | The surface ranks in the page, or focus lands on the page or the body |
| FR8 | Source check over Drawer and MobileNav | Drawer and MobileNav rendered from a control in a second document | A page-level surface moves into the second document |
+| FR10 | `useBackdropPress.test.tsx`; `BackdropPress.a11y.chromium.spec.ts` | Dialog (`purpose="info"`), Drawer scrim, and CommandPalette, with a mouse and a finger: a press that starts and ends on the backdrop, one that starts inside and ends on it, one that starts on it and ends inside, a cancelled pointer, and a backdrop start followed by a press inside | A press that crosses the edge either way dismisses, a cancelled or earlier press carries over, or a press on the backdrop alone does not dismiss |
## Decision links
diff --git a/docs/specs/components/Drawer/Drawer.spec.md b/docs/specs/components/Drawer/Drawer.spec.md
index a65cee4a90..6ba13cce28 100644
--- a/docs/specs/components/Drawer/Drawer.spec.md
+++ b/docs/specs/components/Drawer/Drawer.spec.md
@@ -161,7 +161,7 @@ Consumer prop syntax and examples remain in `Drawer.doc.mjs`.
| FR3 | The desktop inline-size budget MUST accept pixel numbers or CSS lengths and remain bounded by the viewport. At or below 640px, page-reveal mode MUST preserve 56px and use `width` as a cap; full-mobile mode MUST override `width` with `100dvw`. | Current docs, styles, and width tests |
| FR4 | Visibility through Drawer-owned behavior MUST follow `isOpen`, from the render after hydration on (FR17). Uncanceled Escape routed by the shared stack and uncanceled modal-backdrop activation request `false` when `purpose` allows (FR15), and a `DrawerHeader` close action requests `false` through the callback it is given; Drawer prevents its handled native `cancel` event from closing the dialog directly. During controlled exit, Drawer keeps its host and content region mounted while rendering the caller's current `children`. | Current prop contract and lifecycle tests |
| FR5 | At open time, `hasScrim={true}` MUST select native `showModal()` with `aria-modal`, a focus trap, body scroll locking, and a visible backdrop; `hasScrim={false}` MUST select a manual Popover API host that leaves the page behind interactive. Changing `hasScrim` while open is not a supported native-mode transition. | Current source, docs, and initial-mode tests |
-| FR6 | An uncanceled modal root/backdrop click (`target === currentTarget` while live `hasScrim` is true) MUST request close when `purpose` is `info`, and MUST NOT for `form` or `required`. Descendant clicks and dialog-root clicks while live `hasScrim` is false MUST NOT request close, and non-modal presentation MUST NOT install an invisible outside-pointer dismissal plane. | Current click tests |
+| FR6 | An uncanceled press on the modal backdrop that starts and ends there (`target === currentTarget` for the pointer-down, the pointer-up, and the click, while live `hasScrim` is true; `family:overlay-dismissal` FR10) MUST request close when `purpose` is `info`, and MUST NOT for `form` or `required`; a press that crosses the drawer's edge either way MUST NOT request close. Descendant clicks and dialog-root clicks while live `hasScrim` is false MUST NOT request close, and non-modal presentation MUST NOT install an invisible outside-pointer dismissal plane. | Current click tests; `useBackdropPress.test.tsx` |
| FR7 | Drawer MUST NOT render a close control of its own. A visible close action is caller composition, normally `DrawerHeader` with `onOpenChange` (`component:DrawerHeader` FR3), which requests `false` through that callback without taking open-state ownership. | DEC-1; close-control suite |
| FR8 | Opening MUST present the native host, capture the element focused before opening, and attempt to focus the first rendered `[data-autofocus]` descendant, if any. After a completed controlled close releases the native host, Drawer MUST attempt to restore focus to the captured element. The non-modal host's synthetic `close` event MUST dispatch after that restore attempt — matching the task-queued native `dialog.close()` event — so a consumer close listener keeps the last word on final focus. | Current presence hook and focus tests |
| FR9 | Closing MUST retain the panel host, content region, edge, and native presentation while the exit remains visible and continue rendering the caller's current `children`. The transform transition is authoritative, a computed-duration backstop prevents a lost event from stranding the host, and native release and React hiding land together so no frame paints outside the top layer. | Current lifecycle tests and browser close-visibility guard |
diff --git a/packages/core/src/Dialog/Dialog.test.tsx b/packages/core/src/Dialog/Dialog.test.tsx
index ceaa155b58..2e8cc4aea3 100644
--- a/packages/core/src/Dialog/Dialog.test.tsx
+++ b/packages/core/src/Dialog/Dialog.test.tsx
@@ -1098,12 +1098,14 @@ describe('Dialog', () => {
const focus = vi.spyOn(HTMLElement.prototype, 'focus');
fireEvent.pointerDown(invoker);
+ fireEvent.pointerUp(invoker);
fireEvent.click(invoker);
const cancel = screen.getByRole('button', {name: 'Cancel'});
expect(cancel).toHaveFocus();
expect(focusCallsOn(focus, cancel)).toEqual([[{focusVisible: false}]]);
fireEvent.pointerDown(cancel);
+ fireEvent.pointerUp(cancel);
fireEvent.click(cancel);
expect(invoker).toHaveFocus();
expect(focusCallsOn(focus, invoker)).toEqual([[{focusVisible: false}]]);
@@ -1131,6 +1133,7 @@ describe('Dialog', () => {
const invoker = screen.getByRole('button', {name: 'Open dialog'});
invoker.focus();
fireEvent.pointerDown(invoker);
+ fireEvent.pointerUp(invoker);
fireEvent.click(invoker);
// WebKit's native close restores focus to the invoker with a ring before
@@ -1155,6 +1158,7 @@ describe('Dialog', () => {
const cancel = screen.getByRole('button', {name: 'Cancel'});
fireEvent.pointerDown(cancel);
+ fireEvent.pointerUp(cancel);
fireEvent.click(cancel);
expect(blur).toHaveBeenCalledTimes(1);
@@ -1626,6 +1630,8 @@ describe('Dialog', () => {
</Dialog>,
);
+ fireEvent.pointerDown(screen.getByTestId('click-dialog'));
+ fireEvent.pointerUp(screen.getByTestId('click-dialog'));
fireEvent.click(screen.getByTestId('click-dialog'));
expect(onClick).toHaveBeenCalledTimes(1);
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index 565ca54bda..d9b6965a00 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -52,6 +52,7 @@ import {LayerContentBoundary} from '../Layer/layerScopedContext';
import {layerClickBoundary} from '../Layer/layerClickBoundary';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
+import {useBackdropPress} from '../Layer/useBackdropPress';
import {useModalOutlet} from '../Layer/modalOutlet';
import {
colorVars,
@@ -84,6 +85,8 @@ import {focusForLastInput, isFocusLost} from '../utils/focusReturn';
import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
import {useMergedRefs} from '../hooks/useMergedRefs';
+
+type PointerHandler = (event: React.PointerEvent<HTMLDialogElement>) => void;
/**
* Calculate a directional translate offset for dialog entry animation.
* Returns a normalized vector from the trigger element toward the viewport
@@ -723,16 +726,16 @@ export function Dialog({
}
}, [isOpen, isInline, hasConsumerName, titleId]);
- // Handle backdrop click — when the user clicks the ::backdrop pseudo-element,
- // the event target is the <dialog> element itself; clicks on child content
- // always target the child. This avoids false positives from native browser
+ // A press on the ::backdrop targets the <dialog> itself, so native browser
// popups (date pickers, selects, color pickers) that render outside the
- // dialog's bounding rect.
- const handleClick = (event: React.MouseEvent<HTMLDialogElement>) => {
- if (event.target === event.currentTarget && allowBackdropClick) {
- onOpenChange(false);
- }
- };
+ // dialog's rect never count. The press must start and end there.
+ const handleBackdropPress = useCallback(() => {
+ onOpenChange(false);
+ }, [onOpenChange]);
+ const backdropPress = useBackdropPress(
+ handleBackdropPress,
+ allowBackdropClick,
+ );
// The native `cancel` event is the browser's own close-watcher firing: an
// Android back gesture, or a close request the stack never saw a press for.
@@ -890,8 +893,20 @@ export function Dialog({
// written.
{...layerClickBoundary({
...safeProps,
- onClick: chainEventHandlers(handleClick, onClickProp),
+ onClick: chainEventHandlers(backdropPress.onClick, onClickProp),
})}
+ onPointerDownCapture={chainEventHandlers(
+ backdropPress.onPointerDownCapture,
+ safeProps.onPointerDownCapture as PointerHandler | undefined,
+ )}
+ onPointerUpCapture={chainEventHandlers(
+ backdropPress.onPointerUpCapture,
+ safeProps.onPointerUpCapture as PointerHandler | undefined,
+ )}
+ onPointerCancelCapture={chainEventHandlers(
+ backdropPress.onPointerCancelCapture,
+ safeProps.onPointerCancelCapture as PointerHandler | undefined,
+ )}
onCancel={handleCancel}
aria-modal={isHydrating ? undefined : 'true'}
// The default aria-labelledby (from a DialogHeader title) is set
diff --git a/packages/core/src/Drawer/Drawer.test.tsx b/packages/core/src/Drawer/Drawer.test.tsx
index 73ba8adb10..d31f3819a2 100644
--- a/packages/core/src/Drawer/Drawer.test.tsx
+++ b/packages/core/src/Drawer/Drawer.test.tsx
@@ -466,6 +466,8 @@ describe('Drawer', () => {
Content
</Drawer>,
);
+ fireEvent.pointerDown(screen.getByRole('dialog'));
+ fireEvent.pointerUp(screen.getByRole('dialog'));
fireEvent.click(screen.getByRole('dialog'));
expect(handleClick).toHaveBeenCalledTimes(1);
expect(handleOpenChange).toHaveBeenCalledWith(false);
@@ -568,10 +570,42 @@ describe('Drawer', () => {
Content
</Drawer>,
);
+ fireEvent.pointerDown(screen.getByRole('dialog'));
+ fireEvent.pointerUp(screen.getByRole('dialog'));
fireEvent.click(screen.getByRole('dialog'));
expect(handleOpenChange).toHaveBeenCalledWith(false);
});
+ it("forwards the caller's pointer handlers when a child prevents default", () => {
+ const onPointerDown = vi.fn();
+ const onPointerUp = vi.fn();
+ const onPointerCancel = vi.fn();
+ render(
+ <Drawer
+ isOpen
+ onOpenChange={() => {}}
+ label="Details"
+ onPointerDown={onPointerDown}
+ onPointerUp={onPointerUp}
+ onPointerCancel={onPointerCancel}>
+ <button
+ type="button"
+ onPointerDown={event => event.preventDefault()}
+ onPointerUp={event => event.preventDefault()}
+ onPointerCancel={event => event.preventDefault()}>
+ Clear
+ </button>
+ </Drawer>,
+ );
+ const child = screen.getByRole('button', {name: 'Clear'});
+ fireEvent.pointerDown(child);
+ fireEvent.pointerUp(child);
+ fireEvent.pointerCancel(child);
+ expect(onPointerDown).toHaveBeenCalledTimes(1);
+ expect(onPointerUp).toHaveBeenCalledTimes(1);
+ expect(onPointerCancel).toHaveBeenCalledTimes(1);
+ });
+
it('does not close when drawer content is clicked', () => {
const handleOpenChange = vi.fn();
render(
@@ -888,6 +922,8 @@ describe('Drawer', () => {
);
const dialog = screen.getByRole('dialog');
fireEvent.keyDown(dialog, {key: 'Escape'});
+ fireEvent.pointerDown(dialog);
+ fireEvent.pointerUp(dialog);
fireEvent.click(dialog);
expect(handleOpenChange).toHaveBeenCalledTimes(2);
expect(handleOpenChange).toHaveBeenNthCalledWith(1, false);
diff --git a/packages/core/src/Drawer/Drawer.tsx b/packages/core/src/Drawer/Drawer.tsx
index 5bbe6bb1d5..84d110cb70 100644
--- a/packages/core/src/Drawer/Drawer.tsx
+++ b/packages/core/src/Drawer/Drawer.tsx
@@ -78,9 +78,11 @@ import {layerTextReset} from '../Layer/layerTextReset.stylex';
import {layerStructureReset} from '../Layer/layerStructureReset.stylex';
import {LayerContentBoundary} from '../Layer/layerScopedContext';
import {useModalOutlet} from '../Layer/modalOutlet';
+import {useBackdropPress} from '../Layer/useBackdropPress';
import {layerClickBoundary} from '../Layer/layerClickBoundary';
import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
import {composeEventHandlers, mergeProps, themeProps} from '../utils';
+import {chainEventHandlers} from '../utils/chainEventHandlers';
import {container, overlayPaddingReset} from '../Layout';
import {
containerPaddingBlockEndVarStyles,
@@ -92,6 +94,8 @@ import {
import type {SpacingStep, SpacingToken} from '../Layout';
import {useDrawerDialogPresence} from './useDrawerDialogPresence';
+type PointerHandler = (event: React.PointerEvent<HTMLDialogElement>) => void;
+
// =============================================================================
// Styles
// =============================================================================
@@ -543,15 +547,14 @@ export function Drawer({
[allowEscape, handleDismiss, shouldDismissOnCloseRequest],
);
- // Clicks on the ::backdrop target the <dialog> element itself; clicks on
- // drawer content always target a child (the content area fills the panel).
- const handleClick = useCallback(
- (event: React.MouseEvent<HTMLDialogElement>) => {
- if (event.target === event.currentTarget && hasScrim && allowScrimClick) {
- onOpenChange(false);
- }
- },
- [allowScrimClick, hasScrim, onOpenChange],
+ // A press on the ::backdrop targets the <dialog> itself (the content area
+ // fills the panel). The press must start and end there.
+ const handleScrimPress = useCallback(() => {
+ onOpenChange(false);
+ }, [onOpenChange]);
+ const scrimPress = useBackdropPress(
+ handleScrimPress,
+ hasScrim && allowScrimClick,
);
const widthValue = typeof width === 'number' ? `${width}px` : width;
@@ -612,8 +615,22 @@ export function Drawer({
// written.
{...layerClickBoundary({
...safeProps,
- onClick: composeEventHandlers(onClickProp, handleClick),
+ onClick: composeEventHandlers(onClickProp, scrimPress.onClick),
})}
+ // The hook records where the press started first. The caller's capture
+ // handler then runs, also when a child prevented default.
+ onPointerDownCapture={chainEventHandlers(
+ scrimPress.onPointerDownCapture,
+ safeProps.onPointerDownCapture as PointerHandler | undefined,
+ )}
+ onPointerUpCapture={chainEventHandlers(
+ scrimPress.onPointerUpCapture,
+ safeProps.onPointerUpCapture as PointerHandler | undefined,
+ )}
+ onPointerCancelCapture={chainEventHandlers(
+ scrimPress.onPointerCancelCapture,
+ safeProps.onPointerCancelCapture as PointerHandler | undefined,
+ )}
onKeyDown={onKeyDownProp}
onCancel={handleCancel}>
<ModalAnnounceProvider dialogRef={dialogRef} isOpen={isOpen && hasScrim}>
diff --git a/packages/core/src/Layer/__tests__/BackdropPress.a11y.chromium.spec.ts b/packages/core/src/Layer/__tests__/BackdropPress.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..a53dc69602
--- /dev/null
+++ b/packages/core/src/Layer/__tests__/BackdropPress.a11y.chromium.spec.ts
@@ -0,0 +1,114 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @pr-a11y scope core/Layer core/Dialog core/Drawer core/CommandPalette ^apps/storybook/stories/BackdropPressA11y
+
+/**
+ * @file BackdropPress.a11y.chromium.spec.ts
+ * @input The built A11y/BackdropPress story; real Chromium mouse and touch
+ * input
+ * @output Browser evidence that a press which crosses the edge of a Dialog,
+ * Drawer or CommandPalette, either way, leaves it open, and that a
+ * press on the backdrop alone still dismisses it
+ * @position Chromium proof for the shared backdrop-press rule
+ * (Layer/useBackdropPress.ts). jsdom has no backdrop hit testing and no
+ * click retargeting to the common ancestor.
+ */
+
+import {expect, test, type Page} from '@playwright/test';
+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';
+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();
+});
+
+test.use({viewport: {width: 1024, height: 768}, hasTouch: true});
+
+const MEMBERS = [
+ {name: 'Dialog', open: 'Open dialog', dialog: 'Note dialog', field: 'Note'},
+ {name: 'Drawer', open: 'Open drawer', dialog: 'Note drawer', field: 'Note'},
+ {
+ name: 'CommandPalette',
+ open: 'Open palette',
+ dialog: 'Commands',
+ field: null,
+ },
+] as const;
+
+// A backdrop point clear of every member: Dialog and CommandPalette sit in the
+// middle, the Drawer at the end edge.
+const BACKDROP = {x: 12, y: 12};
+
+async function openMember(page: Page, open: string, dialog: string) {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=a11y-backdroppress--members&viewMode=story`,
+ );
+ await holdMotionStill(page);
+ await page.getByRole('button', {name: open, exact: true}).click();
+ const surface = page.getByRole('dialog', {name: dialog});
+ await expect(surface).toBeVisible();
+ return surface;
+}
+
+async function insidePoint(page: Page, dialog: string, field: string | null) {
+ const surface = page.getByRole('dialog', {name: dialog});
+ const target =
+ field == null
+ ? surface.getByRole('combobox').first()
+ : surface.getByRole('textbox', {name: field});
+ const box = await target.boundingBox();
+ if (box == null) {
+ throw new Error(`${dialog} has no field box`);
+ }
+ return {x: box.x + 8, y: box.y + box.height / 2};
+}
+
+for (const {name, open, dialog, field} of MEMBERS) {
+ test.describe(name, () => {
+ test('a mouse press that starts inside and ends on the backdrop leaves it open', async ({
+ page,
+ }) => {
+ const surface = await openMember(page, open, dialog);
+ const inside = await insidePoint(page, dialog, field);
+ // The click this produces goes to the common ancestor, the <dialog>.
+ await page.mouse.move(inside.x, inside.y);
+ await page.mouse.down();
+ await page.mouse.move(BACKDROP.x, BACKDROP.y, {steps: 8});
+ await page.mouse.up();
+ await expect(surface).toBeVisible();
+ });
+
+ test('a mouse press that starts on the backdrop and ends inside leaves it open', async ({
+ page,
+ }) => {
+ const surface = await openMember(page, open, dialog);
+ const inside = await insidePoint(page, dialog, field);
+ await page.mouse.move(BACKDROP.x, BACKDROP.y);
+ await page.mouse.down();
+ await page.mouse.move(inside.x, inside.y, {steps: 8});
+ await page.mouse.up();
+ await expect(surface).toBeVisible();
+ });
+
+ test('a mouse press on the backdrop alone dismisses it', async ({page}) => {
+ const surface = await openMember(page, open, dialog);
+ await page.mouse.click(BACKDROP.x, BACKDROP.y);
+ await expect(surface).toBeHidden();
+ });
+
+ test('a finger tap on the backdrop dismisses it', async ({page}) => {
+ const surface = await openMember(page, open, dialog);
+ await page.touchscreen.tap(BACKDROP.x, BACKDROP.y);
+ await expect(surface).toBeHidden();
+ });
+ });
+}
diff --git a/packages/core/src/Layer/useBackdropPress.test.tsx b/packages/core/src/Layer/useBackdropPress.test.tsx
new file mode 100644
index 0000000000..3e4ffd6c5b
--- /dev/null
+++ b/packages/core/src/Layer/useBackdropPress.test.tsx
@@ -0,0 +1,187 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useBackdropPress.test.tsx
+ * @input Dialog, Drawer and CommandPalette with their backdrop dismissal on
+ * @output Tests that a backdrop press dismisses only when it starts and ends
+ * on the backdrop, for a mouse and for a finger, and that a cancelled
+ * pointer ends the press
+ * @position The shared backdrop-press rule (useBackdropPress) through every
+ * member that uses it
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {fireEvent, render, screen} from '@testing-library/react';
+import type {ReactElement} from 'react';
+import {Dialog} from '../Dialog/Dialog';
+import {Drawer} from '../Drawer/Drawer';
+import {CommandPalette} from '../CommandPalette/CommandPalette';
+import {createStaticSource} from '../Typeahead/createStaticSource';
+import {resetLayerStackForTests} from './layerStack';
+
+beforeEach(() => {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+ // Closing releases the scroll lock, which restores the scroll position.
+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ resetLayerStackForTests();
+});
+
+type Member = {
+ name: string;
+ render: (onOpenChange: (isOpen: boolean) => void) => ReactElement;
+};
+
+const MEMBERS: Member[] = [
+ {
+ name: 'Dialog (purpose="info")',
+ render: onOpenChange => (
+ <Dialog isOpen onOpenChange={onOpenChange} aria-label="Note">
+ <input aria-label="Field" defaultValue="A note to select" />
+ </Dialog>
+ ),
+ },
+ {
+ name: 'Drawer (scrim)',
+ render: onOpenChange => (
+ <Drawer isOpen onOpenChange={onOpenChange} label="Note">
+ <input aria-label="Field" defaultValue="A note to select" />
+ </Drawer>
+ ),
+ },
+ {
+ name: 'CommandPalette',
+ render: onOpenChange => (
+ <CommandPalette
+ isOpen
+ onOpenChange={onOpenChange}
+ aria-label="Note"
+ searchSource={createStaticSource([])}
+ />
+ ),
+ },
+];
+
+const backdropOf = () => screen.getAllByRole('dialog', {hidden: true})[0];
+const insideOf = (backdrop: HTMLElement) =>
+ backdrop.querySelector<HTMLElement>('input') ?? backdrop.firstElementChild!;
+
+describe.each(MEMBERS)(
+ 'a backdrop press on $name',
+ ({render: renderMember}) => {
+ for (const pointerType of ['mouse', 'touch'] as const) {
+ describe(`with a ${pointerType}`, () => {
+ function press(down: Element, up: Element) {
+ fireEvent.pointerDown(down, {pointerType});
+ fireEvent.pointerUp(up, {pointerType});
+ // The browser sends the click to the common ancestor.
+ fireEvent.click(down === up ? down : backdropOf());
+ }
+
+ it('dismisses when it starts and ends on the backdrop', () => {
+ const onOpenChange = vi.fn();
+ render(renderMember(onOpenChange));
+ const backdrop = backdropOf();
+ press(backdrop, backdrop);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('does not dismiss when it starts inside and ends on the backdrop', () => {
+ const onOpenChange = vi.fn();
+ render(renderMember(onOpenChange));
+ const backdrop = backdropOf();
+ // Selecting text in the field and releasing past the edge.
+ press(insideOf(backdrop), backdrop);
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+
+ it('does not dismiss when it starts on the backdrop and ends inside', () => {
+ const onOpenChange = vi.fn();
+ render(renderMember(onOpenChange));
+ const backdrop = backdropOf();
+ press(backdrop, insideOf(backdrop));
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+
+ it('does not dismiss after the pointer is cancelled', () => {
+ const onOpenChange = vi.fn();
+ render(renderMember(onOpenChange));
+ const backdrop = backdropOf();
+ fireEvent.pointerDown(backdrop, {pointerType});
+ fireEvent.pointerCancel(backdrop, {pointerType});
+ fireEvent.click(backdrop);
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+
+ it('does not carry one press over to the next', () => {
+ const onOpenChange = vi.fn();
+ render(renderMember(onOpenChange));
+ const backdrop = backdropOf();
+ fireEvent.pointerDown(backdrop, {pointerType});
+ press(insideOf(backdrop), backdrop);
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+ });
+ }
+ },
+);
+
+// A nested layer stops its presses at its own root in the React tree, as
+// layerClickBoundary does. The backdrop press still sees them.
+function NestedLayer() {
+ return (
+ <div
+ data-testid="nested-layer"
+ onPointerDown={event => event.stopPropagation()}
+ onPointerUp={event => event.stopPropagation()}
+ onClick={event => event.stopPropagation()}>
+ <input aria-label="Nested field" />
+ </div>
+ );
+}
+
+describe.each([
+ {
+ name: 'Dialog (purpose="info")',
+ render: (onOpenChange: (isOpen: boolean) => void) => (
+ <Dialog isOpen onOpenChange={onOpenChange} aria-label="Note">
+ <NestedLayer />
+ </Dialog>
+ ),
+ },
+ {
+ name: 'Drawer (scrim)',
+ render: (onOpenChange: (isOpen: boolean) => void) => (
+ <Drawer isOpen onOpenChange={onOpenChange} label="Note">
+ <NestedLayer />
+ </Drawer>
+ ),
+ },
+])('a press through a nested layer on $name', ({render: renderMember}) => {
+ it('a drag from the backdrop into the nested layer, then from it to the backdrop, does not dismiss', () => {
+ const onOpenChange = vi.fn();
+ render(renderMember(onOpenChange));
+ const backdrop = backdropOf();
+ const nested = screen.getByTestId('nested-layer');
+
+ fireEvent.pointerDown(backdrop);
+ fireEvent.pointerUp(nested);
+ fireEvent.click(backdrop.firstElementChild ?? backdrop);
+
+ fireEvent.pointerDown(nested);
+ fireEvent.pointerUp(backdrop);
+ fireEvent.click(backdrop);
+
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/src/Layer/useBackdropPress.ts b/packages/core/src/Layer/useBackdropPress.ts
new file mode 100644
index 0000000000..2eb55a5f53
--- /dev/null
+++ b/packages/core/src/Layer/useBackdropPress.ts
@@ -0,0 +1,81 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useBackdropPress.ts
+ * @input A modal layer's backdrop dismissal and whether it is allowed now
+ * @output Capture-phase pointer handlers and a click handler for the layer's
+ * <dialog> root
+ * @position Shared backdrop-press rule for Dialog and Drawer
+ */
+
+import {useCallback, useRef, type PointerEvent, type MouseEvent} from 'react';
+
+export interface BackdropPressHandlers {
+ onPointerDownCapture: (event: PointerEvent<HTMLElement>) => void;
+ onPointerUpCapture: (event: PointerEvent<HTMLElement>) => void;
+ onPointerCancelCapture: (event: PointerEvent<HTMLElement>) => void;
+ onClick: (event: MouseEvent<HTMLElement>) => void;
+}
+
+/**
+ * A press on a modal layer's backdrop targets the <dialog> root itself. A
+ * click there is also what the browser sends when a press starts on one side
+ * of the layer's edge and ends on the other (it goes to the nearest common
+ * ancestor), so a backdrop press dismisses only when its pointer-down and its
+ * pointer-up both landed on the backdrop. A cancelled pointer ends the press.
+ *
+ * The pointer handlers run in the capture phase. A nested layer, such as a
+ * popover open in the dialog, stops its presses at its own root, so a
+ * bubble-phase handler here does not see them.
+ */
+export function useBackdropPress(
+ onBackdropPress: () => void,
+ isEnabled: boolean,
+): BackdropPressHandlers {
+ const startedOnBackdropRef = useRef(false);
+ const endedOnBackdropRef = useRef(false);
+
+ const onPointerDownCapture = useCallback(
+ (event: PointerEvent<HTMLElement>) => {
+ startedOnBackdropRef.current = event.target === event.currentTarget;
+ endedOnBackdropRef.current = false;
+ },
+ [],
+ );
+
+ const onPointerUpCapture = useCallback((event: PointerEvent<HTMLElement>) => {
+ endedOnBackdropRef.current =
+ startedOnBackdropRef.current && event.target === event.currentTarget;
+ startedOnBackdropRef.current = false;
+ }, []);
+
+ const onPointerCancelCapture = useCallback(() => {
+ startedOnBackdropRef.current = false;
+ endedOnBackdropRef.current = false;
+ }, []);
+
+ const onClick = useCallback(
+ (event: MouseEvent<HTMLElement>) => {
+ const pressWasOnBackdrop = endedOnBackdropRef.current;
+ startedOnBackdropRef.current = false;
+ endedOnBackdropRef.current = false;
+ if (
+ isEnabled &&
+ pressWasOnBackdrop &&
+ event.target === event.currentTarget
+ ) {
+ onBackdropPress();
+ }
+ },
+ [isEnabled, onBackdropPress],
+ );
+
+ return {
+ onPointerDownCapture,
+ onPointerUpCapture,
+ onPointerCancelCapture,
+ onClick,
+ };
+}
diff --git a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx
index 0e15df6675..b5f9c564a0 100644
--- a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx
+++ b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx
@@ -822,6 +822,9 @@ describe('MobilePowerSearch Filters sheet', () => {
const confirmation = screen.getByRole('alertdialog', {
name: 'Clear all filters?',
});
+ // A scrim press starts and ends on the dialog itself.
+ fireEvent.pointerDown(confirmation);
+ fireEvent.pointerUp(confirmation);
fireEvent.click(confirmation);
expect(
screen.queryByRole('alertdialog', {name: 'Clear all filters?'}),
diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx b/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx
index 638c9f8a68..f0e23d8c48 100644
--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx
+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx
@@ -185,6 +185,9 @@ describe('MobileTokenizer (Lab, single-sheet flow)', () => {
let discard = await screen.findByRole('alertdialog', {
name: 'Discard changes?',
});
+ // A scrim press starts and ends on the dialog itself.
+ fireEvent.pointerDown(discard);
+ fireEvent.pointerUp(discard);
fireEvent.click(discard);
await waitFor(() =>
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument(),