Skip to content

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

TypeScript

feat(core): one shared dismissal stack for every overlay layer (#4881)

Cindy Zhang47d5160dc76c
diff --git a/.changeset/layer-dismissal-stack.md b/.changeset/layer-dismissal-stack.md
new file mode 100644
index 0000000000..e7495c39a1
--- /dev/null
+++ b/.changeset/layer-dismissal-stack.md
@@ -0,0 +1,8 @@
+---
+'@astryxdesign/core': minor
+---
+
+[breaking] Overlays share one dismissal stack, so a single Escape dismisses exactly one layer. Every overlay used to own its own Escape listener, which meant one press could close a popover _and_ the Dialog hosting it, or a modal _and_ the modal it was opened from. `useLayerDismissal` replaces that with a single stack: the stack owns one listener, routes each press to the top-most layer, and suppresses the browser's own close-watcher so nothing dismisses twice. A layer declares what it does with a press via `escapeBehavior` — `close` (default) or `block`, for a `required` Dialog that must swallow the press without closing so nothing behind it dismisses either. Fixes a Tooltip inside a Dialog closing the Dialog rather than the tip, and a HoverCard trigger swallowing Escape whenever it merely had focus. Dismissals the browser starts on its own — the Android back gesture, the platform close watcher — still close a Dialog, and follow the same top-most rule. An Escape that cancels an in-progress IME composition dismisses nothing: the stack claims that press so the browser raises no close request of its own, and a close request that arrives mid-composition anyway is declined, so a CJK user backing out of a half-formed character no longer loses the layer and everything typed into it. One behavior change worth knowing about if you listen for Escape yourself: the stack claims a press with `preventDefault()` but deliberately leaves propagation alone, so a `keydown` listener on `window` now sees an Escape that a focus-trapped layer used to stop — with `defaultPrevented` already `true`, which is how to tell the stack has acted on it. Top-most is resolved from React-tree nesting (which survives portals) rather than DOM containment alone. A layer's place in that order is keyed to the layer's identity rather than to each registration, so a prop change that re-registers it — a Dialog whose `purpose` flips while it is open — never promotes it above the layers opened over it. Controlled layers follow their control state: a controlled `Tooltip` or `HoverCard` stays on the stack and takes the press like any other layer, but answers it by calling `onOpenChange(false)` rather than hiding itself — whether it actually closes is the caller's update to make, exactly as it has always been for `Dialog`.
+
+@freddymeta
+@cixzhang
diff --git a/apps/storybook/stories/LayerDismissal.stories.tsx b/apps/storybook/stories/LayerDismissal.stories.tsx
new file mode 100644
index 0000000000..8c73c40414
--- /dev/null
+++ b/apps/storybook/stories/LayerDismissal.stories.tsx
@@ -0,0 +1,1019 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file LayerDismissal.stories.tsx
+ * @input Uses Dialog, Popover, Tooltip, Lightbox, MobileNav, BottomSheet,
+ * Button, Layout from @astryxdesign/core; InfoTip from @astryxdesign/lab
+ * @output Storybook stories demonstrating shared layer dismissal
+ * @position Storybook; the visual contract for the layer dismissal stack
+ *
+ * Every story here answers the same question — "what does ONE Escape press
+ * do?" — for a different mix of layers. They exist to be pressed, not just
+ * read: the behavior is invisible in a screenshot of a single state.
+ */
+
+import {useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {
+ Button,
+ Dialog,
+ DialogHeader,
+ HoverCard,
+ HStack,
+ Layout,
+ LayoutContent,
+ LayoutFooter,
+ Lightbox,
+ MobileNav,
+ Popover,
+ Text,
+ Tooltip,
+ VStack,
+} from '@astryxdesign/core';
+import {BottomSheet, BottomSheetSwitcher} from '@astryxdesign/core/BottomSheet';
+import {InfoTip} from '@astryxdesign/lab/InfoTip';
+import type {Meta, StoryObj} from '@storybook/react-vite';
+
+const sheetStyles = stylex.create({
+ body: {padding: 24},
+});
+
+const meta: Meta = {
+ title: 'Core/Layer Dismissal',
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'One Escape press dismisses exactly one layer — the top-most one. ' +
+ 'Every overlay family shares a single dismissal stack, so modals, ' +
+ 'popovers, menus and hover tips all peel off in the right order ' +
+ 'regardless of which primitive rendered them.',
+ },
+ },
+ },
+};
+export default meta;
+
+type Story = StoryObj;
+
+/**
+ * A modal opened from inside another modal. One Escape closes the inner one and
+ * leaves the outer open; a second Escape closes the outer.
+ *
+ * The inner Dialog is rendered INSIDE the outer's subtree, which is how this is
+ * written in real code and the case that used to close both at once.
+ */
+function ModalInModalExample() {
+ const [isOuterOpen, setIsOuterOpen] = useState(false);
+ const [isInnerOpen, setIsInnerOpen] = useState(false);
+
+ return (
+ <>
+ <Button
+ label="Open outer modal"
+ variant="secondary"
+ onClick={() => setIsOuterOpen(true)}
+ />
+ <Dialog
+ isOpen={isOuterOpen}
+ onOpenChange={setIsOuterOpen}
+ width={520}
+ aria-label="Outer modal">
+ <Layout
+ header={
+ <DialogHeader
+ title="Outer modal"
+ subtitle="Press Escape once — only the layer on top should close"
+ onOpenChange={setIsOuterOpen}
+ />
+ }
+ content={
+ <LayoutContent>
+ <VStack gap={3}>
+ <Text type="body">
+ Open the inner modal, then press Escape. The inner one closes
+ and this one stays.
+ </Text>
+ <Button
+ label="Open inner modal"
+ variant="primary"
+ onClick={() => setIsInnerOpen(true)}
+ />
+ </VStack>
+
+ <Dialog
+ isOpen={isInnerOpen}
+ onOpenChange={setIsInnerOpen}
+ width={380}
+ aria-label="Inner modal">
+ <Layout
+ header={
+ <DialogHeader
+ title="Inner modal"
+ onOpenChange={setIsInnerOpen}
+ />
+ }
+ content={
+ <LayoutContent>
+ <Text type="body">Escape closes this one only.</Text>
+ </LayoutContent>
+ }
+ />
+ </Dialog>
+ </LayoutContent>
+ }
+ />
+ </Dialog>
+ </>
+ );
+}
+
+export const ModalInModal: Story = {render: () => <ModalInModalExample />};
+
+/**
+ * A popover opened inside a modal. Escape closes the popover and leaves the
+ * modal — the two families share one stack, so a mixed nesting orders the same
+ * way a same-family nesting does.
+ */
+function PopoverInModalExample() {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+ <>
+ <Button
+ label="Open modal"
+ variant="secondary"
+ onClick={() => setIsOpen(true)}
+ />
+ <Dialog
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ width={520}
+ aria-label="Modal hosting a popover">
+ <Layout
+ header={
+ <DialogHeader
+ title="Modal with a popover"
+ onOpenChange={setIsOpen}
+ />
+ }
+ content={
+ <LayoutContent>
+ <VStack gap={3}>
+ <Text type="body">
+ Open the popover, then press Escape: the popover closes and
+ this modal stays open.
+ </Text>
+ <Popover
+ content={
+ <VStack gap={2}>
+ <Text type="body">Popover content</Text>
+ <Text type="supporting">Escape closes just this.</Text>
+ </VStack>
+ }>
+ <Button label="Open popover" variant="primary" />
+ </Popover>
+ </VStack>
+ </LayoutContent>
+ }
+ />
+ </Dialog>
+ </>
+ );
+}
+
+export const PopoverInModal: Story = {
+ render: () => <PopoverInModalExample />,
+};
+
+/**
+ * A hover tip inside a modal. The visible tip is the top-most layer, so Escape
+ * hides the tip and the modal stays open; a second Escape closes the modal.
+ *
+ * Escape affects exactly one layer here, same as everywhere else — hover layers
+ * get no special case. The alternative (hide the tip AND close the modal on one
+ * press) was considered and rejected: someone dismissing a stray tooltip over a
+ * half-filled form would lose the form. One extra keystroke is the cheaper way
+ * to be wrong.
+ *
+ * A tip that is NOT showing claims nothing: presence is read from the DOM at
+ * press time, so merely having a tooltip in the tree never eats an Escape.
+ */
+function HoverTipInModalExample() {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+ <>
+ <Button
+ label="Open modal"
+ variant="secondary"
+ onClick={() => setIsOpen(true)}
+ />
+ <Dialog
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ width={520}
+ aria-label="Modal hosting a hover tip">
+ <Layout
+ header={
+ <DialogHeader
+ title="Modal with a hover tip"
+ onOpenChange={setIsOpen}
+ />
+ }
+ content={
+ <LayoutContent>
+ <VStack gap={3}>
+ <Text type="body">
+ Hover the button below to show its tip, then press Escape: the
+ tip hides and this modal stays open. Press Escape again to
+ close the modal.
+ </Text>
+ <Tooltip content="A hover tip — Escape hides just this">
+ <Button label="Hover me" variant="primary" />
+ </Tooltip>
+ </VStack>
+ </LayoutContent>
+ }
+ />
+ </Dialog>
+ </>
+ );
+}
+
+export const HoverTipInModal: Story = {
+ render: () => <HoverTipInModalExample />,
+};
+
+/**
+ * A `required` modal is a `block` layer: Escape neither dismisses it nor falls
+ * through to anything behind it. Open it from inside another modal and press
+ * Escape — nothing happens at all, which is the point. The user must choose.
+ */
+function RequiredModalExample() {
+ const [isHostOpen, setIsHostOpen] = useState(false);
+ const [isRequiredOpen, setIsRequiredOpen] = useState(false);
+
+ return (
+ <>
+ <Button
+ label="Open host modal"
+ variant="secondary"
+ onClick={() => setIsHostOpen(true)}
+ />
+ <Dialog
+ isOpen={isHostOpen}
+ onOpenChange={setIsHostOpen}
+ width={520}
+ aria-label="Host modal">
+ <Layout
+ header={
+ <DialogHeader title="Host modal" onOpenChange={setIsHostOpen} />
+ }
+ content={
+ <LayoutContent>
+ <VStack gap={3}>
+ <Text type="body">
+ Open the required dialog, then press Escape. Neither dialog
+ closes: a required layer swallows the press so it cannot leak
+ to the layer underneath.
+ </Text>
+ <Button
+ label="Open required dialog"
+ variant="primary"
+ onClick={() => setIsRequiredOpen(true)}
+ />
+ </VStack>
+
+ <Dialog
+ isOpen={isRequiredOpen}
+ onOpenChange={setIsRequiredOpen}
+ purpose="required"
+ width={380}
+ aria-label="Required dialog">
+ <Layout
+ header={<DialogHeader title="Choose an option" />}
+ content={
+ <LayoutContent>
+ <Text type="body">
+ Escape does nothing here. Pick an action to continue.
+ </Text>
+ </LayoutContent>
+ }
+ footer={
+ <LayoutFooter>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Decline"
+ variant="secondary"
+ onClick={() => setIsRequiredOpen(false)}
+ />
+ <Button
+ label="Accept"
+ variant="primary"
+ onClick={() => setIsRequiredOpen(false)}
+ />
+ </HStack>
+ </LayoutFooter>
+ }
+ />
+ </Dialog>
+ </LayoutContent>
+ }
+ />
+ </Dialog>
+ </>
+ );
+}
+
+export const RequiredModalBlocksEscape: Story = {
+ render: () => <RequiredModalExample />,
+};
+
+/**
+ * A Lightbox opened from inside a `required` dialog. Escape closes the
+ * Lightbox and leaves the required dialog exactly where it was.
+ *
+ * Lightbox used to close on the native `cancel` event alone, so the required
+ * dialog — a `block` layer — swallowed the press and the Lightbox could only
+ * be closed with the mouse.
+ */
+function RequiredModalWithLightboxExample() {
+ const [isRequiredOpen, setIsRequiredOpen] = useState(false);
+ const [isLightboxOpen, setIsLightboxOpen] = useState(false);
+
+ return (
+ <>
+ <Button
+ label="Open required dialog"
+ variant="secondary"
+ onClick={() => setIsRequiredOpen(true)}
+ />
+ <Dialog
+ isOpen={isRequiredOpen}
+ onOpenChange={setIsRequiredOpen}
+ purpose="required"
+ width={420}
+ aria-label="Required dialog">
+ <Layout
+ header={<DialogHeader title="Confirm your evidence" />}
+ content={
+ <LayoutContent>
+ <VStack gap={3}>
+ <Text type="body">
+ Open the photo, then press Escape. The photo closes and this
+ dialog stays — it still requires an explicit choice.
+ </Text>
+ <Button
+ label="View photo"
+ variant="primary"
+ onClick={() => setIsLightboxOpen(true)}
+ />
+ </VStack>
+
+ <Lightbox
+ isOpen={isLightboxOpen}
+ onOpenChange={setIsLightboxOpen}
+ media={{
+ src: 'https://picsum.photos/id/1015/1200/800',
+ alt: 'A river through a canyon',
+ }}
+ />
+ </LayoutContent>
+ }
+ footer={
+ <LayoutFooter>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Decline"
+ variant="secondary"
+ onClick={() => setIsRequiredOpen(false)}
+ />
+ <Button
+ label="Accept"
+ variant="primary"
+ onClick={() => setIsRequiredOpen(false)}
+ />
+ </HStack>
+ </LayoutFooter>
+ }
+ />
+ </Dialog>
+ </>
+ );
+}
+
+export const RequiredModalWithLightbox: Story = {
+ render: () => <RequiredModalWithLightboxExample />,
+};
+
+/**
+ * A mobile nav drawer opened over a `required` dialog. Same shape as the
+ * Lightbox story: Escape closes the drawer, the required dialog stays.
+ */
+function RequiredModalWithMobileNavExample() {
+ const [isRequiredOpen, setIsRequiredOpen] = useState(false);
+ const [isNavOpen, setIsNavOpen] = useState(false);
+
+ return (
+ <>
+ <Button
+ label="Open required dialog"
+ variant="secondary"
+ onClick={() => setIsRequiredOpen(true)}
+ />
+ <Dialog
+ isOpen={isRequiredOpen}
+ onOpenChange={setIsRequiredOpen}
+ purpose="required"
+ width={420}
+ aria-label="Required dialog">
+ <Layout
+ header={<DialogHeader title="Confirm your choice" />}
+ content={
+ <LayoutContent>
+ <VStack gap={3}>
+ <Text type="body">
+ Open the navigation drawer, then press Escape. The drawer
+ closes and this dialog stays.
+ </Text>
+ <Button
+ label="Open navigation"
+ variant="primary"
+ onClick={() => setIsNavOpen(true)}
+ />
+ </VStack>
+
+ <MobileNav
+ isOpen={isNavOpen}
+ onOpenChange={setIsNavOpen}
+ header="Navigation">
+ <Text type="body">Escape closes this drawer only.</Text>
+ </MobileNav>
+ </LayoutContent>
+ }
+ footer={
+ <LayoutFooter>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Decline"
+ variant="secondary"
+ onClick={() => setIsRequiredOpen(false)}
+ />
+ <Button
+ label="Accept"
+ variant="primary"
+ onClick={() => setIsRequiredOpen(false)}
+ />
+ </HStack>
+ </LayoutFooter>
+ }
+ />
+ </Dialog>
+ </>
+ );
+}
+
+export const RequiredModalWithMobileNav: Story = {
+ render: () => <RequiredModalWithMobileNavExample />,
+};
+
+/** A Lightbox on its own. Escape closes it, as it always has. */
+function LightboxAloneExample() {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <Button
+ label="View photo"
+ variant="secondary"
+ onClick={() => setIsOpen(true)}
+ />
+ <Lightbox
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ media={{
+ src: 'https://picsum.photos/id/1015/1200/800',
+ alt: 'A river through a canyon',
+ }}
+ />
+ </>
+ );
+}
+
+export const LightboxAlone: Story = {render: () => <LightboxAloneExample />};
+
+/** A mobile nav drawer on its own. Escape closes it, as it always has. */
+function MobileNavAloneExample() {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <Button
+ label="Open navigation"
+ variant="secondary"
+ onClick={() => setIsOpen(true)}
+ />
+ <MobileNav isOpen={isOpen} onOpenChange={setIsOpen} header="Navigation">
+ <Text type="body">Escape closes this drawer.</Text>
+ </MobileNav>
+ </>
+ );
+}
+
+export const MobileNavAlone: Story = {render: () => <MobileNavAloneExample />};
+
+/**
+ * A hover tip inside a non-modal bottom sheet. `BottomSheet` handles Escape
+ * itself rather than through the shared stack, so one press closes the sheet
+ * and the tip goes with it. A tip being up does not stop the sheet closing.
+ */
+function SheetWithHoverTipExample() {
+ const [activeSheet, setActiveSheet] = useState<string | null>(null);
+
+ return (
+ <>
+ <Button
+ label="Open sheet"
+ variant="secondary"
+ onClick={() => setActiveSheet('details')}
+ />
+ <BottomSheetSwitcher
+ activeSheet={activeSheet}
+ onActiveSheetChange={setActiveSheet}
+ hasScrim={false}>
+ <BottomSheet sheetId="details" label="Details" height="hug">
+ <VStack gap={3} xstyle={sheetStyles.body}>
+ <Text type="body">
+ Hover the button to show the tip, then press Escape. BottomSheet
+ handles Escape itself, so one press closes the sheet and the tip
+ goes with it.
+ </Text>
+ <Tooltip content="A hover tip, showing">
+ <Button label="Hover me" variant="secondary" />
+ </Tooltip>
+ </VStack>
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ </>
+ );
+}
+
+export const SheetWithHoverTip: Story = {
+ render: () => <SheetWithHoverTipExample />,
+};
+
+/**
+ * Three layers deep, in two different families: a modal, a modal opened from
+ * inside it, and a popover opened from inside that. Three Escape presses peel
+ * them off one at a time, innermost first — the ordering has to hold past the
+ * two-layer case that is easy to get right by accident.
+ */
+function ThreeDeepExample() {
+ const [isOuterOpen, setIsOuterOpen] = useState(false);
+ const [isInnerOpen, setIsInnerOpen] = useState(false);
+
+ return (
+ <>
+ <Button
+ label="Open outer modal"
+ variant="secondary"
+ onClick={() => setIsOuterOpen(true)}
+ />
+ <Dialog
+ isOpen={isOuterOpen}
+ onOpenChange={setIsOuterOpen}
+ width={520}
+ aria-label="Outer modal">
+ <Layout
+ header={
+ <DialogHeader title="Outer modal" onOpenChange={setIsOuterOpen} />
+ }
+ content={
+ <LayoutContent>
+ <VStack gap={3}>
+ <Text type="body">
+ Open the inner modal, then the popover inside it. Three
+ Escapes, one layer each.
+ </Text>
+ <Button
+ label="Open inner modal"
+ variant="primary"
+ onClick={() => setIsInnerOpen(true)}
+ />
+ </VStack>
+
+ <Dialog
+ isOpen={isInnerOpen}
+ onOpenChange={setIsInnerOpen}
+ width={400}
+ aria-label="Inner modal">
+ <Layout
+ header={
+ <DialogHeader
+ title="Inner modal"
+ onOpenChange={setIsInnerOpen}
+ />
+ }
+ content={
+ <LayoutContent>
+ <Popover content={<Text type="body">Deepest layer</Text>}>
+ <Button label="Open popover" variant="primary" />
+ </Popover>
+ </LayoutContent>
+ }
+ />
+ </Dialog>
+ </LayoutContent>
+ }
+ />
+ </Dialog>
+ </>
+ );
+}
+
+export const ThreeDeep: Story = {render: () => <ThreeDeepExample />};
+
+/**
+ * A dialog whose `purpose` changes while it is open re-registers with the
+ * stack. Its place in the order must not move: a second modal opened over it
+ * still takes the next Escape, and a flip to `required` must not let the older
+ * dialog start swallowing presses meant for the newer one.
+ *
+ * Open the first modal, open the second from inside it, flip the first to
+ * required, then press Escape — the second closes, as it would have without
+ * the flip.
+ */
+function PurposeFlipsWhileOpenExample() {
+ const [isFirstOpen, setIsFirstOpen] = useState(false);
+ const [isSecondOpen, setIsSecondOpen] = useState(false);
+ const [isFirstRequired, setIsFirstRequired] = useState(false);
+
+ return (
+ <>
+ <Button
+ label="Open first modal"
+ variant="secondary"
+ onClick={() => setIsFirstOpen(true)}
+ />
+ <Dialog
+ isOpen={isFirstOpen}
+ onOpenChange={setIsFirstOpen}
+ purpose={isFirstRequired ? 'required' : undefined}
+ width={480}
+ aria-label="First modal">
+ <Layout
+ header={<DialogHeader title="First modal" />}
+ content={
+ <LayoutContent>
+ <VStack gap={3}>
+ <Text type="body">
+ Open the second modal, then flip this one to required from
+ inside it. This one re-registers, and must not overtake the
+ modal opened after it — Escape should still close the second.
+ </Text>
+ <Button
+ label="Open second modal"
+ variant="primary"
+ onClick={() => setIsSecondOpen(true)}
+ />
+ </VStack>
+
+ <Dialog
+ isOpen={isSecondOpen}
+ onOpenChange={setIsSecondOpen}
+ width={380}
+ aria-label="Second modal">
+ <Layout
+ header={
+ <DialogHeader
+ title="Second modal"
+ onOpenChange={setIsSecondOpen}
+ />
+ }
+ content={
+ <LayoutContent>
+ <VStack gap={3}>
+ <Text type="body">Escape closes this one.</Text>
+ <Button
+ label="Make first required"
+ variant="secondary"
+ onClick={() => setIsFirstRequired(true)}
+ />
+ </VStack>
+ </LayoutContent>
+ }
+ />
+ </Dialog>
+ </LayoutContent>
+ }
+ footer={
+ <LayoutFooter>
+ <HStack gap={2} hAlign="end">
+ <Button
+ label="Done"
+ variant="secondary"
+ onClick={() => setIsFirstOpen(false)}
+ />
+ </HStack>
+ </LayoutFooter>
+ }
+ />
+ </Dialog>
+ </>
+ );
+}
+
+export const PurposeFlipsWhileOpen: Story = {
+ render: () => <PurposeFlipsWhileOpenExample />,
+};
+
+/**
+ * A lab InfoTip inside a modal, its tip showing. One Escape hides the tip and
+ * leaves the modal open; a second closes the modal.
+ *
+ * The InfoTip used to `stopPropagation()` the press at its trigger, so the
+ * stack never saw it and the browser's own close watcher closed the modal
+ * underneath instead — one press, both gone (#5168). It now handles no keys of
+ * its own and lets its Tooltip's stack entry take the press.
+ */
+function InfoTipInModalExample() {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+ <>
+ <Button
+ label="Open modal"
+ variant="secondary"
+ onClick={() => setIsOpen(true)}
+ />
+ <Dialog
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ width={480}
+ aria-label="Modal with an info tip">
+ <Layout
+ header={
+ <DialogHeader
+ title="Modal with an info tip"
+ subtitle="Focus or hover the info button, then press Escape once"
+ onOpenChange={setIsOpen}
+ />
+ }
+ content={
+ <LayoutContent>
+ <HStack gap={1} vAlign="center">
+ <Text type="body">Rolling spend</Text>
+ <InfoTip content="30-day rolling average, excluding refunds." />
+ </HStack>
+ </LayoutContent>
+ }
+ />
+ </Dialog>
+ </>
+ );
+}
+
+export const InfoTipInModal: Story = {render: () => <InfoTipInModalExample />};
+
+/**
+ * A HoverCard with focusable content, inside a modal, with focus tabbed INTO
+ * the card. One Escape hides the card and returns focus to its trigger; the
+ * modal stays open.
+ *
+ * The card content used to claim the press itself with `stopPropagation()`,
+ * which kept it from the dialog's own listener but not from the browser's
+ * close watcher — so one press took the card and the modal with it. The card
+ * is on the stack, so `onDismiss` does the work and the stack claims the press.
+ */
+function HoverCardInModalExample() {
+ const [isOpen, setIsOpen] = useState(false);
+
+ return (
+ <>
+ <Button
+ label="Open modal"
+ variant="secondary"
+ onClick={() => setIsOpen(true)}
+ />
+ <Dialog
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ width={520}
+ aria-label="Modal with a hover card">
+ <Layout
+ header={
+ <DialogHeader
+ title="Modal with a hover card"
+ subtitle="Hover the trigger, Tab into the card, then press Escape once"
+ onOpenChange={setIsOpen}
+ />
+ }
+ content={
+ <LayoutContent>
+ <HoverCard
+ content={
+ <VStack gap={2}>
+ <Text type="body">Card body</Text>
+ <Button label="Card action" variant="secondary" />
+ </VStack>
+ }>
+ <Button label="Hover me" variant="secondary" />
+ </HoverCard>
+ </LayoutContent>
+ }
+ />
+ </Dialog>
+ </>
+ );
+}
+
+export const HoverCardInModal: Story = {
+ render: () => <HoverCardInModalExample />,
+};
+
+/**
+ * A hover card the consumer controls (`isOpen`), inside a modal. One Escape
+ * goes to the CARD — it is the top-most layer — and the card answers by
+ * calling `onOpenChange(false)` rather than hiding itself. This consumer's
+ * update closes it, so the card goes and the modal stays.
+ *
+ * Controlled follows control state: Escape attempts the close, the caller's
+ * update function decides. Same contract as a controlled Dialog.
+ */
+function PinnedHoverCardInModalExample() {
+ const [isOpen, setIsOpen] = useState(false);
+ const [isCardOpen, setIsCardOpen] = useState(true);
+ const [requests, setRequests] = useState(0);
+
+ return (
+ <>
+ <Button
+ label="Open modal"
+ variant="secondary"
+ onClick={() => {
+ setIsCardOpen(true);
+ setRequests(0);
+ setIsOpen(true);
+ }}
+ />
+ <Dialog
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ width={520}
+ aria-label="Modal with a pinned hover card">
+ <Layout
+ header={
+ <DialogHeader
+ title="Modal with a pinned hover card"
+ subtitle="The app holds the card open — Escape asks it to close, and this app agrees"
+ onOpenChange={setIsOpen}
+ />
+ }
+ content={
+ <LayoutContent>
+ <VStack gap={2}>
+ <HoverCard
+ isOpen={isCardOpen}
+ onOpenChange={open => {
+ setRequests(n => n + 1);
+ setIsCardOpen(open);
+ }}
+ content={
+ <VStack gap={2}>
+ <Text type="body">Pinned card</Text>
+ <Button label="Card action" variant="secondary" />
+ </VStack>
+ }>
+ <Button label="Card trigger" variant="secondary" />
+ </HoverCard>
+ <Text type="body">{`close requests: ${requests}`}</Text>
+ </VStack>
+ </LayoutContent>
+ }
+ />
+ </Dialog>
+ </>
+ );
+}
+
+export const PinnedHoverCardInModal: Story = {
+ render: () => <PinnedHoverCardInModalExample />,
+};
+
+/**
+ * The same pinned card, with a consumer who ignores their own change handler.
+ * Escape reaches the card, the card reports, nothing happens — and because the
+ * card claimed the press, the modal underneath does not close either.
+ *
+ * That is the consumer's choice, not the stack's doing: a layer that holds
+ * itself open and discards its close requests is keyboard-undismissable, and
+ * so is anything behind it. The story exists to make that visible.
+ */
+function StuckHoverCardInModalExample() {
+ const [isOpen, setIsOpen] = useState(false);
+ const [requests, setRequests] = useState(0);
+
+ return (
+ <>
+ <Button
+ label="Open modal"
+ variant="secondary"
+ onClick={() => {
+ setRequests(0);
+ setIsOpen(true);
+ }}
+ />
+ <Dialog
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ width={520}
+ aria-label="Modal with a stuck hover card">
+ <Layout
+ header={
+ <DialogHeader
+ title="Modal with a stuck hover card"
+ subtitle="The app pins the card and ignores onOpenChange — Escape closes nothing"
+ onOpenChange={setIsOpen}
+ />
+ }
+ content={
+ <LayoutContent>
+ <VStack gap={2}>
+ <HoverCard
+ isOpen
+ onOpenChange={() => setRequests(n => n + 1)}
+ content={<Text type="body">Stuck card</Text>}>
+ <Button label="Card trigger" variant="secondary" />
+ </HoverCard>
+ <Text type="body">{`close requests: ${requests}`}</Text>
+ </VStack>
+ </LayoutContent>
+ }
+ />
+ </Dialog>
+ </>
+ );
+}
+
+export const StuckHoverCardInModal: Story = {
+ render: () => <StuckHoverCardInModalExample />,
+};
+
+/**
+ * The Tooltip side of the same contract. The tip is pinned open by the app
+ * inside a modal; Escape reaches the tip, which calls `onOpenChange(false)`,
+ * and this app's update hides it. The modal stays open — one press, one layer.
+ */
+function PinnedTooltipInModalExample() {
+ const [isOpen, setIsOpen] = useState(false);
+ const [isTipOpen, setIsTipOpen] = useState(true);
+ const [requests, setRequests] = useState(0);
+
+ return (
+ <>
+ <Button
+ label="Open modal"
+ variant="secondary"
+ onClick={() => {
+ setIsTipOpen(true);
+ setRequests(0);
+ setIsOpen(true);
+ }}
+ />
+ <Dialog
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ width={520}
+ aria-label="Modal with a pinned tooltip">
+ <Layout
+ header={
+ <DialogHeader
+ title="Modal with a pinned tooltip"
+ subtitle="The app holds the tip open — Escape asks it to close, and this app agrees"
+ onOpenChange={setIsOpen}
+ />
+ }
+ content={
+ <LayoutContent>
+ <VStack gap={2}>
+ <Tooltip
+ isOpen={isTipOpen}
+ onOpenChange={open => {
+ setRequests(n => n + 1);
+ setIsTipOpen(open);
+ }}
+ content="Pinned tip">
+ <Button label="Tip trigger" variant="secondary" />
+ </Tooltip>
+ <Text type="body">{`close requests: ${requests}`}</Text>
+ </VStack>
+ </LayoutContent>
+ }
+ />
+ </Dialog>
+ </>
+ );
+}
+
+export const PinnedTooltipInModal: Story = {
+ render: () => <PinnedTooltipInModalExample />,
+};
diff --git a/packages/core/src/Dialog/Dialog.test.tsx b/packages/core/src/Dialog/Dialog.test.tsx
index faa4e183b4..7e3d1922d8 100644
--- a/packages/core/src/Dialog/Dialog.test.tsx
+++ b/packages/core/src/Dialog/Dialog.test.tsx
@@ -11,7 +11,7 @@
import {readFileSync} from 'node:fs';
import {describe, it, expect, vi, beforeEach} from 'vitest';
-import {render, screen} from '@testing-library/react';
+import {render, screen, fireEvent} from '@testing-library/react';
import {Dialog, resolveDialogPositionOffsets} from './Dialog';
import {DialogHeader} from './DialogHeader';
@@ -145,6 +145,195 @@ describe('Dialog', () => {
});
});
+ describe('IME composition', () => {
+ // A CJK user presses Escape to cancel a half-formed character several times
+ // a sentence. jsdom models neither composition nor the close watcher, so
+ // these pin the wiring; the behaviour itself is measured in Chromium
+ // against the Layer Dismissal stories.
+ function DialogWithField({onOpenChange}: {onOpenChange: () => void}) {
+ return (
+ <Dialog isOpen onOpenChange={onOpenChange} aria-label="Filters">
+ <input aria-label="Search" />
+ </Dialog>
+ );
+ }
+
+ it('claims the composing Escape instead of letting the browser act', () => {
+ const onOpenChange = vi.fn();
+ render(<DialogWithField onOpenChange={onOpenChange} />);
+
+ const event = new KeyboardEvent('keydown', {
+ key: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ });
+ Object.defineProperty(event, 'isComposing', {value: true});
+ screen.getByRole('textbox', {name: 'Search'}).dispatchEvent(event);
+
+ // Unclaimed, this press becomes a close request that arrives at
+ // handleCancel and closes the dialog on the same keystroke.
+ expect(event.defaultPrevented).toBe(true);
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+
+ it('ignores a close request that arrives mid-composition', () => {
+ // The back gesture and the platform close watcher carry no composition
+ // state, so the dialog asks the stack rather than the event.
+ const onOpenChange = vi.fn();
+ render(<DialogWithField onOpenChange={onOpenChange} />);
+ const field = screen.getByRole('textbox', {name: 'Search'});
+
+ fireEvent.compositionStart(field);
+ const duringComposition = new Event('cancel', {cancelable: true});
+ screen.getByRole('dialog').dispatchEvent(duringComposition);
+
+ expect(duringComposition.defaultPrevented).toBe(true);
+ expect(onOpenChange).not.toHaveBeenCalled();
+
+ fireEvent.compositionEnd(field);
+ screen
+ .getByRole('dialog')
+ .dispatchEvent(new Event('cancel', {cancelable: true}));
+
+ expect(onOpenChange).toHaveBeenCalledTimes(1);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+ });
+
+ describe('nested-modal dismissal', () => {
+ function NestedModals({
+ isInnerOpen,
+ onOuterChange,
+ onInnerChange,
+ }: {
+ isInnerOpen: boolean;
+ onOuterChange: (isOpen: boolean) => void;
+ onInnerChange: (isOpen: boolean) => void;
+ }) {
+ return (
+ <Dialog
+ isOpen={true}
+ onOpenChange={onOuterChange}
+ purpose="info"
+ aria-label="Outer">
+ Outer content
+ <Dialog
+ isOpen={isInnerOpen}
+ onOpenChange={onInnerChange}
+ purpose="info"
+ aria-label="Inner">
+ Inner content
+ </Dialog>
+ </Dialog>
+ );
+ }
+
+ const getDialog = (label: string) =>
+ screen
+ .getAllByRole('dialog', {hidden: true})
+ .find(d => d.getAttribute('aria-label') === label)!;
+
+ const pressEscape = (target: Element) => {
+ target.dispatchEvent(
+ new KeyboardEvent('keydown', {
+ key: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ };
+
+ it('closes only the inner modal, not the outer, on Escape', () => {
+ const onOuterChange = vi.fn();
+ const onInnerChange = vi.fn();
+
+ render(
+ <NestedModals
+ isInnerOpen={true}
+ onOuterChange={onOuterChange}
+ onInnerChange={onInnerChange}
+ />,
+ );
+
+ const outer = getDialog('Outer');
+ const inner = getDialog('Inner');
+ expect(outer.contains(inner)).toBe(true);
+
+ pressEscape(inner);
+
+ expect(onInnerChange).toHaveBeenCalledTimes(1);
+ expect(onInnerChange).toHaveBeenCalledWith(false);
+ expect(onOuterChange).not.toHaveBeenCalled();
+ });
+
+ it('closes the outer modal on the next Escape once the inner one is gone', () => {
+ const onOuterChange = vi.fn();
+ const onInnerChange = vi.fn();
+
+ const {rerender} = render(
+ <NestedModals
+ isInnerOpen={true}
+ onOuterChange={onOuterChange}
+ onInnerChange={onInnerChange}
+ />,
+ );
+ rerender(
+ <NestedModals
+ isInnerOpen={false}
+ onOuterChange={onOuterChange}
+ onInnerChange={onInnerChange}
+ />,
+ );
+
+ pressEscape(getDialog('Outer'));
+
+ expect(onOuterChange).toHaveBeenCalledTimes(1);
+ expect(onOuterChange).toHaveBeenCalledWith(false);
+ expect(onInnerChange).not.toHaveBeenCalled();
+ });
+
+ it('closes the top-most modal on a browser-initiated cancel', () => {
+ const onOuterChange = vi.fn();
+ const onInnerChange = vi.fn();
+
+ render(
+ <NestedModals
+ isInnerOpen={true}
+ onOuterChange={onOuterChange}
+ onInnerChange={onInnerChange}
+ />,
+ );
+
+ const cancelEvent = new Event('cancel', {cancelable: true});
+ getDialog('Inner').dispatchEvent(cancelEvent);
+
+ expect(cancelEvent.defaultPrevented).toBe(true);
+ expect(onInnerChange).toHaveBeenCalledTimes(1);
+ expect(onInnerChange).toHaveBeenCalledWith(false);
+ expect(onOuterChange).not.toHaveBeenCalled();
+ });
+
+ it('leaves a modal that is not top-most open on a browser-initiated cancel', () => {
+ const onOuterChange = vi.fn();
+ const onInnerChange = vi.fn();
+
+ render(
+ <NestedModals
+ isInnerOpen={true}
+ onOuterChange={onOuterChange}
+ onInnerChange={onInnerChange}
+ />,
+ );
+
+ const cancelEvent = new Event('cancel', {cancelable: true});
+ getDialog('Outer').dispatchEvent(cancelEvent);
+
+ expect(cancelEvent.defaultPrevented).toBe(true);
+ expect(onOuterChange).not.toHaveBeenCalled();
+ expect(onInnerChange).not.toHaveBeenCalled();
+ });
+ });
+
describe('variant: standard', () => {
it('renders with default variant', () => {
render(
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index fd74d89952..44e06b286a 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -33,8 +33,8 @@ import {
import type {BaseProps} from '../BaseProps';
import * as stylex from '@stylexjs/stylex';
import {useScrollLock} from '../hooks/useScrollLock';
-import {hasActiveFocusTrapEscape} from '../hooks/useFocusTrap';
-import {isImeKeyEvent} from '../utils/ime';
+import {LayerDepthProvider} from '../Layer/LayerDepthContext';
+import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {
colorVars,
radiusVars,
@@ -523,34 +523,24 @@ export function Dialog({
// Skip for inline rendering — no modal overlay to compensate for.
useScrollLock(isOpen && !isInline);
- // Handle Escape key — skip for inline rendering
- useEffect(() => {
- if (isInline) {
- return;
- }
- const dialog = dialogRef.current;
- if (!dialog || !isOpen) {
- return;
- }
-
- const handleKeyDown = (event: KeyboardEvent) => {
- if (event.key === 'Escape') {
- // Ignore IME composition-cancel, and defer to any popover/menu layered
- // on top of this dialog so a single Escape closes only the top-most
- // layer (the popover's own focus trap handles it and stops propagation).
- if (isImeKeyEvent(event) || hasActiveFocusTrapEscape()) {
- return;
- }
- event.preventDefault();
- if (allowEscape) {
- onOpenChange(false);
- }
- }
- };
-
- dialog.addEventListener('keydown', handleKeyDown);
- return () => dialog.removeEventListener('keydown', handleKeyDown);
- }, [isOpen, isInline, allowEscape, onOpenChange]);
+ // Join the shared layer dismissal stack. The stack owns the Escape listener
+ // and routes each press to the top-most layer, so this dialog does not listen
+ // itself — that is what stops a modal opened from inside another modal (or a
+ // popover opened inside this one) from closing two layers on one press.
+ //
+ // A `required` dialog registers as `block`: it must not be dismissed, and the
+ // press must not fall through and dismiss a layer behind it either.
+ //
+ // Inline mode opts out — it renders dialog content in normal flow, with
+ // nothing layered over anything.
+ const {shouldDismissOnCloseRequest} = useLayerDismissal({
+ isActive: isOpen,
+ isEnabled: !isInline,
+ escapeBehavior: allowEscape ? 'close' : 'block',
+ onDismiss: () => {
+ onOpenChange(false);
+ },
+ });
// Dev-time guardrail: an open modal should always have an accessible name.
// The header-title check reads the DOM, so this stays in an effect; the ref
@@ -586,12 +576,18 @@ export function Dialog({
}
};
- // Handle native cancel event (browser Escape handling)
+ // 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.
+ // Escape presses the stack owns never arrive here — it preventDefault()s
+ // those, which suppresses the close watcher.
+ //
+ // Always preventDefault so the browser cannot close a controlled <dialog>
+ // behind React's back, then answer the request with the stack's own rules:
+ // only the top-most layer dismisses, a `required` dialog swallows it, and
+ // nothing dismisses while an IME composition is in progress.
const handleCancel = (event: React.SyntheticEvent<HTMLDialogElement>) => {
event.preventDefault();
- // Defer to a popover/menu layered on top of this dialog; it will dismiss
- // itself on the same Escape press.
- if (hasActiveFocusTrapEscape()) {
+ if (!shouldDismissOnCloseRequest()) {
return;
}
if (allowEscape) {
@@ -669,7 +665,7 @@ export function Dialog({
(props as Record<string, unknown>)['data-testid'] as
string | undefined
}>
- {innerContent}
+ <LayerDepthProvider>{innerContent}</LayerDepthProvider>
</div>
);
}
@@ -717,7 +713,7 @@ export function Dialog({
// imperatively in `attachDialog`; a consumer-provided aria-labelledby
// flows through {...safeProps} above and wins.
{...(purpose === 'required' ? {role: 'alertdialog'} : undefined)}>
- {innerContent}
+ <LayerDepthProvider>{innerContent}</LayerDepthProvider>
</dialog>
);
}
diff --git a/packages/core/src/HoverCard/HoverCard.tsx b/packages/core/src/HoverCard/HoverCard.tsx
index ee534c44d3..f2cf8ae93b 100644
--- a/packages/core/src/HoverCard/HoverCard.tsx
+++ b/packages/core/src/HoverCard/HoverCard.tsx
@@ -144,6 +144,12 @@ export interface HoverCardProps extends Pick<
* - `true`: force-show the hover card (hover/focus hide is suppressed)
* - `false`: force-hide the hover card
* - `undefined`: uncontrolled — hover/focus triggers manage visibility
+ *
+ * A controlled hover card still takes Escape when it is the top-most layer,
+ * and answers by calling `onOpenChange(false)` without hiding itself —
+ * closing is your update's decision, exactly as for a controlled Dialog.
+ * Ignore the call and the card stays, and so does the press: nothing
+ * underneath dismisses.
*/
isOpen?: boolean;
diff --git a/packages/core/src/HoverCard/useHoverCard.tsx b/packages/core/src/HoverCard/useHoverCard.tsx
index 822eb17e55..17b1b33741 100644
--- a/packages/core/src/HoverCard/useHoverCard.tsx
+++ b/packages/core/src/HoverCard/useHoverCard.tsx
@@ -31,6 +31,7 @@ import {
type LayerTouchTrigger,
} from '../Layer/useTouchTrigger';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
+import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {
colorVars,
shadowVars,
@@ -135,6 +136,11 @@ export interface HoverCardOptions {
* - `true`: force-show the hover card (hover/focus hide is suppressed)
* - `false`: force-hide the hover card
* - `undefined`: uncontrolled — hover/focus triggers manage visibility
+ *
+ * A controlled hover card still takes Escape when it is the top-most layer,
+ * and answers by calling `onHide` without hiding itself — closing is your
+ * update's decision, exactly as for a controlled Dialog. Ignore the call and
+ * the card stays, and so does the press: nothing underneath dismisses.
*/
isOpen?: boolean;
@@ -409,19 +415,71 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
[layer.id, scheduleHide],
);
- const handleKeyDown = useCallback(
- (e: KeyboardEvent) => {
- if (e.key === 'Escape') {
- // Stop propagation so parent components don't react to the same Escape
- e.stopPropagation();
- // Hide immediately without refocusing (we're already on trigger)
- clearTimeouts();
- touch.clearTapOpen();
- layer.hide();
+ // Escape dismissal (WCAG 1.4.13) goes through the shared layer stack: a
+ // visible card is the top-most layer, so it takes the press and consumes it.
+ //
+ // This replaces a keydown listener on the TRIGGER that called
+ // stopPropagation() on any Escape while the trigger merely had focus — open
+ // card or not — so focusing a HoverCard trigger inside a Dialog silently ate
+ // the press that should have closed the Dialog. Presence is now answered from
+ // the DOM, so a closed card never claims a press.
+ // A controlled hover card stays on the stack and takes the press like any
+ // other layer, but answers it by reporting instead of hiding: `isOpen` is
+ // the consumer's value, so only their update may change it. Same contract as
+ // a controlled Dialog.
+ useLayerDismissal({
+ // Registered for the hook's lifetime rather than gated on `layer.isOpen`:
+ // that state can lag a frame behind the DOM, so a press arriving right after
+ // the layer appears would find nothing registered. Because this layer
+ // CONSUMES the press, a stale registration would be worse than a missed one
+ // — it would silently eat Escapes meant for the dialog underneath — so
+ // presence is answered from the DOM at press time instead of from state.
+ isActive: true,
+ isPresent: () => {
+ const el =
+ typeof document === 'undefined'
+ ? null
+ : document.getElementById(layer.id);
+ if (el == null) {
+ return false;
+ }
+ try {
+ return el.matches(':popover-open');
+ } catch {
+ // Browsers without the Popover API (and some test environments) cannot
+ // answer the selector; fall back to the hook's own state.
+ return layer.isOpen;
}
},
- [touch, clearTimeouts, layer],
- );
+ onDismiss: () => {
+ clearTimeouts();
+ touch.clearTapOpen();
+ // Controlled: report and stop. The close — and the focus restore that
+ // goes with it — happens in the controlled effect if and when the
+ // consumer flips `isOpen`.
+ if (isOpen !== undefined) {
+ onHide?.();
+ return;
+ }
+ // Only when the card itself held focus, which is the one case the
+ // content-level handler this replaced could run in. Refocusing
+ // unconditionally would drag the caret out of a field the user was
+ // typing in while a hover card happened to be up; arming the re-show
+ // guard unconditionally would swallow their next focus on the trigger,
+ // because a focus() on the already-focused trigger fires no focusin to
+ // clear it.
+ const card =
+ typeof document === 'undefined'
+ ? null
+ : document.getElementById(layer.id);
+ const hadFocus = card?.contains(document.activeElement) ?? false;
+ layer.hide();
+ if (hadFocus) {
+ isEscapeDismissingRef.current = true;
+ triggerRef.current?.focus();
+ }
+ },
+ });
// Interaction ref that handles event listeners only
const {handlePointerEnter} = touch;
@@ -436,7 +494,6 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
'focusout',
handleFocusOut as EventListener,
);
- triggerRef.current.removeEventListener('keydown', handleKeyDown);
triggerRef.current.removeEventListener(
'pointerenter',
handlePointerEnter,
@@ -465,9 +522,6 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
el.addEventListener('focusin', handleFocusIn);
el.addEventListener('focusout', handleFocusOut as EventListener);
}
-
- // Attach keydown for Escape handling
- el.addEventListener('keydown', handleKeyDown);
}
triggerRef.current = el;
@@ -478,7 +532,6 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
handleMouseLeave,
handleFocusIn,
handleFocusOut,
- handleKeyDown,
handlePointerEnter,
handlePointerDown,
],
@@ -518,7 +571,19 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
layer.show();
} else {
clearTimeouts();
+ // A consumer closing the card while it holds focus would strand focus on
+ // <body>. Arming the re-show guard is what keeps the refocus from
+ // reopening the card through `handleFocusIn`, which shows on any focusin.
+ const card =
+ typeof document === 'undefined'
+ ? null
+ : document.getElementById(layer.id);
+ const hadFocus = card?.contains(document.activeElement) ?? false;
layer.hide();
+ if (hadFocus) {
+ isEscapeDismissingRef.current = true;
+ triggerRef.current?.focus();
+ }
}
}, [isOpen, clearTimeouts, layer]);
@@ -576,20 +641,6 @@ export function useHoverCard(options: HoverCardOptions = {}): HoverCardReturn {
isHoveringContentRef.current = false;
scheduleHide();
}}
- onKeyDown={e => {
- if (e.key === 'Escape') {
- // Stop propagation so parent components don't react to the same Escape
- e.stopPropagation();
- // Set flag to prevent re-show when we refocus trigger
- isEscapeDismissingRef.current = true;
- // Hide immediately
- clearTimeouts();
- touch.clearTapOpen();
- layer.hide();
- // Refocus the trigger
- triggerRef.current?.focus();
- }
- }}
onBlur={e => {
// Check if focus is moving back to the trigger or staying within content
const relatedTarget = e.relatedTarget as HTMLElement | null;
diff --git a/packages/core/src/Layer/LayerDepthContext.tsx b/packages/core/src/Layer/LayerDepthContext.tsx
new file mode 100644
index 0000000000..f606d92fda
--- /dev/null
+++ b/packages/core/src/Layer/LayerDepthContext.tsx
@@ -0,0 +1,62 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file LayerDepthContext.tsx
+ * @input React context
+ * @output Exports LayerDepthContext, useLayerDepth, LayerDepthProvider
+ * @position Layer system; how the dismissal stack learns which layer is nested
+ * inside which.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Layer/index.ts
+ * - /packages/core/src/Layer/useLayerDismissal.ts
+ *
+ * Nesting is read from the React tree rather than the DOM. Two reasons:
+ *
+ * - **Portals.** A nested overlay routinely renders into `document.body` or the
+ * native top layer, so DOM containment reports it as a sibling of the layer
+ * it is logically inside. React context flows through `createPortal`, so the
+ * tree keeps the relationship the DOM loses.
+ * - **Same-commit mounts.** Depth is fixed during render. Effect order is not
+ * available then and is misleading anyway: React runs child effects before
+ * parent effects, so an inner layer registers first and looks "older" than
+ * the outer layer that contains it.
+ *
+ * There is nothing to mount at the app root: the context defaults to 0, and
+ * each layer provides depth for its OWN content, so nesting composes on its own.
+ */
+
+import {createContext, use, type ReactNode} from 'react';
+
+/**
+ * How many layers deep the current subtree is. 0 at the app root; each layer
+ * increments it for its own content.
+ */
+export const LayerDepthContext = createContext(0);
+LayerDepthContext.displayName = 'LayerDepthContext';
+
+/**
+ * Read the current nesting depth. A layer calls this to learn its OWN depth —
+ * the depth of the subtree it is rendered into, before it pushes its content
+ * one level deeper.
+ */
+export function useLayerDepth(): number {
+ return use(LayerDepthContext);
+}
+
+/**
+ * Wrap a layer's content so any layer opened from inside it registers as
+ * nested. Takes no depth prop on purpose: it reads the ambient depth and adds
+ * one, so nesting composes without anyone tracking absolute numbers.
+ *
+ * Renders no DOM element — it is a context boundary only, which is why it takes
+ * no `xstyle`/`ref` and exposes no props interface.
+ */
+export function LayerDepthProvider({children}: {children: ReactNode}) {
+ const depth = use(LayerDepthContext);
+ return <LayerDepthContext value={depth + 1}>{children}</LayerDepthContext>;
+}
+
+LayerDepthProvider.displayName = 'LayerDepthProvider';
diff --git a/packages/core/src/Layer/index.ts b/packages/core/src/Layer/index.ts
index 32d4f38183..e98734e309 100644
--- a/packages/core/src/Layer/index.ts
+++ b/packages/core/src/Layer/index.ts
@@ -29,6 +29,15 @@ export type {
FixedLayerReturn,
} from './useLayer';
+// Layer dismissal stack — one Escape owner for every overlay family
+export {useLayerDismissal} from './useLayerDismissal';
+export type {
+ LayerEscapeBehavior,
+ UseLayerDismissalOptions,
+ UseLayerDismissalReturn,
+} from './useLayerDismissal';
+export {LayerDepthProvider} from './LayerDepthContext';
+
// Shared touch behavior for the hover layers
export {useTouchTrigger, isActionTrigger} from './useTouchTrigger';
export type {
diff --git a/packages/core/src/Layer/layerDismissalFamilies.test.tsx b/packages/core/src/Layer/layerDismissalFamilies.test.tsx
new file mode 100644
index 0000000000..b4b6495163
--- /dev/null
+++ b/packages/core/src/Layer/layerDismissalFamilies.test.tsx
@@ -0,0 +1,359 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file layerDismissalFamilies.test.tsx
+ * @input Uses vitest, @testing-library/react, 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
+ *
+ * The stack routes an Escape press to the top-most REGISTERED layer and
+ * 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.
+ *
+ * SYNC: When a new overlay family joins the stack, add it here.
+ */
+
+import {
+ describe,
+ it,
+ expect,
+ vi,
+ beforeAll,
+ beforeEach,
+ afterAll,
+ afterEach,
+} from 'vitest';
+import {render, screen} from '@testing-library/react';
+
+import {Dialog} from '../Dialog/Dialog';
+import {HoverCard} from '../HoverCard/HoverCard';
+import {Lightbox} from '../Lightbox/Lightbox';
+import {MobileNav} from '../MobileNav/MobileNav';
+import {Tooltip} from '../Tooltip/Tooltip';
+import {resetLayerStackForTests} from './layerStack';
+
+const originalMatches = HTMLElement.prototype.matches;
+const popoverOpenState = new WeakMap<HTMLElement, boolean>();
+
+// jsdom implements no Popover API, and the hover layers answer `isPresent`
+// from `:popover-open`.
+beforeAll(() => {
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ popoverOpenState.set(this, true);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ popoverOpenState.set(this, false);
+ });
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = function (
+ selector: string,
+ ): boolean {
+ if (selector === ':popover-open') {
+ return popoverOpenState.get(this) ?? false;
+ }
+ return originalMatches.call(this, selector);
+ };
+});
+
+afterAll(() => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ (HTMLElement.prototype as any).matches = originalMatches;
+});
+
+// jsdom does not implement showModal/close.
+beforeEach(() => {
+ vi.mocked(HTMLElement.prototype.showPopover).mockClear();
+ vi.mocked(HTMLElement.prototype.hidePopover).mockClear();
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+});
+
+afterEach(() => {
+ resetLayerStackForTests();
+});
+
+function pressEscape(): KeyboardEvent {
+ const event = new KeyboardEvent('keydown', {
+ key: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ });
+ document.dispatchEvent(event);
+ return event;
+}
+
+function fireCancel(dialog: Element): Event {
+ const event = new Event('cancel', {bubbles: false, cancelable: true});
+ dialog.dispatchEvent(event);
+ return event;
+}
+
+const getDialog = (label: string) =>
+ screen
+ .getAllByRole('dialog', {hidden: true})
+ .find(d => d.getAttribute('aria-label') === label)!;
+
+const MEDIA = {src: '/photo.jpg', alt: 'A photo'};
+
+describe('overlay families on the shared dismissal stack', () => {
+ describe('Lightbox', () => {
+ it('takes the Escape when it is open over a required Dialog', () => {
+ const onLightboxChange = vi.fn();
+ const onDialogChange = vi.fn();
+
+ render(
+ <Dialog
+ isOpen={true}
+ onOpenChange={onDialogChange}
+ purpose="required"
+ aria-label="Required">
+ Choose one
+ <Lightbox
+ isOpen={true}
+ onOpenChange={onLightboxChange}
+ media={MEDIA}
+ />
+ </Dialog>,
+ );
+
+ const event = pressEscape();
+
+ expect(onLightboxChange).toHaveBeenCalledWith(false);
+ expect(onDialogChange).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('closes on a browser-initiated cancel when it is top-most', () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Lightbox isOpen={true} onOpenChange={onOpenChange} media={MEDIA} />,
+ );
+
+ const event = fireCancel(screen.getByRole('dialog', {hidden: true}));
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('stays open on a browser-initiated cancel when it is not top-most', () => {
+ const onLightboxChange = vi.fn();
+
+ render(
+ <>
+ <Lightbox
+ isOpen={true}
+ onOpenChange={onLightboxChange}
+ media={MEDIA}
+ />
+ <Dialog isOpen={true} onOpenChange={() => {}} aria-label="Above">
+ Above
+ </Dialog>
+ </>,
+ );
+
+ const event = fireCancel(getDialog('A photo'));
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(onLightboxChange).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('MobileNav', () => {
+ it('takes the Escape when it opens over a required Dialog', () => {
+ const onNavChange = vi.fn();
+ const onDialogChange = vi.fn();
+
+ render(
+ <>
+ <Dialog
+ isOpen={true}
+ onOpenChange={onDialogChange}
+ purpose="required"
+ aria-label="Required">
+ Choose one
+ </Dialog>
+ <MobileNav isOpen={true} onOpenChange={onNavChange} label="Drawer">
+ <span>Nav content</span>
+ </MobileNav>
+ </>,
+ );
+
+ const event = pressEscape();
+
+ expect(onNavChange).toHaveBeenCalledWith(false);
+ expect(onDialogChange).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('closes on a browser-initiated cancel when it is top-most', () => {
+ const onOpenChange = vi.fn();
+ render(
+ <MobileNav isOpen={true} onOpenChange={onOpenChange} label="Drawer">
+ <span>Nav content</span>
+ </MobileNav>,
+ );
+
+ const event = fireCancel(getDialog('Drawer'));
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('stays open on a browser-initiated cancel when it is not top-most', () => {
+ const onNavChange = vi.fn();
+
+ render(
+ <MobileNav isOpen={true} onOpenChange={onNavChange} label="Drawer">
+ <span>Nav content</span>
+ <Dialog isOpen={true} onOpenChange={() => {}} aria-label="Above">
+ Above
+ </Dialog>
+ </MobileNav>,
+ );
+
+ const event = fireCancel(getDialog('Drawer'));
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(onNavChange).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('required Dialog', () => {
+ it('still swallows an Escape when it is alone', () => {
+ const onDialogChange = vi.fn();
+
+ render(
+ <Dialog
+ isOpen={true}
+ onOpenChange={onDialogChange}
+ purpose="required"
+ aria-label="Required">
+ Choose one
+ </Dialog>,
+ );
+
+ const event = pressEscape();
+
+ expect(onDialogChange).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('still swallows an Escape with a Lightbox open UNDER it', () => {
+ const onLightboxChange = vi.fn();
+ const onDialogChange = vi.fn();
+
+ render(
+ <>
+ <Lightbox
+ isOpen={true}
+ onOpenChange={onLightboxChange}
+ media={MEDIA}
+ />
+ <Dialog
+ isOpen={true}
+ onOpenChange={onDialogChange}
+ purpose="required"
+ aria-label="Required">
+ Choose one
+ </Dialog>
+ </>,
+ );
+
+ pressEscape();
+
+ expect(onDialogChange).not.toHaveBeenCalled();
+ expect(onLightboxChange).not.toHaveBeenCalled();
+ });
+ });
+
+ // Controlled follows control state for `isOpen`: Escape still attempts the
+ // close, but only the caller's update function may perform it. Dialog has
+ // always worked this way; these two now do too.
+ describe('controlled hover layers', () => {
+ it('a controlled HoverCard takes the press and reports instead of hiding', () => {
+ const onCardChange = vi.fn();
+ const onDialogChange = vi.fn();
+
+ render(
+ <Dialog isOpen={true} onOpenChange={onDialogChange} aria-label="Host">
+ <HoverCard
+ isOpen={true}
+ onOpenChange={onCardChange}
+ content={<span>Pinned card</span>}>
+ <button type="button">Trigger</button>
+ </HoverCard>
+ </Dialog>,
+ );
+ onCardChange.mockClear();
+ vi.mocked(HTMLElement.prototype.hidePopover).mockClear();
+
+ const event = pressEscape();
+
+ expect(onCardChange).toHaveBeenCalledWith(false);
+ expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled();
+ expect(onDialogChange).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('a controlled Tooltip takes the press and reports instead of hiding', () => {
+ const onTipChange = vi.fn();
+ const onDialogChange = vi.fn();
+
+ render(
+ <Dialog isOpen={true} onOpenChange={onDialogChange} aria-label="Host">
+ <Tooltip
+ isOpen={true}
+ onOpenChange={onTipChange}
+ content="Pinned tip">
+ <button type="button">Trigger</button>
+ </Tooltip>
+ </Dialog>,
+ );
+ onTipChange.mockClear();
+ vi.mocked(HTMLElement.prototype.hidePopover).mockClear();
+
+ const event = pressEscape();
+
+ expect(onTipChange).toHaveBeenCalledWith(false);
+ expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled();
+ expect(onDialogChange).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('leaves the Dialog unclosable when the consumer discards the request', () => {
+ // The round-6 regression, now by consumer choice rather than by ours: a
+ // layer that holds itself open and ignores its own change handler keeps
+ // taking the press, and nothing behind it can be reached.
+ const onCardChange = vi.fn();
+ const onDialogChange = vi.fn();
+
+ render(
+ <Dialog isOpen={true} onOpenChange={onDialogChange} aria-label="Host">
+ <HoverCard
+ isOpen={true}
+ onOpenChange={onCardChange}
+ content={<span>Stuck card</span>}>
+ <button type="button">Trigger</button>
+ </HoverCard>
+ </Dialog>,
+ );
+ onCardChange.mockClear();
+
+ pressEscape();
+ pressEscape();
+
+ expect(onCardChange).toHaveBeenCalledTimes(2);
+ expect(onDialogChange).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/packages/core/src/Layer/layerDismissalInvariants.test.tsx b/packages/core/src/Layer/layerDismissalInvariants.test.tsx
new file mode 100644
index 0000000000..4f5bdaaea5
--- /dev/null
+++ b/packages/core/src/Layer/layerDismissalInvariants.test.tsx
@@ -0,0 +1,417 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file layerDismissalInvariants.test.tsx
+ * @input Uses vitest, @testing-library/react, 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
+ * question of real overlays — after one Escape, what is still on screen?
+ *
+ * Every assertion here reads the DOM (`which dialogs are open`) rather than a
+ * dismiss spy. A spy passes when the stack routes to the wrong layer as long as
+ * something was called; the open-dialog census cannot.
+ *
+ * jsdom models neither the close watcher nor IME composition, so the rows that
+ * depend on a real engine are driven through the same channels the browser
+ * would use — a `cancel` event, a keydown carrying `isComposing` — and the
+ * end-to-end behavior is measured in Chromium instead (probe-kit).
+ *
+ * SYNC: When a new overlay family joins the stack, add it here.
+ */
+
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
+import {render, screen, act} from '@testing-library/react';
+import {useState} from 'react';
+
+import {Dialog} from '../Dialog/Dialog';
+import {Lightbox} from '../Lightbox/Lightbox';
+import {resetLayerStackForTests} from './layerStack';
+import {useLayerDismissal} from './useLayerDismissal';
+
+// jsdom implements neither, and Dialog drives both.
+beforeEach(() => {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+});
+
+afterEach(() => {
+ resetLayerStackForTests();
+});
+
+/**
+ * Everything on screen right now, named the way a person would name it and
+ * sorted so the census is about WHICH layers are up, not what order two role
+ * queries happened to return them in.
+ */
+function onScreen(): string[] {
+ // `purpose="required"` renders role="alertdialog", so both roles have to be
+ // asked for or a required Dialog is invisible to the census.
+ return [
+ ...screen.queryAllByRole('dialog', {hidden: true}),
+ ...screen.queryAllByRole('alertdialog', {hidden: true}),
+ ]
+ .filter(d => (d as HTMLDialogElement).open)
+ .map(d => d.getAttribute('aria-label') ?? '(unnamed)')
+ .sort();
+}
+
+function pressEscape(options: KeyboardEventInit = {}): KeyboardEvent {
+ const event = new KeyboardEvent('keydown', {
+ key: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ ...options,
+ });
+ act(() => {
+ document.dispatchEvent(event);
+ });
+ return event;
+}
+
+function composingEscape(): KeyboardEvent {
+ const event = new KeyboardEvent('keydown', {
+ key: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ });
+ Object.defineProperty(event, 'isComposing', {value: true});
+ act(() => {
+ document.dispatchEvent(event);
+ });
+ return event;
+}
+
+function fireCancel(label: string): Event {
+ const event = new Event('cancel', {bubbles: false, cancelable: true});
+ const dialog = [
+ ...screen.queryAllByRole('dialog', {hidden: true}),
+ ...screen.queryAllByRole('alertdialog', {hidden: true}),
+ ].find(d => d.getAttribute('aria-label') === label)!;
+ act(() => {
+ dialog.dispatchEvent(event);
+ });
+ return event;
+}
+
+/** A modal whose own open state is real, so the DOM changes when it closes. */
+function Modal({
+ label,
+ purpose,
+ isOpenInitially = true,
+ children,
+}: {
+ label: string;
+ purpose?: 'required';
+ isOpenInitially?: boolean;
+ children?: React.ReactNode;
+}) {
+ const [isOpen, setIsOpen] = useState(isOpenInitially);
+ return (
+ <Dialog
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ purpose={purpose}
+ aria-label={label}>
+ {label}
+ {children}
+ </Dialog>
+ );
+}
+
+describe('one Escape dismisses exactly one layer', () => {
+ it('peels a modal-in-modal one press at a time', () => {
+ render(
+ <Modal label="Outer">
+ <Modal label="Inner" />
+ </Modal>,
+ );
+ expect(onScreen()).toEqual(['Inner', 'Outer']);
+
+ pressEscape();
+ expect(onScreen()).toEqual(['Outer']);
+
+ pressEscape();
+ expect(onScreen()).toEqual([]);
+ });
+
+ it('peels three layers in order, never two on one press', () => {
+ render(
+ <Modal label="Outer">
+ <Modal label="Middle">
+ <Modal label="Inner" />
+ </Modal>
+ </Modal>,
+ );
+ expect(onScreen()).toEqual(['Inner', 'Middle', 'Outer']);
+
+ pressEscape();
+ expect(onScreen()).toEqual(['Middle', 'Outer']);
+
+ pressEscape();
+ expect(onScreen()).toEqual(['Outer']);
+
+ pressEscape();
+ expect(onScreen()).toEqual([]);
+ });
+
+ it('lets a Lightbox over a required Dialog take the press, and only it', () => {
+ function LightboxInRequired() {
+ const [isLightboxOpen, setIsLightboxOpen] = useState(true);
+ return (
+ <Modal label="Required" purpose="required">
+ <Lightbox
+ isOpen={isLightboxOpen}
+ onOpenChange={setIsLightboxOpen}
+ media={{src: '/photo.jpg', alt: 'A photo'}}
+ />
+ </Modal>
+ );
+ }
+ render(<LightboxInRequired />);
+ expect(onScreen()).toEqual(['A photo', 'Required']);
+
+ pressEscape();
+ expect(onScreen()).toEqual(['Required']);
+ });
+
+ it('reaches the layer below once the one above is closed another way', () => {
+ // Closing the inner modal with its own control must leave the stack clean,
+ // so the next Escape finds the outer rather than falling into a gap.
+ function OuterAndInner() {
+ const [isInnerOpen, setIsInnerOpen] = useState(true);
+ return (
+ <Modal label="Outer">
+ <button type="button" onClick={() => setIsInnerOpen(false)}>
+ close inner
+ </button>
+ {isInnerOpen ? <Modal label="Inner" /> : null}
+ </Modal>
+ );
+ }
+ render(<OuterAndInner />);
+ expect(onScreen()).toEqual(['Inner', 'Outer']);
+
+ act(() => {
+ screen.getByText('close inner').click();
+ });
+ expect(onScreen()).toEqual(['Outer']);
+
+ pressEscape();
+ expect(onScreen()).toEqual([]);
+ });
+});
+
+describe("escapeBehavior: 'block'", () => {
+ it('swallows the press so nothing behind a required Dialog dismisses either', () => {
+ render(
+ <Modal label="Host">
+ <Modal label="Required" purpose="required" />
+ </Modal>,
+ );
+
+ const event = pressEscape();
+
+ expect(onScreen()).toEqual(['Host', 'Required']);
+ // Claimed, not merely ignored — an unclaimed press is what lets the
+ // browser's own close watcher dismiss something behind our back.
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('does not block a layer opened ON TOP of the required Dialog', () => {
+ render(
+ <Modal label="Required" purpose="required">
+ <Modal label="Above" />
+ </Modal>,
+ );
+
+ pressEscape();
+ expect(onScreen()).toEqual(['Required']);
+ });
+});
+
+describe('re-registration does not reorder the stack', () => {
+ it('keeps a Dialog whose purpose flips below the layer opened over it', () => {
+ // A Dialog re-registers when `purpose` changes, because that changes its
+ // escapeBehavior. Re-registering must not promote it above a layer that
+ // opened on top of it — otherwise a flip to `required` silently starts
+ // swallowing presses meant for the layer above.
+ function FlippingHost() {
+ const [purpose, setPurpose] = useState<'required' | undefined>(undefined);
+ return (
+ <>
+ <Modal label="Host" purpose={purpose} />
+ <Modal label="Later" />
+ <button type="button" onClick={() => setPurpose('required')}>
+ make required
+ </button>
+ </>
+ );
+ }
+ render(<FlippingHost />);
+ expect(onScreen()).toEqual(['Host', 'Later']);
+
+ act(() => {
+ screen.getByText('make required').click();
+ });
+
+ pressEscape();
+ expect(onScreen()).toEqual(['Host']);
+ });
+});
+
+describe('close requests the browser starts itself', () => {
+ it('follows the same top-most rule as a press', () => {
+ render(
+ <Modal label="Outer">
+ <Modal label="Inner" />
+ </Modal>,
+ );
+
+ // The Android back gesture on the layer that is NOT on top.
+ const outerRequest = fireCancel('Outer');
+ expect(outerRequest.defaultPrevented).toBe(true);
+ expect(onScreen()).toEqual(['Inner', 'Outer']);
+
+ fireCancel('Inner');
+ expect(onScreen()).toEqual(['Outer']);
+ });
+
+ it('is declined while an IME composition is running', () => {
+ render(
+ <Modal label="Composing">
+ <input aria-label="field" />
+ </Modal>,
+ );
+ const field = screen.getByLabelText('field');
+
+ act(() => {
+ field.dispatchEvent(
+ new CompositionEvent('compositionstart', {bubbles: true}),
+ );
+ });
+ fireCancel('Composing');
+ expect(onScreen()).toEqual(['Composing']);
+
+ act(() => {
+ field.dispatchEvent(
+ new CompositionEvent('compositionend', {bubbles: true}),
+ );
+ });
+ fireCancel('Composing');
+ expect(onScreen()).toEqual([]);
+ });
+});
+
+describe('an Escape that cancels an IME composition', () => {
+ it('dismisses nothing AND claims the press, so no close request follows', () => {
+ render(<Modal label="Composing" />);
+
+ const event = composingEscape();
+
+ expect(onScreen()).toEqual(['Composing']);
+ // The half that matters. Standing down without claiming leaves the browser
+ // free to raise its own close request, which arrives at `cancel` with no
+ // composition state to read and closes the dialog on the same keypress.
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('leaves the press alone when there is no layer to protect', () => {
+ render(<Modal label="Closed" isOpenInitially={false} />);
+
+ const event = composingEscape();
+
+ expect(event.defaultPrevented).toBe(false);
+ });
+});
+
+describe('registration and teardown', () => {
+ it('drops a layer from the stack when it unmounts', () => {
+ function Pair({hasTop}: {hasTop: boolean}) {
+ return (
+ <Modal label="Bottom">{hasTop ? <Modal label="Top" /> : null}</Modal>
+ );
+ }
+ const {rerender} = render(<Pair hasTop={true} />);
+ rerender(<Pair hasTop={false} />);
+
+ pressEscape();
+ expect(onScreen()).toEqual([]);
+ });
+
+ it('stops claiming Escape once the last layer is gone', () => {
+ // The listener is shared and lives on `document`. If unmounting left an
+ // entry behind, the page would keep losing Escape presses to a layer that
+ // is not there — no error, no visual tell.
+ const {unmount} = render(<Modal label="Only" />);
+ expect(pressEscape().defaultPrevented).toBe(true);
+
+ unmount();
+
+ expect(pressEscape().defaultPrevented).toBe(false);
+ });
+});
+
+describe('presence is asked at press time', () => {
+ it('skips a registered layer that is no longer on screen', () => {
+ // Hover layers register for their whole lifetime and answer presence from
+ // the DOM. A cached answer would let an idle tooltip eat a press meant for
+ // the dialog underneath it.
+ const isTipShowing = false;
+ const tipDismissed = vi.fn();
+
+ function TipLayer() {
+ useLayerDismissal({
+ isActive: true,
+ isPresent: () => isTipShowing,
+ onDismiss: tipDismissed,
+ });
+ return null;
+ }
+
+ render(
+ <Modal label="Host">
+ <TipLayer />
+ </Modal>,
+ );
+
+ // Idle: the press must reach the dialog.
+ pressEscape();
+ expect(tipDismissed).not.toHaveBeenCalled();
+ expect(onScreen()).toEqual([]);
+ });
+
+ it('lets the same registration claim the press once it is showing', () => {
+ let isTipShowing = true;
+ const tipDismissed = vi.fn();
+
+ function TipLayer() {
+ useLayerDismissal({
+ isActive: true,
+ isPresent: () => isTipShowing,
+ onDismiss: tipDismissed,
+ });
+ return null;
+ }
+
+ render(
+ <Modal label="Host">
+ <TipLayer />
+ </Modal>,
+ );
+
+ pressEscape();
+ expect(tipDismissed).toHaveBeenCalledTimes(1);
+ expect(onScreen()).toEqual(['Host']);
+
+ isTipShowing = false;
+ pressEscape();
+ expect(onScreen()).toEqual([]);
+ });
+});
diff --git a/packages/core/src/Layer/layerStack.ts b/packages/core/src/Layer/layerStack.ts
new file mode 100644
index 0000000000..b1842d305d
--- /dev/null
+++ b/packages/core/src/Layer/layerStack.ts
@@ -0,0 +1,362 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file layerStack.ts
+ * @input Uses the isImeKeyEvent predicate from utils/ime
+ * @output Exports the shared layer dismissal stack: registration, top-most
+ * ordering, and the single document-level Escape listener
+ * @position Internal to the Layer system; consumed by useLayerDismissal, which
+ * is what overlays actually call. Not exported from the package root.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Layer/useLayerDismissal.ts
+ * - /packages/core/src/Layer/useLayerDismissal.test.tsx
+ *
+ * ## Why one stack
+ *
+ * Every overlay used to own its own Escape listener, so one press dismissed
+ * every open layer (a popover inside a Dialog closed both; a Modal opened from
+ * inside another Modal closed both). Patching this per primitive produced
+ * parallel registries — the focus-trap Escape stack, Drawer's LIFO registry,
+ * useScrollLock's counter. This module is the single registry those collapse
+ * into. One press dismisses exactly one layer.
+ *
+ * ## Only the top layer acts
+ *
+ * The stack owns ONE `keydown` listener on `document` and routes the press to
+ * the top-most layer itself. Overlays do not listen; they register and say what
+ * they want done. The alternative — every layer listens and filters itself out
+ * — is what forces `stopPropagation()` choreography between element-level and
+ * document-level listeners, and it silently breaks whenever a layer forgets.
+ *
+ * ## Bubble phase, not capture
+ *
+ * The listener is on the BUBBLE phase so content inside a layer can claim the
+ * press first, either by `stopPropagation()` (the press never reaches us) or by
+ * `preventDefault()` (we see it and stand down). Editors are the motivating
+ * case: Monaco and the rich-text editor use Escape to close their own find
+ * widget or autocomplete, and that must win over dismissing the Dialog they sit
+ * in. A capture-phase listener would take the press away from them.
+ *
+ * ## The stack, not the browser, decides
+ *
+ * When the stack handles a press it calls `preventDefault()`, which suppresses
+ * the browser's own close-watcher behavior — both `<dialog>`'s `cancel` event
+ * and `popover="auto"` light-dismiss (verified in Chromium; the default action
+ * runs after propagation, so a bubble-phase `preventDefault` still beats it).
+ * That is deliberate: the native top layer only covers `showModal()` and
+ * `popover="auto"`, so relying on it would leave non-modal `show()` drawers,
+ * `popover="manual"` layers, and older browsers on a second, differently-behaved
+ * code path. One code path, one ordering, everywhere.
+ *
+ * ## An Escape that cancels an IME composition
+ *
+ * That press is not a dismissal, so no layer acts on it — but the stack still
+ * claims it, because an unclaimed Escape is exactly what makes the browser
+ * raise a close request, and that request dismisses the layer through its
+ * `cancel` handler on the same keypress. Claiming is the whole fix; the guard
+ * that only returns measures identically to no guard at all.
+ *
+ * Close requests that arrive with no keydown to read — the Android back
+ * gesture, the platform close watcher — are answered by the hosts, which ask
+ * `isTextComposing()` through `useLayerDismissal`.
+ */
+
+import {isImeKeyEvent} from '../utils/ime';
+
+/**
+ * What a layer does with an Escape press that reaches it.
+ *
+ * - `'close'` — dismiss this layer and consume the press. One Escape closes
+ * exactly this layer. The default, and correct for every dismissible layer:
+ * modals, popovers, menus, comboboxes, and hover layers alike.
+ * - `'block'` — consume the press WITHOUT dismissing. For a layer that requires
+ * an explicit choice (`Dialog purpose="required"`): Escape must not dismiss
+ * it, and must not fall through and dismiss something behind it either.
+ *
+ * There is deliberately no "dismiss but let the press continue" variant. Escape
+ * affects exactly one layer, always — a rule with no per-component exceptions
+ * is one users can predict. Hover layers were the tempting exception (the user
+ * never opened the tip, so why should it eat their press?), but guessing wrong
+ * that way is destructive: someone dismissing a stray tooltip over a form would
+ * lose the whole dialog. Guessing wrong the other way costs one keystroke.
+ */
+export type LayerEscapeBehavior = 'close' | 'block';
+
+export interface LayerStackEntry {
+ /**
+ * Identity for removal; also the equality check for top-most, and the key
+ * `seq` is assigned against so a layer keeps its place across re-registration.
+ */
+ token: object;
+ /**
+ * Nesting depth from the React tree (see LayerDepthContext), NOT the DOM.
+ * Context flows through portals and is known during render, so it is correct
+ * for layers that portal out and for an inner + outer layer that open in the
+ * same commit — the case where effect order lies, because React runs child
+ * effects before parent effects.
+ */
+ depth: number;
+ /**
+ * Monotonic registration order; breaks ties between unrelated layers. For a
+ * layer that registers when it opens this is open order; a hover layer
+ * registers at mount and answers `isPresent` instead, so for two of those it
+ * is mount order rather than which one appeared first.
+ *
+ * Keyed to `token`, not to the registration, because a layer re-registers
+ * whenever its behavior or depth changes and must not overtake the layers
+ * above it.
+ */
+ seq: number;
+ behavior: LayerEscapeBehavior;
+ /**
+ * The layer's container element, read lazily at press time. Used only to
+ * break ties between layers the React tree reports at the same depth — a raw
+ * `useFocusTrap` cannot wrap its content in a depth provider (it renders
+ * nothing), so DOM containment is the only nesting signal those have.
+ */
+ getContainer?: () => HTMLElement | null;
+ /**
+ * Whether the layer is really on screen right now, asked at press time.
+ *
+ * Registration alone is not proof: a layer whose open state lives in React
+ * state can lag a frame behind the DOM, so gating registration on that state
+ * drops presses that arrive in the gap. Such layers register for their whole
+ * lifetime and answer this from the DOM instead. Omit it to mean "registered
+ * means present", which is true for layers that register on open.
+ */
+ isPresent?: () => boolean;
+ dismiss: () => void;
+}
+
+const entries: LayerStackEntry[] = [];
+// Registration order per layer identity. A layer re-registers whenever its
+// depth or behavior changes — a Dialog whose `purpose` flips while open, a focus trap
+// that moves — and StrictMode remounts every effect once more on top of that.
+// Counting registrations instead would hand the layer a fresh, higher seq each
+// time and promote it above the layers opened over it.
+let seqByToken = new WeakMap<object, number>();
+let nextSeq = 0;
+let isListening = false;
+
+function seqFor(token: object): number {
+ const existing = seqByToken.get(token);
+ if (existing !== undefined) {
+ return existing;
+ }
+ const seq = nextSeq++;
+ seqByToken.set(token, seq);
+ return seq;
+}
+
+/**
+ * Order two entries: positive when `a` is above `b`, negative when below.
+ * Three keys, each earning its place:
+ *
+ * 1. **Depth.** The layer nested inside the other is on top. This is what makes
+ * an inner-and-outer pair that mount in the SAME commit come out right;
+ * registration order alone gets it backwards, because React runs child
+ * effects before parent effects.
+ * 2. **DOM containment.** Depth only moves when a layer wraps its content in a
+ * `LayerDepthProvider`, which a bare `useFocusTrap` cannot do — it renders
+ * nothing. For those, containment recovers the nesting the tree did not
+ * report.
+ * 3. **Registration order.** For unrelated layers, the one that registered
+ * later is on top, matching how the browser's own top layer stacks. A layer
+ * keeps its first place for as long as its identity lives, so one that
+ * closes and reopens does not move to the top — see the known edge in the
+ * pull request.
+ *
+ * Modality is deliberately NOT a key. Ranking modals above everything sounds
+ * right and is not: a hover tip shown inside a modal renders on top of it, so
+ * a modal-first rule would hand the press to the dialog and strand the tip.
+ * Nesting already covers the case modality was meant to catch — a layer opened
+ * from inside another is deeper, modal or not.
+ *
+ * Note this is a PARTIAL order: containment relates only nested pairs. Callers
+ * must resolve the top with a pairwise max scan, never `Array.sort`, whose
+ * result is undefined for a non-transitive comparator.
+ */
+function compareEntries(a: LayerStackEntry, b: LayerStackEntry): number {
+ if (a.depth !== b.depth) {
+ return a.depth - b.depth;
+ }
+ const aEl = a.getContainer?.() ?? null;
+ const bEl = b.getContainer?.() ?? null;
+ if (aEl != null && bEl != null && aEl !== bEl) {
+ if (bEl.contains(aEl)) {
+ return 1;
+ }
+ if (aEl.contains(bEl)) {
+ return -1;
+ }
+ }
+ return a.seq - b.seq;
+}
+
+function isPresentEntry(entry: LayerStackEntry): boolean {
+ return entry.isPresent?.() ?? true;
+}
+
+// Whether a text composition is running anywhere on the page. Tracked from
+// composition events because the DOM offers no way to ask.
+let isComposing = false;
+
+/**
+ * Whether the user is part-way through composing text with an IME.
+ *
+ * The stack reads this to decide what an Escape means, and layers read it
+ * through `useLayerDismissal`'s `shouldDismissOnCloseRequest` for the close
+ * requests that arrive without a keydown to inspect — the Android back
+ * gesture, the platform close watcher, or a composing Escape whose keydown
+ * never reached this listener because content stopped it. Mid-composition,
+ * those are far more likely to be the user backing out of a half-formed
+ * character than a request to dismiss a layer, and guessing wrong that way
+ * costs them everything they have typed into it.
+ *
+ * Scope, deliberately page-wide: a composition in a field behind a non-modal
+ * layer also suppresses that layer's close requests. It is one keypress to
+ * recover from, and the alternative — matching the composing element against
+ * a layer's container — cannot work for the layers that do not have one.
+ *
+ * A composition already running when the first layer registers is invisible
+ * here: the listeners go on with the stack's own.
+ */
+export function isTextComposing(): boolean {
+ return isComposing;
+}
+
+function handleCompositionStart(): void {
+ isComposing = true;
+}
+
+// Focus leaving the field ends the composition too. Clearing on blur as well
+// means a compositionend this listener never sees cannot leave the flag stuck
+// on, swallowing every later close request.
+function handleCompositionEnd(): void {
+ isComposing = false;
+}
+
+/** The top-most present layer, or null when nothing is on screen. */
+function topPresentEntry(): LayerStackEntry | null {
+ let top: LayerStackEntry | null = null;
+ for (const entry of entries) {
+ if (!isPresentEntry(entry)) {
+ continue;
+ }
+ if (top == null || compareEntries(entry, top) > 0) {
+ top = entry;
+ }
+ }
+ return top;
+}
+
+/**
+ * Whether `token` identifies the top-most layer. Overlays that still own a
+ * dismissal channel the stack does not model yet (outside-press, swipe) can
+ * gate on this so every channel agrees on who is on top.
+ */
+export function isTopmostLayer(token: object): boolean {
+ return topPresentEntry()?.token === token;
+}
+
+/** Resolve an Escape press against the stack. Returns whether it was handled. */
+function dispatchEscape(): boolean {
+ const top = topPresentEntry();
+ if (top == null) {
+ return false;
+ }
+ if (top.behavior === 'block') {
+ return true;
+ }
+ top.dismiss();
+ return true;
+}
+
+function handleKeyDown(event: KeyboardEvent): void {
+ if (event.key !== 'Escape') {
+ return;
+ }
+ // An IME user pressing Escape is cancelling a composition, not dismissing a
+ // layer. Claim the press anyway, then stand down: left unclaimed, the browser
+ // raises its own close request, which arrives at a layer's `cancel` handler
+ // and dismisses it on this very keypress — measured in Chromium, where a
+ // guard that only returns behaves exactly like no guard at all. Claim it only
+ // while a layer is on screen; with nothing to protect, the press is not ours.
+ if (isImeKeyEvent(event)) {
+ if (topPresentEntry() != null) {
+ event.preventDefault();
+ }
+ return;
+ }
+ // Content inside a layer already claimed this press (see the bubble-phase
+ // note in the file header). Honor it and leave the default action alone.
+ if (event.defaultPrevented) {
+ return;
+ }
+ if (dispatchEscape()) {
+ // Suppress the browser's own close-watcher so it cannot dismiss a second
+ // layer behind our back. Propagation is left alone: consumers may
+ // legitimately listen for Escape on window, and the stack's decision is
+ // already recorded in defaultPrevented.
+ event.preventDefault();
+ }
+}
+
+function startListening(): void {
+ if (isListening || typeof document === 'undefined') {
+ return;
+ }
+ document.addEventListener('keydown', handleKeyDown);
+ document.addEventListener('compositionstart', handleCompositionStart, true);
+ document.addEventListener('compositionend', handleCompositionEnd, true);
+ document.addEventListener('blur', handleCompositionEnd, true);
+ isListening = true;
+}
+
+function stopListening(): void {
+ if (!isListening || typeof document === 'undefined') {
+ return;
+ }
+ document.removeEventListener('keydown', handleKeyDown);
+ document.removeEventListener(
+ 'compositionstart',
+ handleCompositionStart,
+ true,
+ );
+ document.removeEventListener('compositionend', handleCompositionEnd, true);
+ document.removeEventListener('blur', handleCompositionEnd, true);
+ isComposing = false;
+ isListening = false;
+}
+
+/**
+ * Add a layer to the stack for as long as it is active. Returns the unregister
+ * function; callers own calling it.
+ */
+export function registerLayer(entry: Omit<LayerStackEntry, 'seq'>): () => void {
+ const full: LayerStackEntry = {...entry, seq: seqFor(entry.token)};
+ entries.push(full);
+ startListening();
+
+ return () => {
+ const index = entries.indexOf(full);
+ if (index !== -1) {
+ entries.splice(index, 1);
+ }
+ if (entries.length === 0) {
+ stopListening();
+ }
+ };
+}
+
+/** Test-only: drop all entries and detach the listener. */
+export function resetLayerStackForTests(): void {
+ entries.length = 0;
+ seqByToken = new WeakMap();
+ nextSeq = 0;
+ isComposing = false;
+ stopListening();
+}
diff --git a/packages/core/src/Layer/useLayerDismissal.test.tsx b/packages/core/src/Layer/useLayerDismissal.test.tsx
new file mode 100644
index 0000000000..8ca73ed75a
--- /dev/null
+++ b/packages/core/src/Layer/useLayerDismissal.test.tsx
@@ -0,0 +1,469 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useLayerDismissal.test.tsx
+ * @input Uses @testing-library/react, vitest
+ * @output Tests for the shared layer dismissal stack
+ * @position Colocated tests for useLayerDismissal + layerStack
+ *
+ * Every case here is "one Escape press, which layers reacted?" — the single
+ * question the stack exists to answer.
+ */
+
+import {render, fireEvent} from '@testing-library/react';
+import {describe, expect, it, vi, afterEach} from 'vitest';
+import {StrictMode, useRef} from 'react';
+
+import {LayerDepthProvider} from './LayerDepthContext';
+import {useLayerDismissal} from './useLayerDismissal';
+import {resetLayerStackForTests} from './layerStack';
+import type {LayerEscapeBehavior} from './layerStack';
+
+afterEach(() => {
+ resetLayerStackForTests();
+});
+
+/** A layer that registers itself and renders its children one level deeper. */
+function Layer({
+ onDismiss,
+ behavior = 'close',
+ isEnabled = true,
+ isActive = true,
+ isPresent,
+ children,
+}: {
+ onDismiss: () => void;
+ behavior?: LayerEscapeBehavior;
+ isEnabled?: boolean;
+ isActive?: boolean;
+ isPresent?: () => boolean;
+ children?: React.ReactNode;
+}) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ useLayerDismissal({
+ isActive,
+ onDismiss,
+ escapeBehavior: behavior,
+ isEnabled,
+ isPresent,
+ getContainer: () => containerRef.current,
+ });
+ return (
+ <div ref={containerRef}>
+ <LayerDepthProvider>{children}</LayerDepthProvider>
+ </div>
+ );
+}
+
+/** A layer that reports no depth — like a bare focus trap, which renders nothing. */
+function FlatLayer({
+ onDismiss,
+ children,
+}: {
+ onDismiss: () => void;
+ children?: React.ReactNode;
+}) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ useLayerDismissal({
+ isActive: true,
+ onDismiss,
+ getContainer: () => containerRef.current,
+ });
+ return <div ref={containerRef}>{children}</div>;
+}
+
+const pressEscape = () => fireEvent.keyDown(document, {key: 'Escape'});
+
+describe('useLayerDismissal', () => {
+ it('dismisses only the top-most layer when both open in the same commit', () => {
+ // The regression: an inner and outer layer that mount together. React runs
+ // child effects first, so registration order reports the inner layer as the
+ // OLDER one — nesting, not order, has to decide.
+ const outer = vi.fn();
+ const inner = vi.fn();
+
+ render(
+ <Layer onDismiss={outer}>
+ <Layer onDismiss={inner} />
+ </Layer>,
+ );
+
+ pressEscape();
+ expect(inner).toHaveBeenCalledTimes(1);
+ expect(outer).not.toHaveBeenCalled();
+ });
+
+ it('falls through to the outer layer once the inner one closes', () => {
+ const outer = vi.fn();
+ const inner = vi.fn();
+ const {rerender} = render(
+ <Layer onDismiss={outer}>
+ <Layer onDismiss={inner} />
+ </Layer>,
+ );
+ rerender(<Layer onDismiss={outer} />);
+
+ pressEscape();
+ expect(outer).toHaveBeenCalledTimes(1);
+ expect(inner).not.toHaveBeenCalled();
+ });
+
+ it('dismisses the later of two unrelated layers', () => {
+ const first = vi.fn();
+ const second = vi.fn();
+ const {rerender} = render(<Layer onDismiss={first} />);
+ rerender(
+ <>
+ <Layer onDismiss={first} />
+ <Layer onDismiss={second} />
+ </>,
+ );
+
+ pressEscape();
+ expect(second).toHaveBeenCalledTimes(1);
+ expect(first).not.toHaveBeenCalled();
+ });
+
+ it('resolves nesting by DOM containment when the tree reports equal depth', () => {
+ // A bare focus trap renders nothing, so it cannot push a depth provider.
+ // Containment is the only nesting signal those layers have.
+ const outer = vi.fn();
+ const inner = vi.fn();
+ render(
+ <FlatLayer onDismiss={outer}>
+ <FlatLayer onDismiss={inner} />
+ </FlatLayer>,
+ );
+
+ pressEscape();
+ expect(inner).toHaveBeenCalledTimes(1);
+ expect(outer).not.toHaveBeenCalled();
+ });
+
+ describe('escapeBehavior', () => {
+ it("'close' consumes the press, so one Escape affects exactly one layer", () => {
+ // A hover tip inside a modal: the tip is on top, so it takes the press
+ // and the modal stays open. A second Escape closes the modal.
+ const modal = vi.fn();
+ const tip = vi.fn();
+ render(
+ <Layer onDismiss={modal}>
+ <Layer onDismiss={tip} />
+ </Layer>,
+ );
+
+ pressEscape();
+ expect(tip).toHaveBeenCalledTimes(1);
+ expect(modal).not.toHaveBeenCalled();
+ });
+
+ it("'block' consumes the press without dismissing anything", () => {
+ const host = vi.fn();
+ const required = vi.fn();
+ render(
+ <Layer onDismiss={host}>
+ <Layer onDismiss={required} behavior="block" />
+ </Layer>,
+ );
+
+ pressEscape();
+ expect(required).not.toHaveBeenCalled();
+ expect(host).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('registration order', () => {
+ /** Two unrelated same-depth layers; the older one's behavior is a prop. */
+ function Siblings({
+ olderBehavior,
+ onOlderDismiss,
+ onNewerDismiss,
+ }: {
+ olderBehavior: LayerEscapeBehavior;
+ onOlderDismiss: () => void;
+ onNewerDismiss: () => void;
+ }) {
+ return (
+ <>
+ <Layer onDismiss={onOlderDismiss} behavior={olderBehavior} />
+ <Layer onDismiss={onNewerDismiss} />
+ </>
+ );
+ }
+
+ it('keeps a layer below the ones that opened after it when its escapeBehavior changes', () => {
+ // A Dialog whose `purpose` flips from required to info while it is open
+ // re-registers with the stack. Re-registration must not reorder it above
+ // a layer opened on top of it.
+ const older = vi.fn();
+ const newer = vi.fn();
+ const {rerender} = render(
+ <Siblings
+ olderBehavior="block"
+ onOlderDismiss={older}
+ onNewerDismiss={newer}
+ />,
+ );
+ rerender(
+ <Siblings
+ olderBehavior="close"
+ onOlderDismiss={older}
+ onNewerDismiss={newer}
+ />,
+ );
+
+ pressEscape();
+ expect(newer).toHaveBeenCalledTimes(1);
+ expect(older).not.toHaveBeenCalled();
+ });
+
+ it('does not let a re-registered layer swallow a press meant for the layer above it', () => {
+ // The same flip the other way: info to required. A `block` layer that
+ // jumped the queue would consume the press and nothing would close.
+ const older = vi.fn();
+ const newer = vi.fn();
+ const {rerender} = render(
+ <Siblings
+ olderBehavior="close"
+ onOlderDismiss={older}
+ onNewerDismiss={newer}
+ />,
+ );
+ rerender(
+ <Siblings
+ olderBehavior="block"
+ onOlderDismiss={older}
+ onNewerDismiss={newer}
+ />,
+ );
+
+ pressEscape();
+ expect(newer).toHaveBeenCalledTimes(1);
+ expect(older).not.toHaveBeenCalled();
+ });
+
+ it('keeps ordering under StrictMode, which mounts every effect twice', () => {
+ const first = vi.fn();
+ const second = vi.fn();
+ render(
+ <StrictMode>
+ <Layer onDismiss={first} />
+ <Layer onDismiss={second} />
+ </StrictMode>,
+ );
+
+ pressEscape();
+ expect(second).toHaveBeenCalledTimes(1);
+ expect(first).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('presence', () => {
+ it('skips a registered layer that is not on screen', () => {
+ // Hover layers stay registered for their lifetime because their open
+ // state lags the DOM. An absent one must not claim the press — that is
+ // exactly the bug where a HoverCard trigger ate Escapes while idle.
+ const below = vi.fn();
+ const absent = vi.fn();
+ render(
+ <Layer onDismiss={below}>
+ <Layer onDismiss={absent} isPresent={() => false} />
+ </Layer>,
+ );
+
+ pressEscape();
+ expect(absent).not.toHaveBeenCalled();
+ expect(below).toHaveBeenCalledTimes(1);
+ });
+
+ it('lets a present layer claim the press over the one beneath', () => {
+ const below = vi.fn();
+ const present = vi.fn();
+ render(
+ <Layer onDismiss={below}>
+ <Layer onDismiss={present} isPresent={() => true} />
+ </Layer>,
+ );
+
+ pressEscape();
+ expect(present).toHaveBeenCalledTimes(1);
+ expect(below).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('opting out', () => {
+ it('skips a disabled layer entirely, so the press reaches the one below', () => {
+ const below = vi.fn();
+ const optedOut = vi.fn();
+ render(
+ <Layer onDismiss={below}>
+ <Layer onDismiss={optedOut} isEnabled={false} />
+ </Layer>,
+ );
+
+ pressEscape();
+ expect(optedOut).not.toHaveBeenCalled();
+ expect(below).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not register an inactive layer', () => {
+ const onDismiss = vi.fn();
+ render(<Layer onDismiss={onDismiss} isActive={false} />);
+
+ pressEscape();
+ expect(onDismiss).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('deferring to content', () => {
+ it('stands down when content already handled the press', () => {
+ // preventDefault from inside the layer — an editor claiming Escape for
+ // its own find widget, for instance.
+ const onDismiss = vi.fn();
+ render(
+ <Layer onDismiss={onDismiss}>
+ <button
+ type="button"
+ data-testid="editor"
+ onKeyDown={e => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ }
+ }}
+ />
+ </Layer>,
+ );
+
+ fireEvent.keyDown(document.querySelector('[data-testid="editor"]')!, {
+ key: 'Escape',
+ });
+ expect(onDismiss).not.toHaveBeenCalled();
+ });
+
+ it('ignores Escape that is cancelling an IME composition', () => {
+ const onDismiss = vi.fn();
+ render(<Layer onDismiss={onDismiss} />);
+
+ fireEvent.keyDown(document, {key: 'Escape', isComposing: true});
+ expect(onDismiss).not.toHaveBeenCalled();
+
+ fireEvent.keyDown(document, {key: 'Escape', keyCode: 229});
+ expect(onDismiss).not.toHaveBeenCalled();
+
+ pressEscape();
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ });
+
+ it('claims the composing Escape so the browser raises no close request', () => {
+ // Not dismissing is only half of it. An unclaimed Escape lets the browser
+ // raise its own close request, which reaches the layer's `cancel` handler
+ // and dismisses it on the same keypress — so the guard has to swallow the
+ // press, not merely skip the dismissal.
+ render(<Layer onDismiss={vi.fn()} />);
+ const event = new KeyboardEvent('keydown', {
+ key: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ });
+ Object.defineProperty(event, 'isComposing', {value: true});
+
+ document.dispatchEvent(event);
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('leaves a composing Escape alone when no layer is on screen', () => {
+ // With nothing to protect the press is not ours to take: an idle hover
+ // layer in the tree must not suppress the page's own close watcher.
+ render(<Layer onDismiss={vi.fn()} isPresent={() => false} />);
+ const event = new KeyboardEvent('keydown', {
+ key: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ });
+ Object.defineProperty(event, 'isComposing', {value: true});
+
+ document.dispatchEvent(event);
+ expect(event.defaultPrevented).toBe(false);
+ });
+ });
+
+ describe('close requests the browser starts itself', () => {
+ // The Android back gesture and the platform close watcher arrive as a
+ // `cancel` with no keydown to read, so the keydown guard cannot see them.
+ function CloseRequestLayer({onAsk}: {onAsk: (answer: boolean) => void}) {
+ const {shouldDismissOnCloseRequest} = useLayerDismissal({
+ isActive: true,
+ onDismiss: () => {},
+ });
+ return (
+ <>
+ <input aria-label="composing field" />
+ <button
+ type="button"
+ onClick={() => onAsk(shouldDismissOnCloseRequest())}>
+ ask
+ </button>
+ </>
+ );
+ }
+
+ const ask = (onAsk: ReturnType<typeof vi.fn>): boolean => {
+ fireEvent.click(document.querySelector('button')!);
+ return Boolean(onAsk.mock.lastCall?.[0]);
+ };
+
+ it('declines while an IME composition is running, and again once it ends', () => {
+ const onAsk = vi.fn();
+ render(<CloseRequestLayer onAsk={onAsk} />);
+ const field = document.querySelector('input')!;
+
+ expect(ask(onAsk)).toBe(true);
+
+ fireEvent.compositionStart(field);
+ expect(ask(onAsk)).toBe(false);
+
+ fireEvent.compositionEnd(field);
+ expect(ask(onAsk)).toBe(true);
+ });
+
+ it('stops declining when focus leaves a field mid-composition', () => {
+ // A compositionend the stack never sees would otherwise leave the flag
+ // stuck on, and every later back gesture would be swallowed.
+ const onAsk = vi.fn();
+ render(<CloseRequestLayer onAsk={onAsk} />);
+ const field = document.querySelector('input')!;
+
+ fireEvent.compositionStart(field);
+ expect(ask(onAsk)).toBe(false);
+
+ fireEvent.blur(field);
+ expect(ask(onAsk)).toBe(true);
+ });
+ });
+
+ it('leaves the event alone when no layer is open', () => {
+ // Nothing registered: the browser keeps its own Escape behavior (exiting
+ // fullscreen, closing a native picker).
+ render(<div />);
+ const event = new KeyboardEvent('keydown', {
+ key: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ });
+ document.dispatchEvent(event);
+ expect(event.defaultPrevented).toBe(false);
+ });
+
+ it('claims the press it handles so the browser does not act too', () => {
+ // preventDefault is what stops the native close-watcher dismissing a second
+ // layer behind the stack's back.
+ render(<Layer onDismiss={vi.fn()} />);
+ const event = new KeyboardEvent('keydown', {
+ key: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ });
+ document.dispatchEvent(event);
+ expect(event.defaultPrevented).toBe(true);
+ });
+});
diff --git a/packages/core/src/Layer/useLayerDismissal.ts b/packages/core/src/Layer/useLayerDismissal.ts
new file mode 100644
index 0000000000..60a913f944
--- /dev/null
+++ b/packages/core/src/Layer/useLayerDismissal.ts
@@ -0,0 +1,173 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useLayerDismissal.ts
+ * @input Uses React hooks, the layer stack, and LayerDepthContext
+ * @output Exports useLayerDismissal + its option/return types
+ * @position The API overlays use to join the shared dismissal stack. Wraps
+ * layerStack (registration + the single Escape listener) and reads nesting
+ * depth from LayerDepthContext.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Layer/index.ts
+ * - /packages/core/src/Layer/useLayerDismissal.test.tsx
+ * - /packages/core/src/Layer/layerStack.ts
+ */
+
+import {useCallback, useEffect, useRef} from 'react';
+
+import {useLayerDepth} from './LayerDepthContext';
+import {
+ isTextComposing,
+ isTopmostLayer,
+ registerLayer,
+ type LayerEscapeBehavior,
+} from './layerStack';
+
+export type {LayerEscapeBehavior};
+
+export interface UseLayerDismissalOptions {
+ /**
+ * Whether this layer is participating right now. Usually the layer's open
+ * state. A layer whose open state lags the DOM should pass `true` for its
+ * lifetime and answer `isPresent` from the DOM instead.
+ */
+ isActive: boolean;
+ /**
+ * Dismiss this layer. Called by the stack when this layer is the one that
+ * should respond to an Escape press. Not called for `escapeBehavior: 'block'`.
+ */
+ onDismiss: () => void;
+ /**
+ * What this layer does with an Escape press that reaches it.
+ * @default 'close'
+ */
+ escapeBehavior?: LayerEscapeBehavior;
+ /**
+ * This layer's container element, read lazily. Optional: supply it when the
+ * layer cannot wrap its content in `LayerDepthProvider` (a bare focus trap
+ * renders nothing), so nesting can still be recovered from the DOM.
+ */
+ getContainer?: () => HTMLElement | null;
+ /**
+ * Whether the layer is really on screen, asked at press time. Supply it when
+ * `isActive` is `true` for the layer's lifetime because its open state lags
+ * the DOM by a frame; the stack skips layers that answer `false`.
+ */
+ isPresent?: () => boolean;
+ /**
+ * Whether this layer takes part in the shared stack at all. When `false` the
+ * layer is invisible to dismissal: a press flows past it to the layer below,
+ * exactly as if it were not open.
+ *
+ * Deliberately separate from `escapeBehavior: 'block'` — `'block'` is a layer
+ * that is present and swallows the press; this is a layer that is not there
+ * at all. One case uses it: `Dialog`'s inline rendering mode, where content
+ * sits in normal flow with nothing layered over anything.
+ *
+ * A controlled layer is NOT one of these. It stays registered and takes the
+ * press like any other, answering it by calling the consumer's change
+ * handler; whether it then closes is the consumer's decision.
+ *
+ * Layers that are never Escape-dismissible (toasts) should simply not call
+ * this hook.
+ *
+ * @default true
+ */
+ isEnabled?: boolean;
+}
+
+export interface UseLayerDismissalReturn {
+ /**
+ * Whether a close request the browser started on its own — a `<dialog>`'s
+ * `cancel`, the Android back gesture, the platform close watcher — should
+ * dismiss this layer. As well as the top-most rule the stack applies to an
+ * Escape press, it declines a request that arrives while an IME composition
+ * is running, which no `cancel` handler can tell on its own because the
+ * event carries no composition state.
+ */
+ shouldDismissOnCloseRequest: () => boolean;
+}
+
+/**
+ * Join the shared layer dismissal stack for as long as this layer is active.
+ *
+ * The layer does NOT attach a key listener — the stack owns one listener and
+ * routes each Escape press to the top-most REGISTERED layer, so one press
+ * dismisses exactly one of them. Dialog (and what is built on it), Popover and
+ * the menus built on it, Tooltip, HoverCard, Lightbox and MobileNav register
+ * today; `BottomSheetSwitcher` registers through its focus trap when modal and
+ * still handles its own press when not.
+ *
+ * `BottomSheet`, `CommandPalette`, `ContextMenu`, `DropdownMenuSubMenu`,
+ * `PowerSearchEditPopover` and lab's `Drawer` still run their own Escape
+ * listener. 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 layer opened INSIDE one of them does not get the
+ * press: the host takes it and closes instead. Migrating them is the fix.
+ *
+ * Wrap the layer's own content in `LayerDepthProvider` so anything opened from
+ * inside it registers as nested.
+ *
+ * @example
+ * ```tsx
+ * useLayerDismissal({
+ * isActive: isOpen,
+ * onDismiss: () => onOpenChange(false),
+ * });
+ * ```
+ */
+export function useLayerDismissal(
+ options: UseLayerDismissalOptions,
+): UseLayerDismissalReturn {
+ const {
+ isActive,
+ onDismiss,
+ escapeBehavior = 'close',
+ getContainer,
+ isPresent,
+ isEnabled = true,
+ } = options;
+
+ const depth = useLayerDepth();
+
+ // Identity for this layer's stack entry, stable across re-registration.
+ const tokenRef = useRef<object>({});
+
+ // The stack calls these during an event, outside React's render, so they must
+ // reach the latest closures rather than the ones captured at registration.
+ const onDismissRef = useRef(onDismiss);
+ const getContainerRef = useRef(getContainer);
+ const isPresentRef = useRef(isPresent);
+ useEffect(() => {
+ onDismissRef.current = onDismiss;
+ getContainerRef.current = getContainer;
+ isPresentRef.current = isPresent;
+ });
+
+ const isRegistered = isActive && isEnabled;
+
+ useEffect(() => {
+ if (!isRegistered) {
+ return;
+ }
+ return registerLayer({
+ token: tokenRef.current,
+ depth,
+ behavior: escapeBehavior,
+ getContainer: () => getContainerRef.current?.() ?? null,
+ isPresent: () => isPresentRef.current?.() ?? true,
+ dismiss: () => onDismissRef.current(),
+ });
+ }, [isRegistered, depth, escapeBehavior]);
+
+ const shouldDismissOnCloseRequest = useCallback(
+ () =>
+ isRegistered && !isTextComposing() && isTopmostLayer(tokenRef.current),
+ [isRegistered],
+ );
+
+ return {shouldDismissOnCloseRequest};
+}
diff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsx
index 29e9e43e16..cb6ca58eab 100644
--- a/packages/core/src/Lightbox/Lightbox.tsx
+++ b/packages/core/src/Lightbox/Lightbox.tsx
@@ -12,6 +12,7 @@
* - /packages/core/src/Lightbox/Lightbox.doc.mjs (props table, features, implementation notes)
* - /packages/core/src/Lightbox/Lightbox.test.tsx (tests for new/changed behavior)
* - /packages/core/src/Lightbox/index.ts (exports if types change)
+ * - /packages/core/src/Layer/useLayerDismissal.ts (dismissal stack)
* - /apps/storybook/stories/Lightbox.stories.tsx (storybook stories)
* - /packages/cli/assets/templates/blocks/components/Lightbox/ (showcase blocks)
*/
@@ -37,6 +38,8 @@ import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {overlayPaddingReset} from '../Layout/padding.stylex';
+import {LayerDepthProvider} from '../Layer/LayerDepthContext';
+import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {useTranslator} from '../i18n';
/**
@@ -416,13 +419,28 @@ export function Lightbox({
onOpenChange(false);
}, [onOpenChange]);
- // Escape key
+ const {shouldDismissOnCloseRequest} = useLayerDismissal({
+ isActive: isOpen,
+ onDismiss: handleClose,
+ });
+
+ // 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.
+ // Escape presses the stack owns never arrive here — it preventDefault()s
+ // those, which suppresses the close watcher.
+ //
+ // Always preventDefault so the browser cannot close a controlled <dialog>
+ // behind React's back, then answer with the stack's own rules: top-most
+ // only, and never while an IME composition is in progress.
const handleCancel = useCallback(
(e: React.SyntheticEvent) => {
e.preventDefault();
+ if (!shouldDismissOnCloseRequest()) {
+ return;
+ }
handleClose();
},
- [handleClose],
+ [handleClose, shouldDismissOnCloseRequest],
);
// Backdrop click. The layout container fills the whole transparent dialog,
@@ -601,112 +619,114 @@ export function Lightbox({
style,
)}
{...props}>
- <div ref={containerRef} {...stylex.props(styles.container)}>
- {/* Close button */}
- <IconButton
- icon={<Icon icon="close" size="sm" color="inherit" />}
- label={t('@astryx.lightbox.close')}
- variant="ghost"
- onClick={handleClose}
- xstyle={[styles.closeButton, styles.controlButton]}
- />
-
- {/* Gallery nav: prev — stays mounted and is disabled at the start of
- the range so pressing/arrowing to the boundary doesn't unmount the
- focused control and drop focus to <body>. */}
- {isGallery && (
+ <LayerDepthProvider>
+ <div ref={containerRef} {...stylex.props(styles.container)}>
+ {/* Close button */}
<IconButton
- icon={
- <Icon
- icon="chevronLeft"
- size="sm"
- color="inherit"
- xstyle={rtlStyles.mirror}
- />
- }
- label={t('@astryx.lightbox.previous')}
+ icon={<Icon icon="close" size="sm" color="inherit" />}
+ label={t('@astryx.lightbox.close')}
variant="ghost"
- isDisabled={!canPrev}
- onClick={goToPrev}
- xstyle={[styles.navButton, styles.navPrev, styles.controlButton]}
+ onClick={handleClose}
+ xstyle={[styles.closeButton, styles.controlButton]}
/>
- )}
-
- {/* Media + caption group (centered together) */}
- <div {...stylex.props(styles.mediaGroup)}>
- <div
- ref={imageWrapperRef}
- // The wrapper is a keyboard-operable zoom toggle when zoom is
- // enabled: Enter/Space toggles, aria-pressed reflects state.
- role={isZoomTarget ? 'button' : undefined}
- tabIndex={isZoomTarget ? 0 : undefined}
- aria-pressed={isZoomTarget ? isZoomed : undefined}
- aria-label={isZoomTarget ? t('@astryx.lightbox.zoom') : undefined}
- {...stylex.props(
- styles.imageWrapper,
- isZoomTarget && focusOutlineStyles.focusVisible,
- !isVideo && hasZoom && !isZoomed && styles.imageWrapperZoomable,
- !isVideo && isZoomed && styles.imageWrapperZoomed,
- !isVideo && isDragging && styles.imageWrapperDragging,
- )}
- onDoubleClick={isVideo ? undefined : handleDoubleClick}
- onKeyDown={isZoomTarget ? handleImageKeyDown : undefined}
- onPointerDown={isVideo ? undefined : handlePointerDown}>
- {isVideo ? (
- <video
- src={currentItem.src}
- aria-label={currentItem.alt}
- controls
- autoPlay={hasAutoPlay}
- {...stylex.props(styles.video)}
- />
- ) : (
- <img
- src={currentItem.src}
- alt={currentItem.alt}
- draggable={false}
- {...stylex.props(
- styles.image,
- isDragging && styles.imageDragging,
- imageTransform != null &&
- dynamicStyles.imageTransform(imageTransform),
- )}
- />
- )}
- </div>
- {currentItem.caption && (
- <div {...stylex.props(styles.caption)}>{currentItem.caption}</div>
+ {/* Gallery nav: prev — stays mounted and is disabled at the start of
+ the range so pressing/arrowing to the boundary doesn't unmount the
+ focused control and drop focus to <body>. */}
+ {isGallery && (
+ <IconButton
+ icon={
+ <Icon
+ icon="chevronLeft"
+ size="sm"
+ color="inherit"
+ xstyle={rtlStyles.mirror}
+ />
+ }
+ label={t('@astryx.lightbox.previous')}
+ variant="ghost"
+ isDisabled={!canPrev}
+ onClick={goToPrev}
+ xstyle={[styles.navButton, styles.navPrev, styles.controlButton]}
+ />
)}
- </div>
- {/* Gallery nav: next — see "prev" above; stays mounted and disabled at
+ {/* Media + caption group (centered together) */}
+ <div {...stylex.props(styles.mediaGroup)}>
+ <div
+ ref={imageWrapperRef}
+ // The wrapper is a keyboard-operable zoom toggle when zoom is
+ // enabled: Enter/Space toggles, aria-pressed reflects state.
+ role={isZoomTarget ? 'button' : undefined}
+ tabIndex={isZoomTarget ? 0 : undefined}
+ aria-pressed={isZoomTarget ? isZoomed : undefined}
+ aria-label={isZoomTarget ? t('@astryx.lightbox.zoom') : undefined}
+ {...stylex.props(
+ styles.imageWrapper,
+ isZoomTarget && focusOutlineStyles.focusVisible,
+ !isVideo && hasZoom && !isZoomed && styles.imageWrapperZoomable,
+ !isVideo && isZoomed && styles.imageWrapperZoomed,
+ !isVideo && isDragging && styles.imageWrapperDragging,
+ )}
+ onDoubleClick={isVideo ? undefined : handleDoubleClick}
+ onKeyDown={isZoomTarget ? handleImageKeyDown : undefined}
+ onPointerDown={isVideo ? undefined : handlePointerDown}>
+ {isVideo ? (
+ <video
+ src={currentItem.src}
+ aria-label={currentItem.alt}
+ controls
+ autoPlay={hasAutoPlay}
+ {...stylex.props(styles.video)}
+ />
+ ) : (
+ <img
+ src={currentItem.src}
+ alt={currentItem.alt}
+ draggable={false}
+ {...stylex.props(
+ styles.image,
+ isDragging && styles.imageDragging,
+ imageTransform != null &&
+ dynamicStyles.imageTransform(imageTransform),
+ )}
+ />
+ )}
+ </div>
+
+ {currentItem.caption && (
+ <div {...stylex.props(styles.caption)}>{currentItem.caption}</div>
+ )}
+ </div>
+
+ {/* Gallery nav: next — see "prev" above; stays mounted and disabled at
the end of the range instead of unmounting. */}
- {isGallery && (
- <IconButton
- icon={
- <Icon
- icon="chevronRight"
- size="sm"
- color="inherit"
- xstyle={rtlStyles.mirror}
- />
- }
- label={t('@astryx.lightbox.next')}
- variant="ghost"
- isDisabled={!canNext}
- onClick={goToNext}
- xstyle={[styles.navButton, styles.navNext, styles.controlButton]}
- />
- )}
+ {isGallery && (
+ <IconButton
+ icon={
+ <Icon
+ icon="chevronRight"
+ size="sm"
+ color="inherit"
+ xstyle={rtlStyles.mirror}
+ />
+ }
+ label={t('@astryx.lightbox.next')}
+ variant="ghost"
+ isDisabled={!canNext}
+ onClick={goToNext}
+ xstyle={[styles.navButton, styles.navNext, styles.controlButton]}
+ />
+ )}
- {/* Gallery counter */}
- {isGallery && mediaArray.length > 1 && (
- <div {...stylex.props(styles.counter)}>
- {index + 1} / {mediaArray.length}
- </div>
- )}
- </div>
+ {/* Gallery counter */}
+ {isGallery && mediaArray.length > 1 && (
+ <div {...stylex.props(styles.counter)}>
+ {index + 1} / {mediaArray.length}
+ </div>
+ )}
+ </div>
+ </LayerDepthProvider>
</dialog>
);
}
diff --git a/packages/core/src/MobileNav/MobileNav.tsx b/packages/core/src/MobileNav/MobileNav.tsx
index e81918da16..c3d089bafc 100644
--- a/packages/core/src/MobileNav/MobileNav.tsx
+++ b/packages/core/src/MobileNav/MobileNav.tsx
@@ -19,10 +19,15 @@
* - `::backdrop` pseudo-element
* - Body scroll lock
* - Focus trapping
- * - Escape key handling via `cancel` event
+ *
+ * Escape is owned by the shared dismissal stack (`useLayerDismissal`), so a
+ * drawer opened over another layer takes the press and nothing behind it
+ * closes. The native `cancel` event still handles the dismissals the browser
+ * starts itself, such as the Android back gesture.
*
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/MobileNav/index.ts (exports if types change)
+ * - /packages/core/src/Layer/useLayerDismissal.ts (dismissal stack)
* - /packages/core/src/hooks/scrollbarGutter.ts (shared scroll-lock gutter)
* - /packages/cli/assets/templates/blocks/components/MobileNav/ (showcase blocks)
*/
@@ -54,6 +59,8 @@ import {
} from '../hooks/scrollbarGutter';
import {mergeProps, mergeRefs, composeEventHandlers} from '../utils';
import {overlayPaddingReset} from '../Layout/padding.stylex';
+import {LayerDepthProvider} from '../Layer/LayerDepthContext';
+import {useLayerDismissal} from '../Layer/useLayerDismissal';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
@@ -536,13 +543,28 @@ export function MobileNav({
};
}, []);
- // Handle native cancel event (Escape key) — prevent default and route through onOpenChange
+ const {shouldDismissOnCloseRequest} = useLayerDismissal({
+ isActive: isOpen,
+ onDismiss: () => onOpenChange(false),
+ });
+
+ // 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.
+ // Escape presses the stack owns never arrive here — it preventDefault()s
+ // those, which suppresses the close watcher.
+ //
+ // Always preventDefault so the browser cannot close a controlled <dialog>
+ // behind React's back, then answer with the stack's own rules: top-most
+ // only, and never while an IME composition is in progress.
const handleCancel = useCallback(
(event: React.SyntheticEvent<HTMLDialogElement>) => {
event.preventDefault();
+ if (!shouldDismissOnCloseRequest()) {
+ return;
+ }
onOpenChange(false);
},
- [onOpenChange],
+ [onOpenChange, shouldDismissOnCloseRequest],
);
// Handle clicks on the dialog backdrop area (outside the drawer)
@@ -586,38 +608,41 @@ export function MobileNav({
}
onClick={composeEventHandlers(onClickProp, handleDialogClick)}
onCancel={handleCancel}>
- {/* Drawer panel — tabIndex so showModal() focuses the drawer, not the close button */}
- <div
- tabIndex={-1}
- {...stylex.props(
- styles.drawer,
- dynamicStyles.width(width),
- isStart && styles.drawerStart,
- isStart && isOpen && styles.drawerStartOpen,
- !isStart && styles.drawerEnd,
- !isStart && isOpen && styles.drawerEndOpen,
- )}>
- {/* Header — content + close button */}
- <div {...stylex.props(styles.header, !header && styles.headerNoTitle)}>
- {typeof header === 'string' ? (
- <Heading level={2} xstyle={styles.headerText}>
- {header}
- </Heading>
- ) : (
- (header ?? null)
- )}
- <Button
- variant="ghost"
- label={t('@astryx.mobileNav.closeNavigation')}
- icon={<Icon icon="close" color="inherit" />}
- onClick={() => onOpenChange(false)}
- isIconOnly
- />
+ <LayerDepthProvider>
+ {/* Drawer panel — tabIndex so showModal() focuses the drawer, not the close button */}
+ <div
+ tabIndex={-1}
+ {...stylex.props(
+ styles.drawer,
+ dynamicStyles.width(width),
+ isStart && styles.drawerStart,
+ isStart && isOpen && styles.drawerStartOpen,
+ !isStart && styles.drawerEnd,
+ !isStart && isOpen && styles.drawerEndOpen,
+ )}>
+ {/* Header — content + close button */}
+ <div
+ {...stylex.props(styles.header, !header && styles.headerNoTitle)}>
+ {typeof header === 'string' ? (
+ <Heading level={2} xstyle={styles.headerText}>
+ {header}
+ </Heading>
+ ) : (
+ (header ?? null)
+ )}
+ <Button
+ variant="ghost"
+ label={t('@astryx.mobileNav.closeNavigation')}
+ icon={<Icon icon="close" color="inherit" />}
+ onClick={() => onOpenChange(false)}
+ isIconOnly
+ />
+ </div>
+
+ {/* Scrollable content */}
+ <div {...stylex.props(styles.content)}>{children}</div>
</div>
-
- {/* Scrollable content */}
- <div {...stylex.props(styles.content)}>{children}</div>
- </div>
+ </LayerDepthProvider>
</dialog>
);
}
diff --git a/packages/core/src/Popover/usePopover.tsx b/packages/core/src/Popover/usePopover.tsx
index edfb95e54d..00ce13d9b0 100644
--- a/packages/core/src/Popover/usePopover.tsx
+++ b/packages/core/src/Popover/usePopover.tsx
@@ -19,6 +19,7 @@ import React, {useCallback, useEffect, useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {useLayer, type ContextRenderProps} from '../Layer/useLayer';
import {useFocusTrap} from '../hooks/useFocusTrap';
+import {LayerDepthProvider} from '../Layer/LayerDepthContext';
import type {StyleXStyles} from '@stylexjs/stylex';
import {
colorVars,
@@ -436,34 +437,36 @@ export function usePopover(options: UsePopoverOptions = {}): UsePopoverReturn {
: surfaceProps.className;
return layer.render(
- <div
- ref={contentRef}
- role={role === 'dialog' ? 'dialog' : undefined}
- aria-modal={role === 'dialog' && isModal ? true : undefined}
- aria-label={role === 'dialog' ? dialogLabel : undefined}
- {...mergeProps(
- {...surfaceProps, className: surfaceClassName},
- stylex.props(
- styles.contentWrapper,
- hasSurface && styles.surface,
- xstyle,
- ),
- )}>
- {children}
- {hasCloseButton && (
- <div
- {...stylex.props(
- styles.closeButtonWrapper,
- rtlStyles.centerInline('100%'),
- )}>
- <Button
- variant="secondary"
- label={closeButtonLabel}
- onClick={layer.hide}
- />
- </div>
- )}
- </div>,
+ <LayerDepthProvider>
+ <div
+ ref={contentRef}
+ role={role === 'dialog' ? 'dialog' : undefined}
+ aria-modal={role === 'dialog' && isModal ? true : undefined}
+ aria-label={role === 'dialog' ? dialogLabel : undefined}
+ {...mergeProps(
+ {...surfaceProps, className: surfaceClassName},
+ stylex.props(
+ styles.contentWrapper,
+ hasSurface && styles.surface,
+ xstyle,
+ ),
+ )}>
+ {children}
+ {hasCloseButton && (
+ <div
+ {...stylex.props(
+ styles.closeButtonWrapper,
+ rtlStyles.centerInline('100%'),
+ )}>
+ <Button
+ variant="secondary"
+ label={closeButtonLabel}
+ onClick={layer.hide}
+ />
+ </div>
+ )}
+ </div>
+ </LayerDepthProvider>,
{...props, xstyle: props?.xstyle},
);
},
diff --git a/packages/core/src/Tooltip/Tooltip.test.tsx b/packages/core/src/Tooltip/Tooltip.test.tsx
index 0ef60e9f2f..e380d926da 100644
--- a/packages/core/src/Tooltip/Tooltip.test.tsx
+++ b/packages/core/src/Tooltip/Tooltip.test.tsx
@@ -276,6 +276,38 @@ describe('Tooltip', () => {
expect(onOpenChange).not.toHaveBeenCalledWith(false);
});
});
+
+ describe('controlled', () => {
+ // Escape asks a controlled tooltip to close by calling this same handler,
+ // so a consumer who complies sees the request and then this echo. Pinning
+ // the echo here keeps the two straight.
+ it('echoes the close through onOpenChange when the consumer flips isOpen', async () => {
+ const onOpenChange = vi.fn();
+ const {rerender} = render(
+ <Tooltip content="Pinned" isOpen onOpenChange={onOpenChange} delay={0}>
+ <button type="button">Trigger</button>
+ </Tooltip>,
+ );
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+ onOpenChange.mockClear();
+
+ rerender(
+ <Tooltip
+ content="Pinned"
+ isOpen={false}
+ onOpenChange={onOpenChange}
+ delay={0}>
+ <button type="button">Trigger</button>
+ </Tooltip>,
+ );
+
+ await waitFor(() => {
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+ });
+ });
describe('touch', () => {
// The modality is document-global; a tap in one case must not decide the
// next one's answer.
diff --git a/packages/core/src/Tooltip/Tooltip.tsx b/packages/core/src/Tooltip/Tooltip.tsx
index 1243d875fb..5956864acf 100644
--- a/packages/core/src/Tooltip/Tooltip.tsx
+++ b/packages/core/src/Tooltip/Tooltip.tsx
@@ -146,6 +146,11 @@ export interface TooltipProps {
* - `true`: force-show the tooltip (hover/focus hide is suppressed)
* - `false`: force-hide the tooltip
* - `undefined`: uncontrolled — hover/focus triggers manage visibility
+ *
+ * A controlled tooltip still takes Escape when it is the top-most layer, and
+ * answers by calling `onOpenChange(false)` without hiding itself — closing is
+ * your update's decision, exactly as for a controlled Dialog. Ignore the call
+ * and the tip stays, and so does the press: nothing underneath dismisses.
*/
isOpen?: boolean;
diff --git a/packages/core/src/Tooltip/useTooltip.tsx b/packages/core/src/Tooltip/useTooltip.tsx
index 79e17725dc..72ef454d13 100644
--- a/packages/core/src/Tooltip/useTooltip.tsx
+++ b/packages/core/src/Tooltip/useTooltip.tsx
@@ -31,8 +31,8 @@ import {
type LayerTouchTrigger,
} from '../Layer/useTouchTrigger';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
+import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {themeProps} from '../utils/themeProps';
-import {isImeKeyEvent} from '../utils/ime';
import {
colorVars,
radiusVars,
@@ -144,6 +144,11 @@ export interface TooltipOptions {
* - `true`: force-show the tooltip (hover/focus hide is suppressed)
* - `false`: force-hide the tooltip
* - `undefined`: uncontrolled — hover/focus triggers manage visibility
+ *
+ * A controlled tooltip still takes Escape when it is the top-most layer, and
+ * answers by calling `onHide` without hiding itself — closing is your
+ * update's decision, exactly as for a controlled Dialog. Ignore the call and
+ * the tip stays, and so does the press: nothing underneath dismisses.
*/
isOpen?: boolean;
@@ -518,34 +523,52 @@ export function useTooltip(options: TooltipOptions = {}): TooltipReturn {
}
}, [isOpen, clearTimeouts, layer]);
- // Dismiss on Escape (WCAG 1.4.13 — dismissible). Uncontrolled tooltips only;
- // a controlled tooltip's visibility is owned by the consumer. The listener is
- // mounted for the lifetime of an uncontrolled tooltip rather than gated on
- // `layer.isOpen` (React state, which can lag a frame behind the DOM) —
- // `layer.hide()` self-guards and no-ops when the layer is already closed.
- // Guarded against IME composition-cancel.
- useEffect(() => {
- if (isOpen !== undefined) {
- return;
- }
- const handleKeyDown = (e: KeyboardEvent) => {
- if (e.key !== 'Escape') {
- return;
+ // Dismiss on Escape (WCAG 1.4.13 — dismissible) through the shared layer
+ // stack. A visible tip is the top-most layer, so it takes the press and
+ // consumes it: Escape hides the tip and leaves the dialog underneath open.
+ // The user presses Escape again to close that. Consuming (rather than also
+ // dismissing what is beneath) keeps one rule with no per-component
+ // exceptions, and the failure mode is one extra keystroke instead of a
+ // dialog closing under someone who only wanted the tip gone.
+ //
+ // A controlled tooltip stays on the stack and takes the press like any other
+ // layer, but answers it by reporting instead of hiding: `isOpen` is the
+ // consumer's value, so only their update may change it. Same contract as a
+ // controlled Dialog.
+ useLayerDismissal({
+ // Registered for the hook's lifetime rather than gated on `layer.isOpen`:
+ // that state can lag a frame behind the DOM, so a press arriving right after
+ // the layer appears would find nothing registered. Because this layer
+ // CONSUMES the press, a stale registration would be worse than a missed one
+ // — it would silently eat Escapes meant for the dialog underneath — so
+ // presence is answered from the DOM at press time instead of from state.
+ isActive: true,
+ isPresent: () => {
+ const el =
+ typeof document === 'undefined'
+ ? null
+ : document.getElementById(layer.id);
+ if (el == null) {
+ return false;
}
- if (isImeKeyEvent(e)) {
- // Ignore Escape that is committing/cancelling an IME composition;
- // see utils/ime.ts for why.
- return;
+ try {
+ return el.matches(':popover-open');
+ } catch {
+ // Browsers without the Popover API (and some test environments) cannot
+ // answer the selector; fall back to the hook's own state.
+ return layer.isOpen;
}
+ },
+ onDismiss: () => {
clearTimeouts();
clearTapOpen();
+ if (isOpen !== undefined) {
+ onHide?.();
+ return;
+ }
layer.hide();
- };
- document.addEventListener('keydown', handleKeyDown);
- return () => {
- document.removeEventListener('keydown', handleKeyDown);
- };
- }, [isOpen, layer, clearTimeouts, clearTapOpen]);
+ },
+ });
// Render function that wraps layer.render with tooltip styling
const renderTooltip = useCallback(
diff --git a/packages/core/src/hooks/useFocusTrap.ts b/packages/core/src/hooks/useFocusTrap.ts
index 07448ff743..9c6fe593d6 100644
--- a/packages/core/src/hooks/useFocusTrap.ts
+++ b/packages/core/src/hooks/useFocusTrap.ts
@@ -19,80 +19,26 @@
import {useCallback, useEffect, useRef} from 'react';
import {FOCUSABLE_SELECTOR} from './focusableSelector';
-import {isImeKeyEvent} from '../utils/ime';
+import {useLayerDismissal} from '../Layer/useLayerDismissal';
-/**
- * Module-level stack of active focus-trap Escape handlers.
- *
- * Every active `useFocusTrap` used to attach its own document-level `keydown`
- * listener with no coordination, so a single Escape press closed *every* open
- * layer at once (e.g. a popover nested inside a Dialog closed both). Tracking
- * traps in a shared stack lets only the top-most trap respond to Escape.
- *
- * "Top-most" is resolved by DOM containment first, push order second. Push
- * order alone is not reliable: React runs child effects before parent
- * effects, so when an outer and an inner (DOM-nested) trap mount in the SAME
- * commit, the inner trap pushes first and the outer trap would wrongly win a
- * pure last-pushed comparison.
- */
-interface EscapeStackEntry {
- handler: () => void;
- getContainer: () => HTMLElement | null;
-}
-
-const escapeStack: EscapeStackEntry[] = [];
-
-function pushEscapeHandler(entry: EscapeStackEntry): void {
- escapeStack.push(entry);
-}
-
-function removeEscapeHandler(handler: () => void): void {
- for (let i = escapeStack.length - 1; i >= 0; i--) {
- if (escapeStack[i].handler === handler) {
- escapeStack.splice(i, 1);
- return;
- }
- }
-}
-
-/**
- * Resolve the top-most trap: walk the stack in push order, keeping the
- * deepest container by DOM containment. When a later entry's container
- * contains the current candidate's container, the candidate is nested inside
- * it and stays on top; otherwise the later push wins (containment for nested
- * traps, push order as the tiebreaker for unrelated ones).
- */
-function isTopEscapeHandler(handler: () => void): boolean {
- if (escapeStack.length === 0) {
- return false;
- }
- let top = escapeStack[0];
- for (let i = 1; i < escapeStack.length; i++) {
- const entry = escapeStack[i];
- const topContainer = top.getContainer();
- const entryContainer = entry.getContainer();
- if (
- topContainer != null &&
- entryContainer != null &&
- entryContainer !== topContainer &&
- entryContainer.contains(topContainer)
- ) {
- // The current top is nested inside this entry — it stays on top.
- continue;
- }
- top = entry;
- }
- return top.handler === handler;
-}
+// Escape-dismissible focus traps currently mounted. This is the whole state
+// behind `hasActiveFocusTrapEscape`, which predates the shared stack and must
+// keep answering about focus traps alone — the stack now carries families that
+// never trapped focus (tooltips, hover cards), and counting those would tell
+// callers a trap is above them when none is.
+let activeEscapeTrapCount = 0;
/**
- * Whether any focus-trap Escape handler is currently active (i.e. a popover
- * layer is open). Other overlay primitives that manage their own Escape (e.g.
- * Dialog) can consult this to defer to a popover layered on top of them,
- * giving topmost-only dismissal until a full layer stack exists.
+ * Whether an Escape-dismissible focus trap is currently active — a Popover,
+ * menu or other trapped layer that would take an Escape press.
+ *
+ * @deprecated The focus trap no longer owns Escape coordination — every overlay
+ * family shares one stack (`useLayerDismissal`), which routes each press to
+ * the top-most layer. A layer that wants the same ordering should join the
+ * stack rather than ask whether a trap exists.
*/
export function hasActiveFocusTrapEscape(): boolean {
- return escapeStack.length > 0;
+ return activeEscapeTrapCount > 0;
}
/**
@@ -243,6 +189,38 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(
// Track if focus change was triggered by keyboard (Tab key)
const isKeyboardNavigationRef = useRef(false);
+ // Join the shared layer dismissal stack. The trap no longer listens for
+ // Escape itself: the stack owns one listener and routes each press to the
+ // top-most layer, so a popover inside a Dialog, a submenu inside a menu, and
+ // a modal inside a modal all peel off one at a time. A trap with no
+ // `onEscape` is not dismissible and stays off the stack, so a press flows
+ // past it to whatever is underneath.
+ // One expression drives both the stack registration and the deprecated
+ // `hasActiveFocusTrapEscape` count, so the two can never disagree about
+ // whether this trap is active.
+ const isEscapeTrap = isActive && onEscape != null;
+
+ useLayerDismissal({
+ isActive: isEscapeTrap,
+ onDismiss: () => {
+ onEscape?.();
+ },
+ // The trap renders nothing, so it cannot push a depth provider around its
+ // content; hand the stack the container instead so two DOM-nested traps
+ // still resolve in the right order.
+ getContainer: () => containerRef.current,
+ });
+
+ useEffect(() => {
+ if (!isEscapeTrap) {
+ return;
+ }
+ activeEscapeTrapCount += 1;
+ return () => {
+ activeEscapeTrapCount -= 1;
+ };
+ }, [isEscapeTrap]);
+
/**
* Focus the first focusable element.
*/
@@ -353,53 +331,25 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(
}, [isActive]);
/**
- * Handle Tab key to wrap focus at boundaries, and Escape to close.
- * Also tracks that keyboard navigation is occurring.
+ * Handle Tab key to wrap focus at boundaries. Also tracks that keyboard
+ * navigation is occurring.
+ *
+ * No Escape here, and no IME guard: the shared stack owns the press, claims
+ * a composing Escape so no close request follows, and dismisses the trap
+ * through `onEscape` above. The trap renders no element of its own, so it
+ * has no `cancel` to answer either.
*/
useEffect(() => {
if (!isActive) {
return;
}
- // Register this trap on the shared Escape stack so only the top-most
- // active trap responds to Escape. A stable identity per active period is
- // enough — we push on activate and remove on cleanup. The container is
- // read lazily: the ref may not be attached yet at effect time, and the
- // stack resolves top-most by DOM containment at keydown time.
- const escapeHandler = () => {
- onEscape?.();
- };
- if (onEscape) {
- pushEscapeHandler({
- handler: escapeHandler,
- getContainer: () => containerRef.current,
- });
- }
-
const handleKeyDown = (event: KeyboardEvent) => {
const container = containerRef.current;
if (!container) {
return;
}
- if (event.key === 'Escape' && onEscape) {
- // Ignore Escape that is cancelling an IME composition, already handled
- // by a nested handler, or not targeting the top-most trap.
- if (
- event.defaultPrevented ||
- isImeKeyEvent(event) ||
- !isTopEscapeHandler(escapeHandler)
- ) {
- return;
- }
- // Mark handled and stop propagation so an outer layer (e.g. a Dialog
- // hosting this popover) does not also dismiss on the same press.
- event.preventDefault();
- event.stopPropagation();
- onEscape();
- return;
- }
-
if (event.key === 'Tab') {
// Mark that keyboard navigation is happening
isKeyboardNavigationRef.current = true;
@@ -441,9 +391,6 @@ export function useFocusTrap<T extends HTMLElement = HTMLElement>(
return () => {
document.removeEventListener('keydown', handleKeyDown);
- if (onEscape) {
- removeEscapeHandler(escapeHandler);
- }
};
}, [isActive, onEscape]);
diff --git a/packages/core/src/hooks/useFocusTrapEscapeShim.test.tsx b/packages/core/src/hooks/useFocusTrapEscapeShim.test.tsx
new file mode 100644
index 0000000000..27624b41e9
--- /dev/null
+++ b/packages/core/src/hooks/useFocusTrapEscapeShim.test.tsx
@@ -0,0 +1,165 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useFocusTrapEscapeShim.test.tsx
+ * @input Uses vitest, @testing-library/react, useFocusTrap, Dialog, Lightbox,
+ * MobileNav, Tooltip, Popover
+ * @output Tests that hasActiveFocusTrapEscape still means what it meant in
+ * 0.4.2 — an Escape-dismissible FOCUS TRAP is active, not "a layer is open"
+ * @position Testing; guards the deprecated public shim in useFocusTrap.ts
+ *
+ * The shim is public API. Its answer must not change now that Escape moved to
+ * the shared stack: `BottomSheetSwitcher` gates its own dismissal on it, so a
+ * shim that also counts tooltips, hover cards and dialogs tells the sheet a
+ * trap is above it when none is, and the sheet stops closing.
+ *
+ * SYNC: When useFocusTrap.ts changes, update tests to match new behavior
+ */
+
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
+import {render} from '@testing-library/react';
+
+import {hasActiveFocusTrapEscape, useFocusTrap} from './useFocusTrap';
+import {Dialog} from '../Dialog/Dialog';
+import {Lightbox} from '../Lightbox/Lightbox';
+import {MobileNav} from '../MobileNav/MobileNav';
+import {Popover} from '../Popover/Popover';
+import {Tooltip} from '../Tooltip/Tooltip';
+import {resetLayerStackForTests} from '../Layer/layerStack';
+
+beforeEach(() => {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+});
+
+afterEach(() => {
+ resetLayerStackForTests();
+});
+
+function Trap({
+ isActive = true,
+ hasEscape = true,
+ children,
+}: {
+ isActive?: boolean;
+ hasEscape?: boolean;
+ children?: React.ReactNode;
+}) {
+ const {containerRef} = useFocusTrap<HTMLDivElement>({
+ isActive,
+ onEscape: hasEscape ? () => {} : undefined,
+ });
+ return <div ref={containerRef}>{children}</div>;
+}
+
+describe('hasActiveFocusTrapEscape', () => {
+ it('is false with nothing mounted', () => {
+ expect(hasActiveFocusTrapEscape()).toBe(false);
+ });
+
+ it('is true for an active trap with an Escape handler', () => {
+ render(<Trap />);
+ expect(hasActiveFocusTrapEscape()).toBe(true);
+ });
+
+ it('is false for a trap with no Escape handler', () => {
+ render(<Trap hasEscape={false} />);
+ expect(hasActiveFocusTrapEscape()).toBe(false);
+ });
+
+ it('is false for an inactive trap', () => {
+ render(<Trap isActive={false} />);
+ expect(hasActiveFocusTrapEscape()).toBe(false);
+ });
+
+ it('is true for nested traps, and false again once both unmount', () => {
+ const {unmount} = render(
+ <Trap>
+ <Trap />
+ </Trap>,
+ );
+ expect(hasActiveFocusTrapEscape()).toBe(true);
+ unmount();
+ expect(hasActiveFocusTrapEscape()).toBe(false);
+ });
+
+ it('is true for an open Popover, which traps focus', () => {
+ render(
+ <Popover
+ isOpen={true}
+ onOpenChange={() => {}}
+ content="Popover body"
+ label="Popover">
+ <button type="button">Open</button>
+ </Popover>,
+ );
+ expect(hasActiveFocusTrapEscape()).toBe(true);
+ });
+
+ // The families below are all on the shared dismissal stack and none of them
+ // traps focus. Answering `true` for these is what broke the bottom sheet.
+ it('is false for an open Dialog', () => {
+ render(
+ <Dialog isOpen={true} onOpenChange={() => {}} aria-label="Dialog">
+ Body
+ </Dialog>,
+ );
+ expect(hasActiveFocusTrapEscape()).toBe(false);
+ });
+
+ it('is false for an open Lightbox', () => {
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={{src: '/photo.jpg', alt: 'A photo'}}
+ />,
+ );
+ expect(hasActiveFocusTrapEscape()).toBe(false);
+ });
+
+ it('is false for an open MobileNav', () => {
+ render(
+ <MobileNav isOpen={true} onOpenChange={() => {}} label="Drawer">
+ <span>Nav</span>
+ </MobileNav>,
+ );
+ expect(hasActiveFocusTrapEscape()).toBe(false);
+ });
+
+ it('is false for a showing Tooltip', () => {
+ render(
+ <Tooltip content="Tip" isDefaultOpen={true}>
+ <button type="button">Trigger</button>
+ </Tooltip>,
+ );
+ expect(hasActiveFocusTrapEscape()).toBe(false);
+ });
+
+ it('is true for a Popover inside a Dialog, and false once the Popover closes', () => {
+ function Scene({isPopoverOpen}: {isPopoverOpen: boolean}) {
+ return (
+ <Dialog isOpen={true} onOpenChange={() => {}} aria-label="Dialog">
+ <Popover
+ isOpen={isPopoverOpen}
+ onOpenChange={() => {}}
+ content="Popover body"
+ label="Popover">
+ <button type="button">Open</button>
+ </Popover>
+ </Dialog>
+ );
+ }
+ const {rerender} = render(<Scene isPopoverOpen={true} />);
+ expect(hasActiveFocusTrapEscape()).toBe(true);
+
+ rerender(<Scene isPopoverOpen={false} />);
+ expect(hasActiveFocusTrapEscape()).toBe(false);
+ });
+});
diff --git a/packages/lab/src/InfoTip/InfoTip.tsx b/packages/lab/src/InfoTip/InfoTip.tsx
index f0feea5e1c..21163f609b 100644
--- a/packages/lab/src/InfoTip/InfoTip.tsx
+++ b/packages/lab/src/InfoTip/InfoTip.tsx
@@ -14,7 +14,7 @@
* - /packages/lab/src/InfoTip/index.ts (exports if types change)
*/
-import {useCallback, useRef, useState, type ReactNode} from 'react';
+import {type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {Icon, type IconSize} from '@astryxdesign/core/Icon';
@@ -103,33 +103,10 @@ export function InfoTip({
label = 'More information',
size = 'sm',
}: InfoTipProps): ReactNode {
- // Escape dismissal: `true` force-hides the tooltip (Tooltip isOpen={false});
- // `false` returns control to Tooltip's own hover/focus triggers (isOpen
- // undefined). Reset when the pointer or focus leaves the trigger so the
- // tooltip can re-open on the next hover/focus.
- const [isDismissed, setIsDismissed] = useState(false);
- const isOpenRef = useRef(false);
-
- const handleOpenChange = useCallback((isOpen: boolean) => {
- isOpenRef.current = isOpen;
- }, []);
-
- const handleKeyDown = useCallback(
- (event: React.KeyboardEvent<HTMLButtonElement>) => {
- if (event.key === 'Escape' && isOpenRef.current) {
- // Only swallow Escape when it actually dismissed the tooltip, so an
- // enclosing dialog still closes on the next press.
- event.stopPropagation();
- setIsDismissed(true);
- }
- },
- [],
- );
-
- const handleReset = useCallback(() => {
- setIsDismissed(false);
- }, []);
-
+ // No local Escape handler: the trigger used to stopPropagation the press,
+ // which hid the tip but left the browser's close watcher to fire `cancel` on
+ // an enclosing Dialog, so one press took both (#5168). Tooltip's own entry in
+ // the shared dismissal stack takes it instead.
return (
<Tooltip
content={content}
@@ -137,15 +114,10 @@ export function InfoTip({
// give the tap to the control and suppress the tooltip. Here the tooltip
// IS the control's only purpose, so the tap has to open it — otherwise
// an InfoTip's content is unreachable on a phone.
- touchTrigger="tap"
- isOpen={isDismissed ? false : undefined}
- onOpenChange={handleOpenChange}>
+ touchTrigger="tap">
<button
type="button"
aria-label={label}
- onKeyDown={handleKeyDown}
- onBlur={handleReset}
- onMouseLeave={handleReset}
{...stylex.props(focusOutlineStyles.focusVisible, styles.trigger)}>
<Icon icon="info" size={size} />
</button>