Skip to content

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

TypeScript

fix(Dialog, Drawer): a backdrop press that closes a popover inside closes only the popover (#9988)

Cindy Zhanga866c2ab071a
diff --git a/.changeset/backdrop-press-topmost-layer.md b/.changeset/backdrop-press-topmost-layer.md
new file mode 100644
index 0000000000..757eef47bd
--- /dev/null
+++ b/.changeset/backdrop-press-topmost-layer.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A backdrop press that closes a menu or popover open inside a `Dialog` (`purpose="info"`), a `Drawer` with its scrim, or `CommandPalette` now closes only that menu or popover. The next backdrop press closes the dialog, as a second Escape does. Fixes #9920.
+
+@cixzhang
diff --git a/apps/storybook/stories/BackdropPressA11y.stories.tsx b/apps/storybook/stories/BackdropPressA11y.stories.tsx
index 43fe6331db..571786dd91 100644
--- a/apps/storybook/stories/BackdropPressA11y.stories.tsx
+++ b/apps/storybook/stories/BackdropPressA11y.stories.tsx
@@ -3,18 +3,27 @@
/**
* @file BackdropPressA11y.stories.tsx
* @input Dialog, Drawer and CommandPalette, each with a text field, opened
- * from a button
+ * from a button; Dialog and Drawer also hold a DropdownMenu; a second
+ * Dialog holds a Typeahead, a DateInput, an InfoTip and a ContextMenu
* @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
+ * when it starts and ends on the backdrop, and that a press which closes a
+ * menu open inside leaves the host open; excluded from the visual matrix
* @position Browser fixtures for the shared backdrop-press rule
*/
import {useState} from 'react';
+import type {ISODateString} from '@astryxdesign/core/Calendar';
+import {ContextMenu} from '@astryxdesign/core/ContextMenu';
+import {DateInput} from '@astryxdesign/core/DateInput';
+import {InfoTip} from '@astryxdesign/core/InfoTip';
+import {Typeahead} from '@astryxdesign/core/Typeahead';
+import type {SearchableItem} from '@astryxdesign/core/Typeahead';
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 {DropdownMenu} from '@astryxdesign/core/DropdownMenu';
import {createStaticSource} from '@astryxdesign/core/Typeahead';
const meta: Meta = {
@@ -26,6 +35,11 @@ export default meta;
const NOTE = 'A long note to select with the pointer and release past the edge';
+const menuItems = [
+ {label: 'Rename', onClick: () => {}},
+ {label: 'Archive', onClick: () => {}},
+];
+
const commands = createStaticSource([
{id: 'open', label: 'Open file'},
{id: 'save', label: 'Save file'},
@@ -55,6 +69,7 @@ export const Members: StoryObj = {
defaultValue={NOTE}
style={{width: '100%'}}
/>
+ <DropdownMenu button={{label: 'Actions'}} items={menuItems} />
</Dialog>
<Drawer
isOpen={open === 'drawer'}
@@ -65,6 +80,7 @@ export const Members: StoryObj = {
defaultValue={NOTE}
style={{width: '100%'}}
/>
+ <DropdownMenu button={{label: 'Actions'}} items={menuItems} />
</Drawer>
<CommandPalette
isOpen={open === 'palette'}
@@ -76,3 +92,44 @@ export const Members: StoryObj = {
);
},
};
+
+const fruits = createStaticSource<SearchableItem>([
+ {id: 'apple', label: 'Apple'},
+ {id: 'apricot', label: 'Apricot'},
+ {id: 'banana', label: 'Banana'},
+]);
+
+/** A Dialog that holds each layer that closes on a press or a focus move. */
+export const LayersInDialog: StoryObj = {
+ render: function LayersInDialogStory() {
+ const [isOpen, setIsOpen] = useState(false);
+ const [fruit, setFruit] = useState<SearchableItem | null>(null);
+ const [date, setDate] = useState<ISODateString | undefined>(undefined);
+ return (
+ <>
+ <Button label="Open layers dialog" onClick={() => setIsOpen(true)} />
+ <Dialog
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ aria-label="Layers dialog">
+ <Typeahead
+ label="Fruit"
+ searchSource={fruits}
+ value={fruit}
+ onChange={setFruit}
+ />
+ <DateInput
+ label="Date"
+ value={date}
+ onChange={setDate}
+ presentation="popover"
+ />
+ <InfoTip content="Help text" label="About layers" />
+ <ContextMenu items={menuItems}>
+ <div style={{padding: 16}}>Right-click here</div>
+ </ContextMenu>
+ </Dialog>
+ </>
+ );
+ },
+};
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index 8eb9f41c6f..984cdfaa4b 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -331,8 +331,8 @@ stack reports itself absent to the shared stack while that lasts
registry, and only the order among sheets is the sheet stack's to state. 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:
+Outside interaction is not coordinated by the shared stack. Current paths
+close their own layers independently:
- auto popovers use native light dismiss;
- BaseTypeahead's list, DateInput's calendar, DateTimeInput's time list and
@@ -348,6 +348,15 @@ independent:
- dropdown submenus encode their root-close relationship locally through
`DropdownMenuContext`.
+One fact joins these paths, for a modal host's backdrop press
+(`family:overlay-dismissal` FR11). The outside-press watch, the touch-only
+outside listener, the text fields' blur closes, ContextMenu's `mousedown` close,
+and a held Tooltip's focus-out release each record their close in a
+per-document count. A Dialog or Drawer backdrop press that sees the count
+change, or an auto popover close, between its pointer-down and its click leaves
+the host open. The count orders nothing else: each path still closes only its
+own layer.
+
The shared stack exposes `isTopmostLayer()`, but current outside, backdrop, touch,
and swipe paths do not use it. There is no shared interaction-owner role,
association graph, branch registry, or outside-branch resolution operation on
@@ -474,9 +483,13 @@ layers use Layer rendering without joining Escape/platform dismissal.
- **INV8 — Current Escape delivery follows registered layers.** The shared stack
uses present `close` and `block` entries in its current depth, containment, and
stable-registration order.
-- **INV9 — Outside channels remain component-owned and uncoordinated.** Current
- backdrop, pointer, touch, hover/focus, and swipe handlers act through their
- owning component or browser mechanism rather than one shared branch operation.
+- **INV9 — Outside channels remain component-owned.** Current backdrop,
+ pointer, touch, hover/focus, and swipe handlers act through their owning
+ component or browser mechanism rather than one shared branch operation. Their
+ one shared fact is the per-document count of outside closes in
+ `Layer/outsidePress.ts`: a modal backdrop press reads it, so a press that
+ closed a layer above the host does not also close the host
+ (`family:overlay-dismissal` FR11).
- **INV10 — LayerProvider is configuration, not a universal layer host.** It
carries Toast configuration and the app-declared viewport inset. Trigger-
associated layers resolve near their JSX position independently of the
@@ -670,7 +683,8 @@ is staged as `[breaking]` (`spec:AST-017` FR32) and `component:SelectableCard`
touch-only outside listener for Tooltip/HoverCard.
- `Layer/outsidePress.ts` owns the outside-press watch for a text field's
manual layer, used by BaseTypeahead, DateInput, DateTimeInput and
- ChatComposerInput's trigger menu.
+ ChatComposerInput's trigger menu, and the per-document count of outside
+ closes that a modal backdrop press reads (`family:overlay-dismissal` FR11).
- `DropdownMenuContext` and `DropdownMenuSubMenu` own the current local
menu-cascade parent-close chain.
- Dialog families own native modal/backdrop presentation and their local channel
@@ -711,7 +725,7 @@ this current architecture record.
| INV12 | The `Core/Layer` viewport-inset stories' first-frame comparison, and `useLayer.test.tsx`'s synchronous anchor read | A layer whose first painted rectangle differs from its settled one |
| INV6, INV7 | `useLayer.test.tsx`, `Popover.test.tsx`, `DropdownMenu.test.tsx`, and `useMenuHover.test.tsx` | Duplicate close callback or the same press/re-hover reopens a surface |
| INV8 | `useLayerDismissal.test.tsx`, `layerDismissalInvariants.test.tsx`, and `useFocusTrap.test.tsx` | Current top registered layer is skipped, two layers close, or a blocker leaks through |
-| INV9 | Representative Dialog, ContextMenu, Tooltip/HoverCard, and BottomSheet source/tests | A current local channel silently changes ownership or policy |
+| INV9 | Representative Dialog, ContextMenu, Tooltip/HoverCard, and BottomSheet source/tests; `useBackdropPress.test.tsx`; `outsidePress.test.ts` | A current local channel silently changes ownership or policy |
| INV10 | `LayerProvider.tsx`, `LayerProvider.test.tsx`, `useToast.tsx`, `ToastViewport.test.tsx`, and `ToastViewport.modalHost.test.tsx` | Provider begins relocating ordinary layers, Toast fallback loses its current lifecycle, or a default provider renders differently from no provider |
| INV14, INV15 | Source boundary check over Core for top-layer hosts, exit copies, backdrop elements, lift, and rectangle-morph code outside the runtime and the lift module | A component building its own copy of a mechanism INV14 lists (top-layer mounting, close-request delivery, hold, exit copy, or backdrop element), or re-implementing the lift or the grow |
| INV17 | One runtime suite over every kind of layer root: a `useLayer` layer, inline and portaled, and the Dialog, Drawer, Lightbox, MobileNav, BottomSheetPanel, and ToastViewport content roots, each inside a plain `onClick` wrapper and a Core clickable container; nested layers | A click inside a layer root that reaches an ancestor bubble-phase handler, a caller's wrapper included; an outer layer's handler that receives an inner layer's press; or a document listener or light dismiss that no longer receives it |
diff --git a/docs/families/overlay-dismissal.md b/docs/families/overlay-dismissal.md
index 6af60abcf5..bf3c1efa64 100644
--- a/docs/families/overlay-dismissal.md
+++ b/docs/families/overlay-dismissal.md
@@ -229,6 +229,17 @@ this record's current membership snapshot must be updated with it.
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.
+- **FR11 — The topmost surface consumes its outside press.** An outside press
+ that light-dismisses the topmost surface is consumed by it; a host surface
+ under it does not also light-dismiss on that press. A backdrop press that
+ closes a layer open inside a Dialog with `purpose="info"`, a Drawer with its
+ scrim, or CommandPalette (a menu, a popover, a combobox list, a date
+ calendar, a pinned tooltip, or a context menu) leaves the host open, and the
+ next backdrop press dismisses the host. A layer that hides on its own, such
+ as a tooltip whose trigger lost focus, does not consume the press. A press
+ that closes only the layer leaves focus inside the host: where the closed
+ layer returns it, or else on the host itself. The rule is the same for a
+ mouse, a pen, and a finger.
## Allowed component variation
@@ -241,7 +252,7 @@ this record's current membership snapshot must be updated with it.
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; the
- backdrop press of the members FR10 names follows FR10.
+ backdrop press of the members FR10 names follows FR10 and FR11.
- **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
@@ -302,6 +313,7 @@ modality, positioning, outside-dismissal, and open-state contracts.
| 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 |
+| FR11 | `useBackdropPress.test.tsx`; `BackdropPress.a11y.chromium.spec.ts` | Dialog (`purpose="info"`) and Drawer scrim with a menu open inside, with a mouse and a finger: a backdrop press, then a second one; a Dialog with a Typeahead list, a DateInput calendar, a pinned InfoTip, or a ContextMenu open inside, with a mouse; a DateTimeInput time list whose field blurs at mousedown; a press while a tooltip hides on its own; a press that closes no layer above | A press that closes the menu also closes the host, or the second press leaves the host open |
## Decision links
diff --git a/docs/specs/components/Drawer/Drawer.spec.md b/docs/specs/components/Drawer/Drawer.spec.md
index f5d47c6fba..6c98f898a3 100644
--- a/docs/specs/components/Drawer/Drawer.spec.md
+++ b/docs/specs/components/Drawer/Drawer.spec.md
@@ -160,28 +160,28 @@ Consumer prop syntax and examples remain in `Drawer.doc.mjs`.
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
-| FR1 | Drawer MUST remain a viewport-relative, full-block-size overlay on the logical inline-start or inline-end edge and MUST NOT reserve layout space or reflow the page beneath it. | Current source, docs, stories, and tests |
-| FR2 | The logical edge selected for an open Drawer MUST remain latched through its exit even when caller state changes the live edge prop during close. | Current exit-side test and implementation |
-| 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, page scroll locking, and a visible backdrop; under the lock, pull-to-refresh and the page's bounce stop, because a scroll lock under a modal holds the page (`spec:AST-094` FR19), as behind a UIKit modal presentation; `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 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 |
-| FR10 | Sibling Drawers MUST be composed as siblings. The last-opened present sibling owns the first Escape request through the shared stack; a closing sibling retains that ownership through its visible exit, and reopening registers a new active cycle so one request never closes two surfaces. Paint order in both presentations follows the browser top layer's chronological order. | Current docs, shared stack, and tests |
-| FR11 | `DrawerProps` extends `BaseProps<HTMLDialogElement>` and separately declares `ref`. The root filters `open`, merges `xstyle`, `className`, and `style`, forwards remaining unclaimed props, composes consumer `onClick`, forwards consumer `onKeyDown` ahead of the shared document-level Escape owner, and owns `aria-label`, `aria-modal`, and, for a modal `required` drawer, `role="alertdialog"`. Implementation gap: a consumer `onCancel` is dropped (Current-state impact). A consumer `onKeyDown` that prevents default cancels shared-stack Escape dismissal for the press. | Current source and focused keyboard tests |
-| FR12 | The painted root dialog emits the documented `drawer` target and `side` selector axis and applies the container-padding reset. `DrawerHeader`'s targets are owned by `component:DrawerHeader` FR5. No separate Drawer target is currently emitted for content or scrim; future target qualification remains owned by `architecture:component-theming-surface`. | Current source, docs, and structural target metadata |
-| FR13 | Drawer MUST join the shared dismissal stack for its full rendered lifetime, provide logical depth to descendant layers, route platform close through the same topmost/IME decision, and preserve consumer `preventDefault()` ownership. | Shared family contract and focused tests |
-| FR14 | Non-modal Drawer MUST use a manual Popover API host so cross-surface order comes from the browser top layer rather than a page-level z-index band. The reduced fallback may use `dialog.show()` only below the Popover API support floor. | Current source, browser guard, and `spec:AST-027` |
-| FR15 | `purpose` takes the same values and default as Dialog's prop. `info` (default) lets Escape, platform close, and a modal scrim click request close; `form` lets Escape and platform close request close and ignores scrim clicks; `required` lets none request close, registers with the shared stack as `block` so the request does not reach a lower layer, and exposes a modal drawer as `role="alertdialog"`. Without a scrim, `form` and `info` behave the same. | DEC-1; purpose suite; `family:overlay-dismissal` Escape behavior |
-| FR16 | The Content area pads caller content by the drawer's container inset, `--spacing-4` by default as in Dialog, and publishes the applied inset to descendants as a container publisher would; `architecture:container-padding` does not yet admit Drawer as one (Current-state impact). Its block-end edge applies the container inset plus the home-indicator safe area while publishing the inset alone, so a bleed child subtracts only the inset and the safe area survives below it. The root dialog keeps the container-padding reset (FR12). | `architecture:container-padding`; container padding suite |
-| FR17 | A Drawer open on the server renders closed until hydration (no open styles, no `aria-modal`, the markup of a closed Drawer) and opens in the render after hydration, the first that can enter its native host; it never claims a modality it does not have (`spec:AST-020` FR1, WCAG 2.2 SC 4.1.2). The server and hydrating renders produce the same markup (`spec:AST-013` FR9), and the open after hydration is settled, with no entry motion; later opens and closes animate as usual (`spec:AST-013` FR13). | `spec:AST-020` FR1 |
-| FR18 | While a modal Drawer (`hasScrim`) is open it supplies its `<dialog>` as the passive global outlet, so app-global surfaces such as toasts render inside it, paint above it, and stay operable and reachable by keyboard; it stops supplying when it starts to close, so they return to their place and are not carried out with the exit. Moving them keeps toast entries, timers, and focus handoff (`spec:AST-003` FR18, FR19). A non-modal Drawer supplies no outlet (`architecture:layer-runtime`). | `spec:AST-003` FR18 |
-| FR19 | When a non-modal Drawer (`hasScrim={false}`) enters the top layer through `showPopover()`, a top-layer toast viewport shown before it leaves and re-enters the top layer in place, keeping focus inside it, so toasts paint above the drawer; the drawer supplies no outlet, and its close moves and re-enters nothing (`architecture:layer-runtime`). | `architecture:layer-runtime` |
-| FR20 | Drawer's scrim is the theme's `--color-overlay` dim with no blur, on every pointer; under forced colors the drawer keeps a visible edge. | Owner decision, 2026-10-25: the overlay stays theme-controlled and unblurred on every pointer. |
+| ID | Invariant | Basis |
+| ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
+| FR1 | Drawer MUST remain a viewport-relative, full-block-size overlay on the logical inline-start or inline-end edge and MUST NOT reserve layout space or reflow the page beneath it. | Current source, docs, stories, and tests |
+| FR2 | The logical edge selected for an open Drawer MUST remain latched through its exit even when caller state changes the live edge prop during close. | Current exit-side test and implementation |
+| 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 the press closes no layer open above the drawer (FR6), 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, page scroll locking, and a visible backdrop; under the lock, pull-to-refresh and the page's bounce stop, because a scroll lock under a modal holds the page (`spec:AST-094` FR19), as behind a UIKit modal presentation; `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 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`, unless the press light-dismisses a layer open above the drawer, which consumes it (`family:overlay-dismissal` FR11), 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 |
+| FR10 | Sibling Drawers MUST be composed as siblings. The last-opened present sibling owns the first Escape request through the shared stack; a closing sibling retains that ownership through its visible exit, and reopening registers a new active cycle so one request never closes two surfaces. Paint order in both presentations follows the browser top layer's chronological order. | Current docs, shared stack, and tests |
+| FR11 | `DrawerProps` extends `BaseProps<HTMLDialogElement>` and separately declares `ref`. The root filters `open`, merges `xstyle`, `className`, and `style`, forwards remaining unclaimed props, composes consumer `onClick`, forwards consumer `onKeyDown` ahead of the shared document-level Escape owner, and owns `aria-label`, `aria-modal`, and, for a modal `required` drawer, `role="alertdialog"`. Implementation gap: a consumer `onCancel` is dropped (Current-state impact). A consumer `onKeyDown` that prevents default cancels shared-stack Escape dismissal for the press. | Current source and focused keyboard tests |
+| FR12 | The painted root dialog emits the documented `drawer` target and `side` selector axis and applies the container-padding reset. `DrawerHeader`'s targets are owned by `component:DrawerHeader` FR5. No separate Drawer target is currently emitted for content or scrim; future target qualification remains owned by `architecture:component-theming-surface`. | Current source, docs, and structural target metadata |
+| FR13 | Drawer MUST join the shared dismissal stack for its full rendered lifetime, provide logical depth to descendant layers, route platform close through the same topmost/IME decision, and preserve consumer `preventDefault()` ownership. | Shared family contract and focused tests |
+| FR14 | Non-modal Drawer MUST use a manual Popover API host so cross-surface order comes from the browser top layer rather than a page-level z-index band. The reduced fallback may use `dialog.show()` only below the Popover API support floor. | Current source, browser guard, and `spec:AST-027` |
+| FR15 | `purpose` takes the same values and default as Dialog's prop. `info` (default) lets Escape, platform close, and a modal scrim click request close; `form` lets Escape and platform close request close and ignores scrim clicks; `required` lets none request close, registers with the shared stack as `block` so the request does not reach a lower layer, and exposes a modal drawer as `role="alertdialog"`. Without a scrim, `form` and `info` behave the same. | DEC-1; purpose suite; `family:overlay-dismissal` Escape behavior |
+| FR16 | The Content area pads caller content by the drawer's container inset, `--spacing-4` by default as in Dialog, and publishes the applied inset to descendants as a container publisher would; `architecture:container-padding` does not yet admit Drawer as one (Current-state impact). Its block-end edge applies the container inset plus the home-indicator safe area while publishing the inset alone, so a bleed child subtracts only the inset and the safe area survives below it. The root dialog keeps the container-padding reset (FR12). | `architecture:container-padding`; container padding suite |
+| FR17 | A Drawer open on the server renders closed until hydration (no open styles, no `aria-modal`, the markup of a closed Drawer) and opens in the render after hydration, the first that can enter its native host; it never claims a modality it does not have (`spec:AST-020` FR1, WCAG 2.2 SC 4.1.2). The server and hydrating renders produce the same markup (`spec:AST-013` FR9), and the open after hydration is settled, with no entry motion; later opens and closes animate as usual (`spec:AST-013` FR13). | `spec:AST-020` FR1 |
+| FR18 | While a modal Drawer (`hasScrim`) is open it supplies its `<dialog>` as the passive global outlet, so app-global surfaces such as toasts render inside it, paint above it, and stay operable and reachable by keyboard; it stops supplying when it starts to close, so they return to their place and are not carried out with the exit. Moving them keeps toast entries, timers, and focus handoff (`spec:AST-003` FR18, FR19). A non-modal Drawer supplies no outlet (`architecture:layer-runtime`). | `spec:AST-003` FR18 |
+| FR19 | When a non-modal Drawer (`hasScrim={false}`) enters the top layer through `showPopover()`, a top-layer toast viewport shown before it leaves and re-enters the top layer in place, keeping focus inside it, so toasts paint above the drawer; the drawer supplies no outlet, and its close moves and re-enters nothing (`architecture:layer-runtime`). | `architecture:layer-runtime` |
+| FR20 | Drawer's scrim is the theme's `--color-overlay` dim with no blur, on every pointer; under forced colors the drawer keeps a visible edge. | Owner decision, 2026-10-25: the overlay stays theme-controlled and unblurred on every pointer. |
### Allowed variation
diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx
index ffc0999b77..5ad820b114 100644
--- a/packages/core/src/ContextMenu/ContextMenu.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.tsx
@@ -59,6 +59,7 @@ import {useLayerInternal} from '../Layer/useLayer';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {currentGesture} from '../Layer/gestureCounter';
+import {noteOutsideDismissal} from '../Layer/outsidePress';
import {MenuBottomSheetActionList} from '../DropdownMenu/MenuBottomSheetActionList';
import {menuBottomSheetStyles} from '../DropdownMenu/menuBottomSheet.stylex';
import {renderDropdownItems} from '../DropdownMenu/renderDropdownItems';
@@ -531,6 +532,7 @@ export function ContextMenu({
return;
}
if (menu && !menu.contains(e.target as Node)) {
+ noteOutsideDismissal(menu.ownerDocument);
closeMenu();
}
};
diff --git a/packages/core/src/DateInput/DateInput.tsx b/packages/core/src/DateInput/DateInput.tsx
index 2cb7b742dd..e4ece00680 100644
--- a/packages/core/src/DateInput/DateInput.tsx
+++ b/packages/core/src/DateInput/DateInput.tsx
@@ -65,6 +65,7 @@ import {usePopover} from '../Popover';
import {
isFocusInsideOwnedLayer,
isPressInsideOwnedLayer,
+ noteOutsideDismissal,
useOutsidePress,
} from '../Layer/outsidePress';
import {NativeDateField} from './NativeDateField';
@@ -818,6 +819,7 @@ function PointerDateField({
return;
}
isFocusMovingAwayRef.current = true;
+ noteOutsideDismissal(e.currentTarget.ownerDocument);
popover.hide();
},
[popover],
diff --git a/packages/core/src/DateTimeInput/DateTimeInput.tsx b/packages/core/src/DateTimeInput/DateTimeInput.tsx
index be694498ef..bb273d0c96 100644
--- a/packages/core/src/DateTimeInput/DateTimeInput.tsx
+++ b/packages/core/src/DateTimeInput/DateTimeInput.tsx
@@ -67,6 +67,7 @@ import {usePopover} from '../Popover';
import {
isFocusInsideOwnedLayer,
isPressInsideOwnedLayer,
+ noteOutsideDismissal,
useOutsidePress,
} from '../Layer/outsidePress';
import {useTooltip} from '../Tooltip';
@@ -1435,6 +1436,7 @@ function PointerDateTimeField({
timePopover.id,
)
) {
+ noteOutsideDismissal(e.currentTarget.ownerDocument);
timePopover.hide();
}
diff --git a/packages/core/src/Layer/__tests__/BackdropPress.a11y.chromium.spec.ts b/packages/core/src/Layer/__tests__/BackdropPress.a11y.chromium.spec.ts
index 7f00468a1a..562b664e26 100644
--- a/packages/core/src/Layer/__tests__/BackdropPress.a11y.chromium.spec.ts
+++ b/packages/core/src/Layer/__tests__/BackdropPress.a11y.chromium.spec.ts
@@ -1,19 +1,26 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-// @pr-a11y scope core/Layer core/Dialog core/Drawer core/CommandPalette ^apps/storybook/stories/BackdropPressA11y
+// @pr-a11y scope core/Layer core/Dialog core/Drawer core/CommandPalette core/DropdownMenu core/Typeahead core/DateInput core/InfoTip core/Tooltip core/ContextMenu ^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
+ * Drawer or CommandPalette, either way, leaves it open, that a press on the
+ * backdrop alone still dismisses it, and that a backdrop press which closes
+ * a layer open inside a Dialog or Drawer (a menu, a Typeahead list, a
+ * DateInput calendar, a pinned InfoTip, a ContextMenu) leaves the host open
* @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 '@astryxdesign/a11y-spec/playwright';
+import {
+ expect,
+ test,
+ type Locator,
+ type Page,
+} from '@astryxdesign/a11y-spec/playwright';
import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';
import {
DEFAULT_STORYBOOK_DIR,
@@ -48,6 +55,17 @@ const MEMBERS = [
// middle, the Drawer at the end edge.
const BACKDROP = {x: 12, y: 12};
+// FR11: a press that closes only the layer leaves focus inside the host.
+async function expectFocusInside(surface: Locator) {
+ expect(
+ await surface.evaluate(
+ element =>
+ element === document.activeElement ||
+ element.contains(document.activeElement),
+ ),
+ ).toBe(true);
+}
+
async function openMember(page: Page, open: string, dialog: string) {
await page.goto(
`${storybook.origin}/iframe.html?id=a11y-backdroppress--members&viewMode=story`,
@@ -112,3 +130,101 @@ for (const {name, open, dialog, field} of MEMBERS) {
});
});
}
+
+for (const {name, open, dialog} of MEMBERS.filter(
+ member => member.name !== 'CommandPalette',
+)) {
+ test.describe(`${name} with a menu open inside`, () => {
+ async function openMenu(page: Page) {
+ const surface = await openMember(page, open, dialog);
+ await surface.getByRole('button', {name: 'Actions'}).click();
+ const menu = page.getByRole('menu');
+ await expect(menu).toBeVisible();
+ return {surface, menu};
+ }
+
+ test('a mouse press on the backdrop closes only the menu, and the next closes the host', async ({
+ page,
+ }) => {
+ const {surface, menu} = await openMenu(page);
+ await page.mouse.click(BACKDROP.x, BACKDROP.y);
+ await expect(menu).toBeHidden();
+ await expect(surface).toBeVisible();
+ await expectFocusInside(surface);
+ await page.mouse.click(BACKDROP.x, BACKDROP.y);
+ await expect(surface).toBeHidden();
+ });
+
+ test('a finger tap on the backdrop closes only the menu, and the next closes the host', async ({
+ page,
+ }) => {
+ const {surface, menu} = await openMenu(page);
+ await page.touchscreen.tap(BACKDROP.x, BACKDROP.y);
+ await expect(menu).toBeHidden();
+ await expect(surface).toBeVisible();
+ await expectFocusInside(surface);
+ await page.touchscreen.tap(BACKDROP.x, BACKDROP.y);
+ await expect(surface).toBeHidden();
+ });
+ });
+}
+
+test.describe('Dialog with another layer open inside, with a mouse', () => {
+ async function openLayersDialog(page: Page) {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=a11y-backdroppress--layers-in-dialog&viewMode=story`,
+ );
+ await holdMotionStill(page);
+ await page.getByRole('button', {name: 'Open layers dialog'}).click();
+ const surface = page.getByRole('dialog', {name: 'Layers dialog'});
+ await expect(surface).toBeVisible();
+ return surface;
+ }
+
+ const LAYERS = [
+ {
+ name: 'a Typeahead list',
+ open: async (page: Page) => {
+ await page.getByRole('combobox', {name: 'Fruit'}).fill('ap');
+ return page.getByRole('listbox');
+ },
+ },
+ {
+ name: 'a DateInput calendar',
+ open: async (page: Page) => {
+ await page.getByRole('button', {name: 'Open calendar'}).click();
+ return page.getByRole('grid').first();
+ },
+ },
+ {
+ name: 'a pinned InfoTip',
+ open: async (page: Page) => {
+ await page.getByRole('button', {name: 'About layers'}).click();
+ return page.getByRole('tooltip');
+ },
+ },
+ {
+ name: 'a ContextMenu',
+ open: async (page: Page) => {
+ await page.getByText('Right-click here').click({button: 'right'});
+ return page.getByRole('menu');
+ },
+ },
+ ];
+
+ for (const {name, open} of LAYERS) {
+ test(`a backdrop click closes only ${name}, and the next closes the dialog`, async ({
+ page,
+ }) => {
+ const surface = await openLayersDialog(page);
+ const layer = await open(page);
+ await expect(layer).toBeVisible();
+ await page.mouse.click(BACKDROP.x, BACKDROP.y);
+ await expect(layer).toBeHidden();
+ await expect(surface).toBeVisible();
+ await expectFocusInside(surface);
+ await page.mouse.click(BACKDROP.x, BACKDROP.y);
+ await expect(surface).toBeHidden();
+ });
+ }
+});
diff --git a/packages/core/src/Layer/outsidePress.test.ts b/packages/core/src/Layer/outsidePress.test.ts
index 8a96eca862..bea4e64dec 100644
--- a/packages/core/src/Layer/outsidePress.test.ts
+++ b/packages/core/src/Layer/outsidePress.test.ts
@@ -9,7 +9,12 @@
*/
import {afterEach, describe, expect, it} from 'vitest';
-import {isFocusInsideOwnedLayer, isPressInsideOwnedLayer} from './outsidePress';
+import {
+ isFocusInsideOwnedLayer,
+ isPressInsideOwnedLayer,
+ outsideDismissalCount,
+ watchOutsidePress,
+} from './outsidePress';
describe('isFocusInsideOwnedLayer', () => {
function setup() {
@@ -96,3 +101,26 @@ describe('inside tests across realms', () => {
).toBe(false);
});
});
+
+describe('outsideDismissalCount', () => {
+ it('counts each layer an outside press closes, and not a press inside', () => {
+ const owner = document.createElement('div');
+ const outside = document.createElement('div');
+ document.body.append(owner, outside);
+ const stop = watchOutsidePress(
+ owner,
+ path => path.includes(owner),
+ () => {},
+ );
+ const before = outsideDismissalCount(document);
+ owner.dispatchEvent(new Event('pointerdown', {bubbles: true}));
+ owner.dispatchEvent(new Event('pointerup', {bubbles: true}));
+ expect(outsideDismissalCount(document)).toBe(before);
+ outside.dispatchEvent(new Event('pointerdown', {bubbles: true}));
+ outside.dispatchEvent(new Event('pointerup', {bubbles: true}));
+ expect(outsideDismissalCount(document)).toBe(before + 1);
+ stop();
+ owner.remove();
+ outside.remove();
+ });
+});
diff --git a/packages/core/src/Layer/outsidePress.ts b/packages/core/src/Layer/outsidePress.ts
index d910936de1..e3be73ae42 100644
--- a/packages/core/src/Layer/outsidePress.ts
+++ b/packages/core/src/Layer/outsidePress.ts
@@ -6,7 +6,9 @@
* @file outsidePress.ts
* @input Listens for pointerdown, pointerup and pointercancel on a document
* @output Exports watchOutsidePress and useOutsidePress, which owns one watch
- * for a component: start on show, stop on hide, stop on unmount; and the
+ * for a component: start on show, stop on hide, stop on unmount;
+ * noteOutsideDismissal and outsideDismissalCount, a per-document count of
+ * layers that an outside press or focus move closed; and the
* inside tests a text field's owner runs: isPressInsideOwnedLayer for a
* press, isFocusInsideOwnedLayer for a blur
* @position Internal to Layer; the outside-press dismissal for a manual
@@ -23,6 +25,20 @@
import {useCallback, useEffect, useMemo, useRef} from 'react';
+// A modal host's backdrop press reads this. A press that closed a layer above
+// the host is that layer's, so the host stays open.
+const outsideDismissals = new WeakMap<Document, number>();
+
+/** Records that a layer in `doc` is closing because a press or focus went outside it. */
+export function noteOutsideDismissal(doc: Document): void {
+ outsideDismissals.set(doc, (outsideDismissals.get(doc) ?? 0) + 1);
+}
+
+/** How many layers an outside press has closed in `doc` so far. */
+export function outsideDismissalCount(doc: Document): number {
+ return outsideDismissals.get(doc) ?? 0;
+}
+
/**
* Watch the owner's document for a press outside, until the returned function
* is called. The caller stops it when its layer hides and when it unmounts.
@@ -49,6 +65,7 @@ export function watchOutsidePress(
const wasOutside = startedOutside;
startedOutside = false;
if (wasOutside && !isInside(event.composedPath())) {
+ noteOutsideDismissal(doc);
onOutside();
}
};
diff --git a/packages/core/src/Layer/useBackdropPress.test.tsx b/packages/core/src/Layer/useBackdropPress.test.tsx
index 3e4ffd6c5b..6f60da8805 100644
--- a/packages/core/src/Layer/useBackdropPress.test.tsx
+++ b/packages/core/src/Layer/useBackdropPress.test.tsx
@@ -4,8 +4,9 @@
* @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
+ * on the backdrop, for a mouse and for a finger, that a cancelled pointer
+ * ends the press, and that a press which light-dismisses a popover open
+ * above the host closes only that popover
* @position The shared backdrop-press rule (useBackdropPress) through every
* member that uses it
*/
@@ -16,6 +17,8 @@ import type {ReactElement} from 'react';
import {Dialog} from '../Dialog/Dialog';
import {Drawer} from '../Drawer/Drawer';
import {CommandPalette} from '../CommandPalette/CommandPalette';
+import {DateTimeInput} from '../DateTimeInput/DateTimeInput';
+import type {ISODateTimeString} from '../DateTimeInput/DateTimeInput';
import {createStaticSource} from '../Typeahead/createStaticSource';
import {resetLayerStackForTests} from './layerStack';
@@ -185,3 +188,131 @@ describe.each([
expect(onOpenChange).not.toHaveBeenCalled();
});
});
+
+// jsdom has no Popover API. An element that carries `data-open` stands for a
+// popover the browser shows; a press closes it the way light dismiss does, at
+// pointer-up.
+function PopoverInside() {
+ return (
+ <>
+ <div data-testid="inner-popover" popover="auto" data-open="">
+ <button type="button">Rename</button>
+ </div>
+ <div data-testid="inner-tip" popover="manual" data-open="">
+ Help text
+ </div>
+ </>
+ );
+}
+
+describe.each([
+ {
+ name: 'Dialog (purpose="info")',
+ render: (onOpenChange: (isOpen: boolean) => void) => (
+ <Dialog isOpen onOpenChange={onOpenChange} aria-label="Note">
+ <PopoverInside />
+ </Dialog>
+ ),
+ },
+ {
+ name: 'Drawer (scrim)',
+ render: (onOpenChange: (isOpen: boolean) => void) => (
+ <Drawer isOpen onOpenChange={onOpenChange} label="Note">
+ <PopoverInside />
+ </Drawer>
+ ),
+ },
+])(
+ 'a backdrop press while a popover inside $name is open',
+ ({render: renderMember}) => {
+ beforeEach(() => {
+ const matches = Element.prototype.matches;
+ vi.spyOn(Element.prototype, 'matches').mockImplementation(function (
+ this: Element,
+ selector: string,
+ ) {
+ if (selector === ':popover-open') {
+ return this.isConnected && this.hasAttribute('data-open');
+ }
+ return matches.call(this, selector);
+ });
+ });
+
+ for (const pointerType of ['mouse', 'touch'] as const) {
+ it(`with a ${pointerType}, closes only the popover; the next press closes the host`, () => {
+ const onOpenChange = vi.fn();
+ render(renderMember(onOpenChange));
+ const backdrop = backdropOf();
+ const popover = screen.getByTestId('inner-popover');
+
+ fireEvent.pointerDown(backdrop, {pointerType});
+ // The browser light-dismisses the popover at pointer-up.
+ popover.removeAttribute('data-open');
+ fireEvent.pointerUp(backdrop, {pointerType});
+ fireEvent.click(backdrop);
+ expect(onOpenChange).not.toHaveBeenCalled();
+
+ fireEvent.pointerDown(backdrop, {pointerType});
+ fireEvent.pointerUp(backdrop, {pointerType});
+ fireEvent.click(backdrop);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+ }
+
+ it('closes the host when a tooltip hides during the press for another reason', () => {
+ const onOpenChange = vi.fn();
+ render(renderMember(onOpenChange));
+ const backdrop = backdropOf();
+ fireEvent.pointerDown(backdrop, {pointerType: 'mouse'});
+ // A tooltip whose trigger lost focus hides on its own delay.
+ screen.getByTestId('inner-tip').removeAttribute('data-open');
+ fireEvent.pointerUp(backdrop, {pointerType: 'mouse'});
+ fireEvent.click(backdrop);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('closes the host when the press dismisses no layer above it', () => {
+ const onOpenChange = vi.fn();
+ render(renderMember(onOpenChange));
+ const backdrop = backdropOf();
+ // The popover stays open: this press is not its dismissal.
+ fireEvent.pointerDown(backdrop, {pointerType: 'mouse'});
+ fireEvent.pointerUp(backdrop, {pointerType: 'mouse'});
+ fireEvent.click(backdrop);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+ },
+);
+
+describe('a backdrop press while a DateTimeInput time list inside a Dialog is open', () => {
+ it('with a mouse, closes only the list when the field blurs at mousedown; the next press closes the Dialog', () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Dialog isOpen onOpenChange={onOpenChange} aria-label="Note">
+ <DateTimeInput
+ label="Meeting"
+ value={'2026-03-15T14:00' as ISODateTimeString}
+ timeOptionInterval={60}
+ onChange={() => {}}
+ />
+ </Dialog>,
+ );
+ const backdrop = backdropOf();
+ const timeInput = screen.getByLabelText('Meeting time');
+ fireEvent.keyDown(timeInput, {key: 'ArrowDown', altKey: true});
+ expect(timeInput).toHaveAttribute('aria-expanded', 'true');
+
+ fireEvent.pointerDown(backdrop, {pointerType: 'mouse'});
+ // The mousedown moves focus from the field to the dialog.
+ fireEvent.blur(timeInput, {relatedTarget: backdrop});
+ fireEvent.pointerUp(backdrop, {pointerType: 'mouse'});
+ fireEvent.click(backdrop);
+ expect(timeInput).toHaveAttribute('aria-expanded', 'false');
+ expect(onOpenChange).not.toHaveBeenCalled();
+
+ fireEvent.pointerDown(backdrop, {pointerType: 'mouse'});
+ fireEvent.pointerUp(backdrop, {pointerType: 'mouse'});
+ fireEvent.click(backdrop);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+});
diff --git a/packages/core/src/Layer/useBackdropPress.ts b/packages/core/src/Layer/useBackdropPress.ts
index 2eb55a5f53..8334f5f624 100644
--- a/packages/core/src/Layer/useBackdropPress.ts
+++ b/packages/core/src/Layer/useBackdropPress.ts
@@ -11,6 +11,7 @@
*/
import {useCallback, useRef, type PointerEvent, type MouseEvent} from 'react';
+import {outsideDismissalCount} from './outsidePress';
export interface BackdropPressHandlers {
onPointerDownCapture: (event: PointerEvent<HTMLElement>) => void;
@@ -19,6 +20,21 @@ export interface BackdropPressHandlers {
onClick: (event: MouseEvent<HTMLElement>) => void;
}
+function isPopoverShowing(element: Element): boolean {
+ try {
+ return element.matches(':popover-open');
+ } catch {
+ // jsdom and pre-Popover browsers do not recognize :popover-open.
+ return false;
+ }
+}
+
+function showingAutoPopovers(host: HTMLElement): ReadonlyArray<Element> {
+ return Array.from(
+ host.ownerDocument.querySelectorAll('[popover="auto"], [popover=""]'),
+ ).filter(element => !element.contains(host) && isPopoverShowing(element));
+}
+
/**
* 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
@@ -26,6 +42,14 @@ export interface BackdropPressHandlers {
* 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.
*
+ * A press that light-dismisses a layer open above the host, such as a menu
+ * open in the dialog, is that layer's: the host stays open, and the next
+ * backdrop press dismisses it, as a second Escape does. The press is the
+ * layer's when it closes one. A `popover="auto"` layer that showed at
+ * pointer-down no longer shows at the click, or a layer counted its close
+ * with noteOutsideDismissal. A layer that hides for another reason, such as a
+ * Tooltip whose trigger lost focus, does not count.
+ *
* 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.
@@ -36,11 +60,20 @@ export function useBackdropPress(
): BackdropPressHandlers {
const startedOnBackdropRef = useRef(false);
const endedOnBackdropRef = useRef(false);
+ const autoPopoversRef = useRef<ReadonlyArray<Element>>([]);
+ const dismissalCountRef = useRef(0);
const onPointerDownCapture = useCallback(
(event: PointerEvent<HTMLElement>) => {
- startedOnBackdropRef.current = event.target === event.currentTarget;
+ const isOnBackdrop = event.target === event.currentTarget;
+ startedOnBackdropRef.current = isOnBackdrop;
endedOnBackdropRef.current = false;
+ autoPopoversRef.current = isOnBackdrop
+ ? showingAutoPopovers(event.currentTarget)
+ : [];
+ dismissalCountRef.current = outsideDismissalCount(
+ event.currentTarget.ownerDocument,
+ );
},
[],
);
@@ -54,16 +87,23 @@ export function useBackdropPress(
const onPointerCancelCapture = useCallback(() => {
startedOnBackdropRef.current = false;
endedOnBackdropRef.current = false;
+ autoPopoversRef.current = [];
}, []);
const onClick = useCallback(
(event: MouseEvent<HTMLElement>) => {
const pressWasOnBackdrop = endedOnBackdropRef.current;
+ const dismissedALayerAbove =
+ autoPopoversRef.current.some(layer => !isPopoverShowing(layer)) ||
+ outsideDismissalCount(event.currentTarget.ownerDocument) !==
+ dismissalCountRef.current;
startedOnBackdropRef.current = false;
endedOnBackdropRef.current = false;
+ autoPopoversRef.current = [];
if (
isEnabled &&
pressWasOnBackdrop &&
+ !dismissedALayerAbove &&
event.target === event.currentTarget
) {
onBackdropPress();
diff --git a/packages/core/src/Layer/useTouchTrigger.ts b/packages/core/src/Layer/useTouchTrigger.ts
index 14b6fb7089..3f290ceb0d 100644
--- a/packages/core/src/Layer/useTouchTrigger.ts
+++ b/packages/core/src/Layer/useTouchTrigger.ts
@@ -53,6 +53,7 @@ import {
type RefObject,
} from 'react';
import {currentGesture} from './gestureCounter';
+import {noteOutsideDismissal} from './outsidePress';
import {
innermostInteractive,
matchesInteractiveSelectors,
@@ -436,6 +437,9 @@ export function useTouchTriggerInternal(
}
}
disarmOutsideDismiss();
+ if (target != null) {
+ noteOutsideDismissal(target.ownerDocument ?? document);
+ }
hideRef.current();
};
diff --git a/packages/core/src/Tooltip/useTooltip.tsx b/packages/core/src/Tooltip/useTooltip.tsx
index a1733343ec..745b6d0514 100644
--- a/packages/core/src/Tooltip/useTooltip.tsx
+++ b/packages/core/src/Tooltip/useTooltip.tsx
@@ -37,6 +37,7 @@ import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';
import {useMergedRefs} from '../hooks/useMergedRefs';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
import {registerLayerSurface} from '../Layer/layerSurfacePress';
+import {noteOutsideDismissal} from '../Layer/outsidePress';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {themeProps} from '../utils/themeProps';
import {
@@ -451,6 +452,7 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
) {
return;
}
+ noteOutsideDismissal(view.document);
releaseHold();
},
[isHeldOpen, layerId, releaseHold],
diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsx
index 150fa25511..25f60e2ea2 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.tsx
+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx
@@ -44,6 +44,7 @@ import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {
isFocusInsideOwnedLayer,
isPressInsideOwnedLayer,
+ noteOutsideDismissal,
useOutsidePress,
} from '../Layer/outsidePress';
import {isImeKeyEvent} from '../utils/ime';
@@ -1473,6 +1474,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
if (isFocusInsideOwnedLayer(e.relatedTarget, anchorEl, popover.id)) {
return;
}
+ noteOutsideDismissal(e.currentTarget.ownerDocument);
popover.hide();
},
[popover, anchorRef],