Skip to content

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

TypeScript

fix(Layer): a press inside a layer stops at the layer root in the React tree (#9497)

Cindy Zhang09a482eaf8ce
diff --git a/.changeset/layer-click-boundary.md b/.changeset/layer-click-boundary.md
new file mode 100644
index 0000000000..f485d10746
--- /dev/null
+++ b/.changeset/layer-click-boundary.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A press inside an open layer (a popover, tooltip, hover card, menu, dialog, drawer, lightbox, mobile navigation, bottom sheet or toast) no longer runs click, pointer, mouse or touch handlers on the elements around where the layer is written. Before, a click inside a menu written inside a clickable card or row could also activate that card or row. Handlers inside the layer, capture-phase handlers, and document and window listeners still receive the press. A handler that needs presses inside a layer belongs on the layer's content.
+
+`SelectableCard`: a click inside an open layer within the card (such as a popover's content) no longer toggles it. Until the next minor, the caller's `onClick` still receives that click, now during the capture phase, so before the layer's own handlers.
+
+@cixzhang
diff --git a/apps/storybook/stories/LayerDismissal.stories.tsx b/apps/storybook/stories/LayerDismissal.stories.tsx
index 172da11e87..745e347c23 100644
--- a/apps/storybook/stories/LayerDismissal.stories.tsx
+++ b/apps/storybook/stories/LayerDismissal.stories.tsx
@@ -16,6 +16,7 @@ import {useState} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
Button,
+ ClickableCard,
Dialog,
DialogHeader,
HoverCard,
@@ -25,6 +26,7 @@ import {
LayoutFooter,
Lightbox,
MobileNav,
+ MoreMenu,
Popover,
Text,
Tooltip,
@@ -1017,3 +1019,45 @@ function PinnedTooltipInModalExample() {
export const PinnedTooltipInModal: Story = {
render: () => <PinnedTooltipInModalExample />,
};
+
+/**
+ * A menu and a popover written inside a clickable card. A press inside either
+ * open layer stays in the layer: choosing "Rename" counts a menu choice, and a
+ * click on the popover's text does nothing, but neither activates the card
+ * around them. A click on the card's own text still activates it.
+ */
+function PressInsideLayerExample() {
+ const [cardActivations, setCardActivations] = useState(0);
+ const [menuChoices, setMenuChoices] = useState(0);
+ return (
+ <VStack gap={3}>
+ <ClickableCard
+ label="Project Atlas"
+ onClick={() => setCardActivations(count => count + 1)}>
+ <HStack gap={2}>
+ <Text type="body">Project Atlas</Text>
+ <MoreMenu
+ items={[
+ {
+ label: 'Rename',
+ onClick: () => setMenuChoices(count => count + 1),
+ },
+ ]}
+ />
+ <Popover
+ label="Details"
+ content={<Text type="body">Owned by the design team.</Text>}>
+ <Button label="Details" variant="secondary" />
+ </Popover>
+ </HStack>
+ </ClickableCard>
+ <Text type="body">
+ Card activations: {cardActivations} · Menu choices: {menuChoices}
+ </Text>
+ </VStack>
+ );
+}
+
+export const PressInsideLayer: Story = {
+ render: () => <PressInsideLayerExample />,
+};
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index 7541c038c5..c9d3cc537c 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -32,6 +32,7 @@ verified_by:
packages/core/src/Layer/layerHost.test.ts,
packages/core/src/Layer/anchorName.test.ts,
packages/core/src/Layer/useLayerDismissal.test.tsx,
+ packages/core/src/Layer/layerClickBoundary.test.tsx,
packages/core/src/Layer/layerDismissalInvariants.test.tsx,
packages/core/src/Popover/Popover.test.tsx,
packages/core/src/DropdownMenu/DropdownMenu.test.tsx,
@@ -572,19 +573,24 @@ keeps a document's sheets in open order, a step dialog's modal present, and
the non-modal sheet's popover host — alongside its scrim; the ordering rules
above are the stack's, the mounting under them is this gap's.
-INV17 is not met yet. Implementation gap: not built. A press inside a layer
-still propagates through the React tree to the ancestors of the layer's JSX
-position; only Tooltip and HoverCard surfaces are guarded, and only against
-the Core containers that check them (`component:Tooltip` FR11,
-`component:HoverCard` FR11). Compatibility: the owner ruled on 2026-11-01
-that closing the gap ships as a patch `[fix]` (`spec:AST-017` FR5's fix
-class) for every caller no released record covered: no record promised that
-a press inside a layer reaches the layer's JSX ancestors, and a handler that
-needs those presses belongs on the layer content. The one released promise is
+INV17 is met through one seam, `Layer/layerClickBoundary.ts`, which every
+listed root spreads; BottomSheetPanel's root is the BottomSheet dialog that
+hosts it, so a BottomSheetSwitcher's forwarded handlers there still receive
+presses on sheet content (`component:BottomSheetSwitcher` FR9); Dialog's
+inline rendering mode layers nothing and is not a layer root. The per-component Tooltip and HoverCard guards
+(`component:Tooltip` FR11, `component:HoverCard` FR11) remain beside it until
+they are removed. Compatibility: the owner ruled on 2026-11-01 that the
+boundary ships as a patch `[fix]` (`spec:AST-017` FR5's fix class) for every
+caller no released record covered: no record promised that a press inside a
+layer reaches the layer's JSX ancestors, and a handler that needs those presses
+belongs on the layer content. The one released promise is
`component:SelectableCard` FR2, whose caller `onClick` also runs for clicks
that do not toggle, including a click inside an open Tooltip or HoverCard
-surface; SelectableCard keeps that until the next minor, where the change is
-staged as `[breaking]` (`spec:AST-017` FR32).
+surface. Until the next minor, SelectableCard keeps it by calling the caller's
+`onClick` from a capture-phase handler on the card root for a click that starts
+inside a layer within the card, so before the layer's own handlers; the change
+is staged as `[breaking]` (`spec:AST-017` FR32) and `component:SelectableCard`
+`CLN-0026` removes that handler.
## Change coupling
@@ -635,6 +641,9 @@ staged as `[breaking]` (`spec:AST-017` FR32).
transitions of a layer and its content across the re-placement's display
reset.
- `Layer/gestureCounter.ts` owns physical pointer/key gesture identity.
+- `Layer/layerClickBoundary.ts` owns the INV17 seam: the React-tree stop every
+ layer content root spreads, with the layer-root mark that
+ `privateAttributes/layerRoot.stylex.ts` owns.
- One shared seam in the layer runtime owns INV17's stop on every layer content
root. It stops propagation through the React tree only. React's
`stopPropagation()` also stops the native event in React 19, which would
diff --git a/docs/specs/components/SelectableCard/SelectableCard.spec.md b/docs/specs/components/SelectableCard/SelectableCard.spec.md
index b478000abe..ea4e1ccfbf 100644
--- a/docs/specs/components/SelectableCard/SelectableCard.spec.md
+++ b/docs/specs/components/SelectableCard/SelectableCard.spec.md
@@ -61,10 +61,12 @@ toggling, and the selection ring; the caller owns the selection state.
- Released default preserved: `yes` until the next minor; then `no` for the
caller `onClick` (FR2)
- Compatibility class: no public prop, default, DOM, or styling output
- changes; one behavior change staged as `[breaking]` for the next minor:
- a click inside an open layer inside the card (e.g. a Tooltip or HoverCard
- surface) stops at the layer root and no longer reaches the caller's
- `onClick` (`architecture:layer-runtime` INV17). Not built.
+ changes; one behavior change staged as `[breaking]` for the next minor
+ (`CLN-0026`): a click inside an open layer inside the card (e.g. a Tooltip
+ or HoverCard surface) stops at the layer root and no longer reaches the
+ caller's `onClick` (`architecture:layer-runtime` INV17). Until then the
+ caller's `onClick` still runs for those clicks, during capture, so before
+ the layer's own handlers.
- Controlled/uncontrolled behavior: controlled only; `isSelected` and
`onChange` are required
- Migration decision: at the next minor, a caller `onClick` handler that
@@ -72,14 +74,29 @@ toggling, and the selection ring; the caller owns the selection state.
Consumer migration instructions belong in consumer docs and release notes.
+### CLN-0026 — A click inside an open layer no longer reaches SelectableCard's `onClick`
+
+| Field | Value |
+| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| id | `CLN-0026` |
+| lifecycle | No deprecation: the staged `[breaking]` change for FR2 (`architecture:layer-runtime` INV17) |
+| delta | Remove the card root's capture-phase handler that calls the caller's `onClick` for a click that starts inside an open layer within the card; that click then stops at the layer root |
+| rollback | Restore the capture-phase handler from the final-patch baseline |
+| state | `pending` — lands in a declared minor with its `[breaking]` Changeset |
+
## Current-state impact
- **Caller `onClick` still receives clicks inside an open layer (FR2).** A
- click inside an open Tooltip or HoverCard surface inside the card reaches
- the caller's `onClick`. At the next minor, staged as `[breaking]`, that
- click stops at the layer root (`architecture:layer-runtime` INV17) and
- callers move a handler that needs those presses to the layer content. Not
- built.
+ click inside an open layer inside the card (a Tooltip or HoverCard surface)
+ reaches the caller's `onClick` from a capture-phase handler on the card
+ root, so before the layer's own handlers, because the layer boundary
+ (`architecture:layer-runtime` INV17) stops it before the bubble phase; its
+ `stopPropagation()` does not keep the press from the layer, its
+ `preventDefault()` cancels only the browser's default and not the controls
+ inside the layer, and a popover the caller writes without a layer root is
+ not a layer. It does not toggle. At the next minor, staged as `[breaking]` (`CLN-0026`),
+ that handler is removed and callers move a handler that needs those presses
+ to the layer content.
- **Two focus indicators on nested controls (FR4, AR2).** The card draws its
outline whenever any descendant has `:focus-visible`, so focusing a nested
control shows the card outline and the control's own, where
diff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsx
index 2547976f52..ee2de4b787 100644
--- a/packages/core/src/BottomSheet/BottomSheet.tsx
+++ b/packages/core/src/BottomSheet/BottomSheet.tsx
@@ -150,6 +150,7 @@ import {
export type {BottomSheetHeight, BottomSheetSnapPoint} from './BottomSheetPanel';
import type {BottomSheetHeight, BottomSheetSnapPoint} from './BottomSheetPanel';
import {BottomSheetEscapeContext} from './bottomSheetEscape';
+import {layerClickBoundary} from '../Layer/layerClickBoundary';
const styles = stylex.create({
dialog: {
@@ -845,7 +846,9 @@ function StandaloneBottomSheet({
hasScrim && stackView.depth > 0 ? stackView.depth : undefined
}
onCancel={handleCancel}
- onClick={handleClick}>
+ // Presses inside the sheet do not reach handlers around where it is
+ // written. The dialog, not the panel, is the root, as in a switcher.
+ {...layerClickBoundary({onClick: handleClick})}>
<BottomSheetPanel
{...props}
ref={ref}
@@ -1179,8 +1182,14 @@ function SwitcherBottomSheetItem({
}
role={purpose === 'required' ? 'alertdialog' : switcherDialogProps.role}
onCancel={onDialogCancel}
- onClick={onDialogClick}
- onKeyDown={onDialogKeyDown}>
+ onKeyDown={onDialogKeyDown}
+ // Presses inside the sheet do not reach handlers around where it is
+ // written. The step's dialog, not the panel, is the root, because the
+ // switcher's handlers sit here and must still run.
+ {...layerClickBoundary({
+ ...switcherDialogProps,
+ onClick: onDialogClick,
+ })}>
<div
{...stylex.props(
styles.positioner,
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index a0839b346d..6e46c4a8e1 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -49,6 +49,7 @@ import {useScrollLock} from '../hooks/useScrollLock';
import {layerTextReset} from '../Layer/layerTextReset.stylex';
import {layerStructureReset} from '../Layer/layerStructureReset.stylex';
import {LayerContentBoundary} from '../Layer/layerScopedContext';
+import {layerClickBoundary} from '../Layer/layerClickBoundary';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
import {useModalOutlet} from '../Layer/modalOutlet';
@@ -849,7 +850,12 @@ export function Dialog({
className,
style,
)}
- onClick={chainEventHandlers(handleClick, onClickProp)}
+ // Presses inside the dialog do not reach handlers around where it is
+ // written.
+ {...layerClickBoundary({
+ ...safeProps,
+ onClick: chainEventHandlers(handleClick, onClickProp),
+ })}
onCancel={handleCancel}
aria-modal={isHydrating ? undefined : 'true'}
// The default aria-labelledby (from a DialogHeader title) is set
diff --git a/packages/core/src/Drawer/Drawer.tsx b/packages/core/src/Drawer/Drawer.tsx
index 8ad2660408..984cb93495 100644
--- a/packages/core/src/Drawer/Drawer.tsx
+++ b/packages/core/src/Drawer/Drawer.tsx
@@ -77,6 +77,7 @@ import {LayerDepthProvider, useLayerDismissal} from '../Layer';
import {layerTextReset} from '../Layer/layerTextReset.stylex';
import {layerStructureReset} from '../Layer/layerStructureReset.stylex';
import {LayerContentBoundary} from '../Layer/layerScopedContext';
+import {layerClickBoundary} from '../Layer/layerClickBoundary';
import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
import {composeEventHandlers, mergeProps, themeProps} from '../utils';
import {container, overlayPaddingReset} from '../Layout';
@@ -601,7 +602,12 @@ export function Drawer({
{...(purpose === 'required' && hasScrim
? {role: 'alertdialog'}
: undefined)}
- onClick={composeEventHandlers(onClickProp, handleClick)}
+ // Presses inside the drawer do not reach handlers around where it is
+ // written.
+ {...layerClickBoundary({
+ ...safeProps,
+ onClick: composeEventHandlers(onClickProp, handleClick),
+ })}
onKeyDown={onKeyDownProp}
onCancel={handleCancel}>
<ModalAnnounceProvider dialogRef={dialogRef} isOpen={isOpen && hasScrim}>
diff --git a/packages/core/src/Layer/layerClickBoundary.test.tsx b/packages/core/src/Layer/layerClickBoundary.test.tsx
new file mode 100644
index 0000000000..9c8d60208f
--- /dev/null
+++ b/packages/core/src/Layer/layerClickBoundary.test.tsx
@@ -0,0 +1,492 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file layerClickBoundary.test.tsx
+ * @input Uses React Testing Library, every layer root (Popover, Dialog, Drawer,
+ * Lightbox, MobileNav, BottomSheet, ToastViewport), ClickableCard,
+ * ContextMenu, BaseTypeahead, SelectableCard, Tooltip and
+ * useKeepLayerOpenProps
+ * @output A press inside a layer stops at the layer root in the React tree,
+ * and the native press still reaches document listeners (ContextMenu's
+ * outside mousedown, Typeahead's deferred click, the keep-open pointerup);
+ * SelectableCard's compatibility path until the next minor.
+ */
+
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@testing-library/react';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {useEffect, type ReactNode} from 'react';
+import {Popover} from '../Popover/Popover';
+import {Dialog} from '../Dialog/Dialog';
+import {Drawer} from '../Drawer/Drawer';
+import {Lightbox} from '../Lightbox/Lightbox';
+import {MobileNav} from '../MobileNav/MobileNav';
+import {BottomSheet} from '../BottomSheet/BottomSheet';
+import {BottomSheetSwitcher} from '../BottomSheet/BottomSheetSwitcher';
+import {ToastViewport} from '../Toast/ToastViewport';
+import {useToast} from '../Toast/useToast';
+import {ClickableCard} from '../ClickableCard/ClickableCard';
+import {ContextMenu} from '../ContextMenu/ContextMenu';
+import {BaseTypeahead} from '../Typeahead/BaseTypeahead';
+import {SelectableCard} from '../SelectableCard/SelectableCard';
+import {Tooltip} from '../Tooltip/Tooltip';
+import {Button} from '../Button/Button';
+import {useKeepLayerOpenProps} from './useLayer';
+import type {SearchSource, SearchableItem} from '../Typeahead/types';
+
+function press(target: Element) {
+ fireEvent.pointerDown(target);
+ fireEvent.mouseDown(target);
+ fireEvent.pointerUp(target);
+ fireEvent.mouseUp(target);
+ fireEvent.click(target);
+}
+
+describe('layer click boundary (layer-runtime INV17)', () => {
+ it('stops a press inside a popover at its root, after the handlers inside ran', () => {
+ const inner = vi.fn();
+ const ancestor = {
+ click: vi.fn(),
+ pointerDown: vi.fn(),
+ mouseDown: vi.fn(),
+ clickCapture: vi.fn(),
+ };
+ const documentClick = vi.fn();
+ document.addEventListener('click', documentClick);
+ try {
+ render(
+ <div
+ onClick={ancestor.click}
+ onPointerDown={ancestor.pointerDown}
+ onMouseDown={ancestor.mouseDown}
+ onClickCapture={ancestor.clickCapture}>
+ <Popover
+ isOpen
+ label="Details"
+ content={
+ <button type="button" onClick={inner}>
+ Inside
+ </button>
+ }>
+ <button type="button">Trigger</button>
+ </Popover>
+ </div>,
+ );
+ press(screen.getByRole('button', {name: 'Inside', hidden: true}));
+
+ expect(inner).toHaveBeenCalledTimes(1);
+ expect(ancestor.click).not.toHaveBeenCalled();
+ expect(ancestor.pointerDown).not.toHaveBeenCalled();
+ expect(ancestor.mouseDown).not.toHaveBeenCalled();
+ // Capture-phase ancestors run before the stop.
+ expect(ancestor.clickCapture).toHaveBeenCalledTimes(1);
+ // The native press is not stopped.
+ expect(documentClick).toHaveBeenCalledTimes(1);
+
+ // Positive control: a press outside the layer still reaches the
+ // ancestor.
+ press(screen.getByRole('button', {name: 'Trigger'}));
+ expect(ancestor.click).toHaveBeenCalled();
+ } finally {
+ document.removeEventListener('click', documentClick);
+ }
+ });
+
+ it('stops a press inside a nested layer at its own root', () => {
+ const outerContent = vi.fn();
+ render(
+ <Popover
+ isOpen
+ label="Outer"
+ content={
+ <div onClick={outerContent}>
+ <Popover isOpen label="Inner" content={<span>Inner text</span>}>
+ <button type="button">Inner trigger</button>
+ </Popover>
+ </div>
+ }>
+ <button type="button">Outer trigger</button>
+ </Popover>,
+ );
+ press(screen.getByText('Inner text'));
+ expect(outerContent).not.toHaveBeenCalled();
+ });
+
+ describe('every kind of layer root', () => {
+ const {showModal, close} = HTMLDialogElement.prototype;
+ beforeEach(() => {
+ HTMLDialogElement.prototype.showModal = function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ };
+ HTMLDialogElement.prototype.close = function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ };
+ });
+ afterEach(() => {
+ // Unmount while the stubs still exist: closing calls dialog.close().
+ cleanup();
+ HTMLDialogElement.prototype.showModal = showModal;
+ HTMLDialogElement.prototype.close = close;
+ });
+
+ function ShowToast() {
+ const toast = useToast();
+ useEffect(() => {
+ toast({body: 'Root text', isAutoHide: false});
+ }, [toast]);
+ return null;
+ }
+
+ const roots: [string, () => ReactNode][] = [
+ [
+ 'an inline useLayer layer',
+ () => (
+ <Popover isOpen label="Details" content={<span>Root text</span>}>
+ <button type="button">Trigger</button>
+ </Popover>
+ ),
+ ],
+ [
+ 'a portaled useLayer layer',
+ () => (
+ <ul>
+ <li>
+ <Popover isOpen label="Details" content={<span>Root text</span>}>
+ <button type="button">Trigger</button>
+ </Popover>
+ </li>
+ </ul>
+ ),
+ ],
+ [
+ 'Dialog',
+ () => (
+ <Dialog isOpen onOpenChange={() => {}}>
+ <p>Root text</p>
+ </Dialog>
+ ),
+ ],
+ [
+ 'Drawer',
+ () => (
+ <Drawer isOpen onOpenChange={() => {}} label="Details">
+ Root text
+ </Drawer>
+ ),
+ ],
+ [
+ 'Lightbox',
+ () => (
+ <Lightbox
+ isOpen
+ onOpenChange={() => {}}
+ media={[{src: '/photo.jpg', alt: 'Root text'}]}
+ />
+ ),
+ ],
+ [
+ 'MobileNav',
+ () => (
+ <MobileNav isOpen onOpenChange={() => {}}>
+ <span>Root text</span>
+ </MobileNav>
+ ),
+ ],
+ [
+ 'BottomSheetPanel',
+ () => (
+ <BottomSheet isOpen onOpenChange={() => {}} label="Filters">
+ Root text
+ </BottomSheet>
+ ),
+ ],
+ [
+ 'ToastViewport',
+ () => (
+ <ToastViewport isTopLayer={false}>
+ <ShowToast />
+ </ToastViewport>
+ ),
+ ],
+ ];
+
+ const target = () =>
+ screen.queryByText('Root text') ?? screen.getByAltText('Root text');
+
+ it.each(roots)(
+ 'a press inside %s reaches no plain wrapper bubble handler',
+ async (_name, renderRoot) => {
+ const wrapper = {
+ click: vi.fn(),
+ pointerDown: vi.fn(),
+ gotCapture: vi.fn(),
+ lostCapture: vi.fn(),
+ };
+ render(
+ <div
+ onClick={wrapper.click}
+ onPointerDown={wrapper.pointerDown}
+ onGotPointerCapture={wrapper.gotCapture}
+ onLostPointerCapture={wrapper.lostCapture}>
+ {renderRoot()}
+ </div>,
+ );
+ await waitFor(() => expect(target()).toBeInTheDocument());
+ press(target());
+ // A drag handle or slider inside the layer taking and releasing
+ // pointer capture.
+ fireEvent(target(), new Event('gotpointercapture', {bubbles: true}));
+ fireEvent(target(), new Event('lostpointercapture', {bubbles: true}));
+ expect(wrapper.click).not.toHaveBeenCalled();
+ expect(wrapper.pointerDown).not.toHaveBeenCalled();
+ expect(wrapper.gotCapture).not.toHaveBeenCalled();
+ expect(wrapper.lostCapture).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(roots)(
+ 'a press inside %s does not activate a ClickableCard around it',
+ async (_name, renderRoot) => {
+ const onClick = vi.fn();
+ render(
+ <ClickableCard label="Card" onClick={onClick}>
+ {renderRoot()}
+ </ClickableCard>,
+ );
+ await waitFor(() => expect(target()).toBeInTheDocument());
+ press(target());
+ expect(onClick).not.toHaveBeenCalled();
+ },
+ );
+
+ it("a BottomSheetSwitcher's forwarded handlers still receive presses on sheet content", () => {
+ const switcher = {click: vi.fn(), pointerDown: vi.fn()};
+ const wrapperClick = vi.fn();
+ render(
+ <div onClick={wrapperClick}>
+ <BottomSheetSwitcher
+ activeSheet="details"
+ onActiveSheetChange={() => {}}
+ onClick={switcher.click}
+ onPointerDown={switcher.pointerDown}>
+ <BottomSheet sheetId="details" label="Details">
+ Step text
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ </div>,
+ );
+ press(screen.getByText('Step text'));
+ // The switcher forwards these to the step's dialog.
+ expect(switcher.click).toHaveBeenCalledTimes(1);
+ expect(switcher.pointerDown).toHaveBeenCalledTimes(1);
+ expect(wrapperClick).not.toHaveBeenCalled();
+ });
+
+ it("runs the root's own onClick before the stop (Dialog)", () => {
+ const ancestorClick = vi.fn();
+ const dialogClick = vi.fn();
+ render(
+ <div onClick={ancestorClick}>
+ <Dialog isOpen onOpenChange={() => {}} onClick={dialogClick}>
+ <p>Dialog text</p>
+ </Dialog>
+ </div>,
+ );
+ press(screen.getByText('Dialog text'));
+ expect(dialogClick).toHaveBeenCalledTimes(1);
+ expect(ancestorClick).not.toHaveBeenCalled();
+ });
+ });
+});
+
+describe('document listeners still receive presses inside a layer', () => {
+ it("ContextMenu's outside mousedown closes it for a press inside an open popover", () => {
+ const onOpenChange = vi.fn<(isOpen: boolean) => void>();
+ render(
+ <>
+ <ContextMenu items={[{label: 'Cut'}]} onOpenChange={onOpenChange}>
+ <div>Right-click me</div>
+ </ContextMenu>
+ <Popover isOpen label="Details" content={<span>Popover text</span>}>
+ <button type="button">Trigger</button>
+ </Popover>
+ </>,
+ );
+ fireEvent.contextMenu(screen.getByText('Right-click me'));
+ expect(onOpenChange).toHaveBeenLastCalledWith(true);
+ fireEvent.pointerDown(screen.getByText('Popover text'), {
+ pointerType: 'mouse',
+ pointerId: 7,
+ });
+ fireEvent.mouseDown(screen.getByText('Popover text'));
+ expect(onOpenChange).toHaveBeenLastCalledWith(false);
+ });
+
+ it('a Typeahead inside a popover opens its list on the deferred document click', async () => {
+ const fruits: SearchableItem[] = [
+ {id: 'apple', label: 'Apple'},
+ {id: 'banana', label: 'Banana'},
+ ];
+ const source: SearchSource = {
+ bootstrap: () => fruits,
+ search: query =>
+ fruits.filter(item => item.label.toLowerCase().includes(query)),
+ };
+ render(
+ <Popover
+ isOpen
+ label="Filters"
+ content={
+ <BaseTypeahead
+ searchSource={source}
+ value={null}
+ onChange={() => {}}
+ hasEntriesOnFocus
+ debounceMs={0}
+ />
+ }>
+ <button type="button">Trigger</button>
+ </Popover>,
+ );
+ const input = screen.getByRole('combobox', {hidden: true});
+ // The press focuses the input; the list's show waits for the press's
+ // click on the document, then a frame.
+ fireEvent.pointerDown(input);
+ act(() => {
+ input.focus();
+ });
+ fireEvent.pointerUp(input);
+ fireEvent.click(input);
+ await waitFor(() => {
+ expect(input).toHaveAttribute('aria-expanded', 'true');
+ });
+ });
+
+ it('a keep-open control inside a popover releases its invoker on the document pointerup', async () => {
+ function KeepOpen() {
+ const props = useKeepLayerOpenProps('some-layer', true);
+ return (
+ <button type="button" {...props}>
+ Keep open
+ </button>
+ );
+ }
+ render(
+ <Popover isOpen label="Details" content={<KeepOpen />}>
+ <button type="button">Trigger</button>
+ </Popover>,
+ );
+ const control = screen.getByRole('button', {
+ name: 'Keep open',
+ hidden: true,
+ });
+ fireEvent.pointerDown(control);
+ expect(control).toHaveAttribute('popovertarget', 'some-layer');
+ fireEvent.pointerUp(control);
+ await waitFor(() => {
+ expect(control).not.toHaveAttribute('popovertarget');
+ });
+ });
+});
+
+// Until the next minor, the caller's onClick still runs for a click inside an
+// open layer within the card, during capture, and the card does not toggle.
+describe('SelectableCard compatibility until the next minor', () => {
+ it("still calls the caller's onClick for a click inside an open tooltip, without toggling", () => {
+ const onClick = vi.fn();
+ const onChange = vi.fn();
+ render(
+ <SelectableCard
+ label="Plan"
+ isSelected={false}
+ onChange={onChange}
+ onClick={onClick}>
+ <Tooltip content="Tooltip text" isOpen>
+ <span tabIndex={0}>Info</span>
+ </Tooltip>
+ <span>Card body</span>
+ </SelectableCard>,
+ );
+ fireEvent.click(screen.getByText('Tooltip text'));
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(onChange).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByText('Card body'));
+ expect(onChange).toHaveBeenCalledWith(true);
+ expect(onClick).toHaveBeenCalledTimes(2);
+ });
+
+ it('a caller onClick that stops propagation does not block a control inside the layer', () => {
+ const inside = vi.fn();
+ const onClick = vi.fn((event: {stopPropagation: () => void}) => {
+ event.stopPropagation();
+ });
+ render(
+ <SelectableCard
+ label="Plan"
+ isSelected={false}
+ onChange={() => {}}
+ onClick={onClick}>
+ <Popover
+ isOpen
+ label="Details"
+ content={
+ <button type="button" onClick={inside}>
+ Inside
+ </button>
+ }>
+ <button type="button">Trigger</button>
+ </Popover>
+ </SelectableCard>,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Inside', hidden: true}));
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(inside).toHaveBeenCalledTimes(1);
+ });
+
+ it("a caller onClick that prevents default does not cancel a Button's clickAction inside the layer, and the default stays cancelled", () => {
+ const clickAction = vi.fn();
+ render(
+ <SelectableCard
+ label="Plan"
+ isSelected={false}
+ onChange={() => {}}
+ onClick={event => event.preventDefault()}>
+ <Popover
+ isOpen
+ label="Details"
+ content={<Button label="Apply" clickAction={clickAction} />}>
+ <button type="button">Trigger</button>
+ </Popover>
+ </SelectableCard>,
+ );
+ const isNotCancelled = fireEvent.click(
+ screen.getByRole('button', {name: 'Apply', hidden: true}),
+ );
+ expect(clickAction).toHaveBeenCalledTimes(1);
+ expect(isNotCancelled).toBe(false);
+ });
+
+ it('calls onClick once for a click inside a caller-written popover, which is not a layer root', () => {
+ const onClick = vi.fn();
+ render(
+ <SelectableCard
+ label="Plan"
+ isSelected={false}
+ onChange={() => {}}
+ onClick={onClick}>
+ <div popover="manual">Own popover text</div>
+ </SelectableCard>,
+ );
+ fireEvent.click(screen.getByText('Own popover text'));
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/core/src/Layer/layerClickBoundary.ts b/packages/core/src/Layer/layerClickBoundary.ts
new file mode 100644
index 0000000000..ed32d2eacc
--- /dev/null
+++ b/packages/core/src/Layer/layerClickBoundary.ts
@@ -0,0 +1,97 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file layerClickBoundary.ts
+ * @input React pointer, mouse, touch and click events on a layer root
+ * @output Exports layerClickBoundary, the props every layer content root
+ * spreads, including the layer-root mark
+ * @position Internal to Layer; used by useLayer's renderers and the Dialog,
+ * Drawer, Lightbox, MobileNav, BottomSheetPanel and ToastViewport roots.
+ * Not exported from the package.
+ *
+ * A press that starts inside a layer runs the handlers inside the layer and
+ * the root's own, then stops propagating through the React tree, so no
+ * bubble-phase handler on an ancestor of the layer's JSX position receives it.
+ * Capture-phase handlers on those ancestors already ran. The stop is
+ * React-only: it marks the synthetic event stopped and never calls the
+ * native `stopPropagation()`, so document and window listeners (outside
+ * presses, light dismiss, deferred clicks) still receive the press.
+ */
+
+import type {SyntheticEvent} from 'react';
+import {layerRootProps} from '../privateAttributes/layerRoot.stylex';
+
+/** The React event props that stop at a layer root. */
+const BOUNDARY_EVENTS = [
+ 'onClick',
+ 'onAuxClick',
+ 'onDoubleClick',
+ 'onContextMenu',
+ 'onMouseDown',
+ 'onMouseUp',
+ 'onMouseMove',
+ 'onMouseOver',
+ 'onMouseOut',
+ 'onPointerDown',
+ 'onPointerUp',
+ 'onPointerMove',
+ 'onPointerOver',
+ 'onPointerOut',
+ 'onPointerCancel',
+ 'onGotPointerCapture',
+ 'onLostPointerCapture',
+ 'onTouchStart',
+ 'onTouchMove',
+ 'onTouchEnd',
+ 'onTouchCancel',
+] as const;
+
+type BoundaryEvent = (typeof BOUNDARY_EVENTS)[number];
+type Handler = (event: SyntheticEvent) => void;
+
+export type LayerClickBoundaryProps = Record<BoundaryEvent, Handler> &
+ Readonly<Record<`data-${string}`, string>>;
+
+const returnTrue = () => true;
+
+/**
+ * Stop a synthetic event at this element for the rest of the React tree only.
+ * React's dispatch asks `isPropagationStopped()` before each further
+ * listener; the native event is left alone.
+ */
+function stopInReactTree(event: SyntheticEvent): void {
+ event.isPropagationStopped = returnTrue;
+}
+
+/**
+ * The boundary props for a layer content root. Pass the root's own props
+ * (its caller's rest props and its own handlers): for each boundary event, a
+ * handler found there runs first, then the event stops. Spread the result
+ * after the root's other props.
+ *
+ * @param own - The root's props; only its boundary-event handlers are read.
+ * @returns One handler per boundary event, to spread on the root element.
+ */
+export function layerClickBoundary(
+ own: Readonly<Record<string, unknown>> = {},
+): LayerClickBoundaryProps {
+ const props: Partial<Record<BoundaryEvent, Handler>> = {};
+ for (const name of BOUNDARY_EVENTS) {
+ const handler = own[name];
+ props[name] =
+ typeof handler === 'function'
+ ? event => {
+ (handler as Handler)(event);
+ stopInReactTree(event);
+ }
+ : stopInReactTree;
+ }
+ return {
+ // Every boundary event is set by the loop above.
+ ...(props as Record<BoundaryEvent, Handler>),
+ // Marks the root, so code outside the layer can find where it starts.
+ ...layerRootProps,
+ };
+}
diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsx
index e14899af63..d25c2f73a8 100644
--- a/packages/core/src/Layer/useLayer.tsx
+++ b/packages/core/src/Layer/useLayer.tsx
@@ -29,6 +29,7 @@ import * as stylex from '@stylexjs/stylex';
import type {StyleXStyles} from '@stylexjs/stylex';
import {createPortal} from 'react-dom';
import {LayerContentBoundary} from './layerScopedContext';
+import {layerClickBoundary} from './layerClickBoundary';
import {addAnchorName, removeAnchorName} from './anchorName';
import {currentGesture, currentGestureHasClicked} from './gestureCounter';
import {resolveLayerPortalTarget} from './layerHost';
@@ -1909,7 +1910,10 @@ function useLayerImplementation(
...extraStyle,
}}
onMouseEnter={onMouseEnter}
- onMouseLeave={onMouseLeave}>
+ onMouseLeave={onMouseLeave}
+ // Presses inside the layer do not reach handlers around where it
+ // is written.
+ {...layerClickBoundary()}>
<LayerContentBoundary>{children}</LayerContentBoundary>
</Container>
);
@@ -1970,7 +1974,10 @@ function useLayerImplementation(
id={id}
popover={lightDismiss ? 'auto' : 'manual'}
className={combinedClassName}
- style={{...stylexResult.style, ...positionStyle, ...extraStyle}}>
+ style={{...stylexResult.style, ...positionStyle, ...extraStyle}}
+ // Presses inside the layer do not reach handlers around where it
+ // is written.
+ {...layerClickBoundary()}>
<LayerContentBoundary>{children}</LayerContentBoundary>
</div>
);
diff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsx
index 3f63993ae8..34ac76bcf4 100644
--- a/packages/core/src/Lightbox/Lightbox.tsx
+++ b/packages/core/src/Lightbox/Lightbox.tsx
@@ -41,6 +41,7 @@ import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {layerTextReset} from '../Layer/layerTextReset.stylex';
import {layerStructureReset} from '../Layer/layerStructureReset.stylex';
import {LayerContentBoundary} from '../Layer/layerScopedContext';
+import {layerClickBoundary} from '../Layer/layerClickBoundary';
import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
import {overlayPaddingReset} from '../Layout/padding.stylex';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
@@ -648,10 +649,6 @@ export function Lightbox({
<dialog
ref={mergedDialogRef}
onCancel={handleCancel}
- onClick={e => {
- handleBackdropClick(e);
- onClickProp?.(e);
- }}
onKeyDown={e => {
handleKeyDown(e);
onKeyDownProp?.(e);
@@ -669,7 +666,16 @@ export function Lightbox({
className,
style,
)}
- {...props}>
+ {...props}
+ // Presses inside the lightbox do not reach handlers around where it is
+ // written.
+ {...layerClickBoundary({
+ ...props,
+ onClick: (e: React.MouseEvent<HTMLDialogElement>) => {
+ handleBackdropClick(e);
+ onClickProp?.(e);
+ },
+ })}>
<LayerDepthProvider>
<ModalAnnounceProvider dialogRef={dialogRef} isOpen={isOpen}>
<LayerContentBoundary>
diff --git a/packages/core/src/MobileNav/MobileNav.tsx b/packages/core/src/MobileNav/MobileNav.tsx
index 20332be1a1..75bbdedf01 100644
--- a/packages/core/src/MobileNav/MobileNav.tsx
+++ b/packages/core/src/MobileNav/MobileNav.tsx
@@ -70,6 +70,7 @@ import {mergeProps, composeEventHandlers} from '../utils';
import {layerTextReset} from '../Layer/layerTextReset.stylex';
import {layerStructureReset} from '../Layer/layerStructureReset.stylex';
import {LayerContentBoundary} from '../Layer/layerScopedContext';
+import {layerClickBoundary} from '../Layer/layerClickBoundary';
import {overlayPaddingReset} from '../Layout/padding.stylex';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
@@ -712,7 +713,12 @@ export function MobileNav({
? header
: t('@astryx.mobileNav.navigation'))
}
- onClick={composeEventHandlers(onClickProp, handleDialogClick)}
+ // Presses inside the navigation do not reach handlers around where it
+ // is written.
+ {...layerClickBoundary({
+ ...rest,
+ onClick: composeEventHandlers(onClickProp, handleDialogClick),
+ })}
onCancel={handleCancel}>
<ModalAnnounceProvider dialogRef={dialogRef} isOpen={isOpen}>
<LayerDepthProvider>
diff --git a/packages/core/src/SelectableCard/SelectableCard.tsx b/packages/core/src/SelectableCard/SelectableCard.tsx
index 1d6dce18ee..4b68921405 100644
--- a/packages/core/src/SelectableCard/SelectableCard.tsx
+++ b/packages/core/src/SelectableCard/SelectableCard.tsx
@@ -44,6 +44,7 @@ import {mergeProps} from '../utils';
import {Card} from '../Card/Card';
import type {CardVariant} from '../Card/Card';
import {useClickableContainer} from '../hooks/useClickableContainer';
+import {closestLayerRoot} from '../privateAttributes/layerRoot.stylex';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
@@ -323,6 +324,44 @@ export interface SelectableCardProps extends Omit<BaseProps, 'onChange'> {
// Component
// =============================================================================
+/**
+ * Call a caller's click handler during capture, before the layer's own
+ * handlers, without letting it change what those handlers see. Its
+ * stopPropagation() would keep the press from the control inside the layer,
+ * so it does nothing here. Its preventDefault() would mark the event handled
+ * for those controls (a Button skips its clickAction), so it is applied to
+ * the native event only after the press has bubbled to the document, where it
+ * still cancels the browser's default action.
+ */
+function callBeforeLayerHandlers(
+ handler: (event: MouseEvent<HTMLElement>) => void,
+ event: MouseEvent<HTMLElement>,
+): void {
+ const {stopPropagation, preventDefault} = event;
+ let isDefaultPreventedByCaller = false;
+ event.stopPropagation = () => {};
+ event.preventDefault = () => {
+ isDefaultPreventedByCaller = true;
+ };
+ try {
+ handler(event);
+ } finally {
+ event.stopPropagation = stopPropagation;
+ event.preventDefault = preventDefault;
+ }
+ if (isDefaultPreventedByCaller) {
+ const nativeEvent = event.nativeEvent;
+ const doc = event.currentTarget.ownerDocument;
+ const cancelDefault = (bubbled: Event) => {
+ doc.removeEventListener(nativeEvent.type, cancelDefault);
+ if (bubbled === nativeEvent) {
+ nativeEvent.preventDefault();
+ }
+ };
+ doc.addEventListener(nativeEvent.type, cancelDefault);
+ }
+}
+
/**
* A card that toggles between selected and unselected states.
*
@@ -415,6 +454,24 @@ export function SelectableCard({
}
: onClick;
+ // Until the next minor, a click inside an open layer within the card still
+ // reaches the caller's onClick. The layer root stops that click before the
+ // bubble phase, so it is delivered here, during capture. It never toggles.
+ // Remove at the next minor, when that click stops reaching onClick.
+ const handleLayerClickCapture = onClickProp
+ ? (e: MouseEvent<HTMLElement>) => {
+ const target = e.target;
+ if (!(target instanceof Element)) {
+ return;
+ }
+ const layerRoot = closestLayerRoot(target);
+ if (layerRoot == null || layerRoot.contains(e.currentTarget)) {
+ return;
+ }
+ callBeforeLayerHandlers(onClickProp, e);
+ }
+ : undefined;
+
const composedOnMouseUp = onMouseUpProp
? (e: MouseEvent<HTMLElement>) => {
onMouseUp(e);
@@ -455,7 +512,15 @@ export function SelectableCard({
}
onClick={!isDisabled ? composedOnClick : undefined}
onMouseUp={!isDisabled ? composedOnMouseUp : undefined}
- {...props}>
+ {...props}
+ onClickCapture={
+ !isDisabled && handleLayerClickCapture
+ ? (e: MouseEvent<HTMLDivElement>) => {
+ handleLayerClickCapture(e);
+ props.onClickCapture?.(e);
+ }
+ : props.onClickCapture
+ }>
<input
ref={interactiveRef}
type="checkbox"
diff --git a/packages/core/src/Toast/ToastViewport.tsx b/packages/core/src/Toast/ToastViewport.tsx
index 22c15f4ee4..daf859aad4 100644
--- a/packages/core/src/Toast/ToastViewport.tsx
+++ b/packages/core/src/Toast/ToastViewport.tsx
@@ -33,6 +33,7 @@ import {useAnnounce} from '../hooks/useAnnounce';
import {layerTextReset} from '../Layer/layerTextReset.stylex';
import {layerStructureReset} from '../Layer/layerStructureReset.stylex';
import {LayerContentBoundary} from '../Layer/layerScopedContext';
+import {layerClickBoundary} from '../Layer/layerClickBoundary';
import {
getActiveModalOutlet,
subscribeModalOutlets,
@@ -823,7 +824,9 @@ export function ToastViewport({
{
style: Object.keys(insetStyle).length > 0 ? insetStyle : undefined,
},
- )}>
+ )}
+ // Presses on toasts do not reach handlers around the viewport.
+ {...layerClickBoundary()}>
<LayerContentBoundary>
{visibleToasts.map(entry => (
<ToastRow
diff --git a/packages/core/src/privateAttributes/layerRoot.stylex.ts b/packages/core/src/privateAttributes/layerRoot.stylex.ts
new file mode 100644
index 0000000000..b6d8f9cd40
--- /dev/null
+++ b/packages/core/src/privateAttributes/layerRoot.stylex.ts
@@ -0,0 +1,28 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file privateAttributes/layerRoot.stylex.ts
+ * @input A layer content root
+ * @output layerRootProps, which marks an element as a layer root, and
+ * closestLayerRoot, which finds the nearest marked root
+ * @position Owner module of the private layer-root attribute: the only
+ * file that writes its name. Layer's click boundary spreads the mark on
+ * every layer root; SelectableCard reads it for its compatibility path
+ * until the next minor. No package entry exports it.
+ */
+
+const LAYER_ROOT = 'data-astryx-layer-root';
+
+/** Spread on a layer content root. */
+export const layerRootProps: Readonly<Record<`data-${string}`, string>> = {
+ [LAYER_ROOT]: '',
+};
+
+/**
+ * The nearest layer root at or above `target`, or null outside every layer.
+ * Only marked roots count; an element that merely carries `popover` or is a
+ * `<dialog>` does not.
+ */
+export function closestLayerRoot(target: Element): Element | null {
+ return target.closest(`[${LAYER_ROOT}]`);
+}