An open source design system that's fully customizable and agent ready
TypeScript
fix(DropdownMenu): the press that opens the menu does not close it (#10689)
Christopher Chedeau71450dd2cbf5
diff --git a/.changeset/menu-opening-press-release.md b/.changeset/menu-opening-press-release.mdnew file mode 100644index 0000000000..78d5050ec8--- /dev/null+++ b/.changeset/menu-opening-press-release.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] DropdownMenu: a menu that a mouse press opens stays open when that press is released quickly away from the trigger, or after the trigger moved away under the pointer. Before, the browser's light dismiss read that release as a press outside and closed the menu at once. A press released after the settle time outside the menu still closes it, and a later press outside dismisses it.++@vjeuxdiff --git a/docs/specs/components/DropdownMenu/DropdownMenu.spec.md b/docs/specs/components/DropdownMenu/DropdownMenu.spec.mdindex d76ed47a82..d93a49e5e7 100644--- a/docs/specs/components/DropdownMenu/DropdownMenu.spec.md+++ b/docs/specs/components/DropdownMenu/DropdownMenu.spec.md@@ -353,6 +353,7 @@ than adding a DropdownMenu-owned heading target.| FR6 | `DropdownMenu.test.tsx` focus-return cases ("restores focus to the trigger after keyboard dismissal", "returns focus to the trigger after pointer dismissal without a focus ring", "leaves focus on the control a press outside landed on") and the "focus return after a pointer pick" and "a trigger the caller renders" cases | Keyboard and pointer close; Button and custom trigger | A lost focus return, a ring after a pointer close, no ring after a keyboard close, or focus pulled off a control pressed outside fails. | `audit:DropdownMenu/accessibility` || FR7 | `DropdownMenu.test.tsx` menuMaxHeight cases | A cap above 300px; viewport bound | A menu clipped to 300px under a raised cap, or one that escapes the viewport, fails. Evidence gap: no test asserts that the touch sheet ignores the cap. | `audit:DropdownMenu/layout` || FR8 | `DropdownMenu.test.tsx` press-model trigger cases ("a mouse press on the trigger opens the menu and a drag-release acts on the row under it", "the opening release before the settle time acts on nothing and the menu stays", "pressing the trigger of an open menu closes it and does not reopen it in the same gesture", "a held touch on the trigger opens with the finger down and a slide picks", "a tap on the trigger still opens through its click") | Mouse press-open; held finger; tap | A mouse that opens only on click, an opening release that acts early, or a re-open in the closing gesture fails. The held-touch case asserts the current 500 ms hold, the FR8 gap pending conformance. | `audit:DropdownMenu/behavior` |+| FR8 | `DropdownMenuOpeningRelease.interaction.browser.spec.ts` (Chromium, WebKit): an opening release off the trigger, under a trigger that moved away, or on the trigger after a show that waited leaves the menu open; a settled release outside closes it | Mouse release off the trigger | An opening release before the settle time that the browser's light dismiss closes fails | `audit:DropdownMenu/behavior` || FR9, AR1 | `DropdownMenu.test.tsx` custom trigger cases; `DropdownMenuSubMenu.test.tsx` "a menu hung off a custom trigger" cases | Custom trigger open, keyboard, mouse, disabled; both props given; Back row names | A custom trigger that does not open, toggle, or name the menu, a disabled one that opens, a missing warning, or a wrong Back row name fails. | `audit:DropdownMenu/accessibility` || FR10, AR2, ORD1 | `DropdownMenu.test.tsx` "DropdownMenuItem href" and "link rows — the browser's own clicks" cases | Plain, modified, middle, and right click; Enter; bottom sheet; disabled; blocked | A row that is not an anchor, a modified click that runs `onClick`, a middle click that does not close, a disabled row with an address, or a live blocked destination fails. Evidence gap: no test asserts the order of `onClick`, close, and navigation. | `audit:DropdownMenu/behavior` || FR11, AR3 | `DropdownMenuSubMenu.test.tsx` "drill-in on a phone" cases; `DropdownMenuDrillIn.a11y.chromium.spec.ts` | Phone and laptop; forced presentations; theme breakpoint; reset on close | A flyout on a phone, a drill-in on a laptop by default, a wrong name, a Back that loses focus, or a drilled view that survives a close fails. | `audit:DropdownMenu/accessibility` |@@ -385,6 +386,8 @@ than adding a DropdownMenu-owned heading target.- **Rich sheet heading for caller-rendered triggers (OQ2).** With`renderTrigger`, the bottom-sheet heading shows only the flattened text ofthe trigger's accessible name, and a trigger with no name gets no heading.+- **Deferred show.** When the menu's show waits for another popover operation,+ its opening release off the trigger closes it, against FR8.## Decision logdiff --git a/docs/specs/components/DropdownMenu/modules/useMenuPress.spec.md b/docs/specs/components/DropdownMenu/modules/useMenuPress.spec.mdindex d9fc16e787..0036c515ee 100644--- a/docs/specs/components/DropdownMenu/modules/useMenuPress.spec.md+++ b/docs/specs/components/DropdownMenu/modules/useMenuPress.spec.md@@ -245,10 +245,17 @@ lit row with the pressed overlay instead (AR1).visibility; this module reads them and adds no modality definition.- `architecture:layer-runtime` owns native light dismiss, which this moduleleaves in place: a press outside a `popover="auto"` menu still dismisses it- through the browser. Proposed FR8 holds the trigger as the popover's- invoker for the extent of a press-open so the release over the trigger is- not read as a dismissal, the same mechanism the layer runtime's keep-open- props use.+ through the browser. The press that opens the menu is claimed when its show is+ accepted at once (`component:DropdownMenu` FR8, `spec:AST-003` FR11–FR13).+ Wherever that press is released, the browser's light dismiss does not read the+ release as a dismissal, and the press model decides what it does. The trigger+ stays the popover's invoker for the extent of the press, the same mechanism+ the layer runtime's keep-open props use. Under a mouse, the trigger holds the+ pointer while the pointer is over it. The menu's layer holds it while the+ pointer is outside both. When the show waits for another popover operation,+ the press model no longer tracks that press, so only the invoker hold applies+ and a release off the trigger dismisses (a gap against+ `component:DropdownMenu` FR8).- `family:overlay-dismissal` owns Escape ordering; unchanged here.## Verification map@@ -262,6 +269,7 @@ lit row with the pressed overlay instead (AR1).| FR4 (scroll) | `MenuPress.a11y.chromium.spec.ts` (real Chromium) | Chromium touch pan in an overflowing menu; touch-action by overflow; finger slide and its stray click | Not provable in jsdom; a pan that acts on a row, or a slide that acts on the press row, fails || FR4 (pinch) | `MenuPinchZoom.a11y.chromium.spec.ts` (real Chromium, phone emulation) | two-finger pinch over a menu whose rows fit, over one that scrolls, and over a picker listbox | Not provable in jsdom; a pinch that leaves the page at scale 1, or acts on a row, fails || FR8 (proposed), FR9 | `menuPressGesture.test.ts` trigger states; `useMenuPress.test.tsx` trigger suite; `DropdownMenu.test.tsx` press-open cases | mouse opens at once, settle before/after, cancel; finger opening per `spec:AST-094` FR29; press-open + drag-release, unsettled release, trigger toggle, held touch, tap | A menu that does not open on a mouse press, an unsettled release that acts, or a trigger that reopens in the same gesture fails |+| FR8 (proposed) | `DropdownMenuOpeningRelease.interaction.browser.spec.ts`, Chromium and WebKit | opening release off the trigger, under a trigger that moved away, and after a show that waited; settled release outside | An unsettled opening release that the browser's light dismiss closes fails || FR10, FR11, AR5 | `DropdownMenuSubMenu.test.tsx` press cases and a real-browser finger case for the resting row; `useMenuPress.test.tsx` continuation suite plus a real-browser handoff case; open and close event counts for AR5 | a finger released on and resting on a sub-menu row; a continued finger, the distance from the first sample, a lift before it, a mouse; the menu's open and close each observed once | A sub-menu that opens on a resting finger, a continued finger that picks before the handoff, or an open withdrawn, or opened or closed twice, fails || ORD1a (proposed) | `DropdownMenuSubMenu.test.tsx` press cases; `SubMenuHeaderFooter.a11y.chromium.spec.ts` press-drag case | a mouse press on a menu row released on a row of a sub-menu rendered beside the menu; the same press released on that sub-menu's header field | A release on such a row that acts on nothing or closes the menu, or a release on its header field that acts, fails. |diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsxindex f7055f1d36..121de94761 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx@@ -39,6 +39,7 @@ import {COMPACT_TOUCH_PRESENTATION_QUERY} from '../hooks/useAdaptivePresentationimport {MENU_PRESS_LONG_PRESS_MS} from '../hooks/useMenuPress';import {MENU_PRESS_SETTLE_MS} from '../hooks/menuPressGesture';import {isInHeldLayer} from '../Layer/inputHold';+import {runPopoverOperation} from '../Layer/popoverOperations';import {TOUCH_QUERY} from '../utils/touchPresentation';import {UIKIT_GESTURES} from '../motion/uikit/gestures';@@ -3527,6 +3528,108 @@ describe('DropdownMenu press model', () => {}});+ describe('the press that opens the menu', () => {+ let captured: Element[] = [];++ beforeEach(() => {+ captured = [];+ HTMLElement.prototype.setPointerCapture = function (this: HTMLElement) {+ captured.push(this);+ };+ HTMLElement.prototype.hasPointerCapture = () => false;+ HTMLElement.prototype.releasePointerCapture = () => {};+ });++ afterEach(() => {+ fireEvent.pointerUp(document.body, mouse);+ delete (HTMLElement.prototype as Partial<HTMLElement>).setPointerCapture;+ delete (HTMLElement.prototype as Partial<HTMLElement>).hasPointerCapture;+ delete (HTMLElement.prototype as Partial<HTMLElement>)+ .releasePointerCapture;+ });++ const layerOfMenu = () =>+ screen.getByRole('menu', {hidden: true}).closest('[popover]');++ it('a mouse press on the trigger claims that press, the trigger keeps the pointer, and it is the invoker until the release', () => {+ vi.useFakeTimers();+ try {+ const trigger = renderMenu();+ fireEvent.pointerDown(trigger, mouse);+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ // The pointer is over the trigger, so its own pointerup and click+ // still reach it. The claim is the layer's, for a pointer outside.+ expect(layerOfMenu()).not.toBeNull();+ expect(captured).toEqual([trigger]);+ expect(trigger).toHaveAttribute('popovertarget');+ fireEvent.pointerUp(document.body, mouse);+ act(() => {+ vi.advanceTimersByTime(0);+ });+ expect(trigger).not.toHaveAttribute('popovertarget');+ } finally {+ vi.useRealTimers();+ }+ });++ it('a show that waits for another popover operation keeps the trigger as the invoker while the press is down, and claims nothing', async () => {+ const trigger = renderMenu();+ // The press lands inside another layer's show or hide, so the show+ // waits for that operation and replays after it. The press model has+ // ended that press, so a settled release outside must still close it.+ runPopoverOperation(document, () => {+ fireEvent.pointerDown(trigger, mouse);+ });+ await act(async () => {+ await Promise.resolve();+ });+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ expect(captured).toEqual([]);+ expect(trigger).toHaveAttribute('popovertarget');+ });++ it('a show replayed after the press ended claims nothing', async () => {+ const trigger = renderMenu();+ runPopoverOperation(document, () => {+ fireEvent.pointerDown(trigger, mouse);+ fireEvent.pointerUp(trigger, mouse);+ });+ await act(async () => {+ await Promise.resolve();+ });+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ expect(captured).toEqual([]);+ expect(trigger).not.toHaveAttribute('popovertarget');+ });++ it('a held finger’s open keeps the trigger as the invoker and claims nothing', () => {+ vi.useFakeTimers();+ try {+ const trigger = renderMenu();+ fireEvent.pointerDown(trigger, touch);+ act(() => {+ vi.advanceTimersByTime(500);+ });+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ expect(trigger).toHaveAttribute('popovertarget');+ expect(captured).toEqual([]);+ fireEvent.pointerUp(trigger, touch);+ } finally {+ vi.useRealTimers();+ }+ });++ it('a keyboard open neither holds the invoker nor claims a press', async () => {+ const user = userEvent.setup();+ const trigger = renderMenu();+ trigger.focus();+ await user.keyboard('{Enter}');+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ expect(trigger).not.toHaveAttribute('popovertarget');+ expect(captured).toEqual([]);+ });+ });+it('a tap on the trigger still opens through its click', () => {const trigger = renderMenu();fireEvent.pointerDown(trigger, touch);diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsxindex e6aefd7b1a..eb5f216f0e 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx@@ -49,6 +49,11 @@ import {readAccessibleName} from '../utils/accessibleName';import * as stylex from '@stylexjs/stylex';import {usePopover} from '../Popover/usePopover';import {holdEntranceInput} from '../Layer/holdEntranceInput';+import {+ claimPress,+ currentGesture,+ isPressInFlight,+} from '../Layer/gestureCounter';import {Button, type ButtonProps} from '../Button';import {Heading} from '../Heading';import {Icon} from '../Icon';@@ -963,6 +968,11 @@ function DropdownMenuPopover({// the list ref exists, and its release is kept for the close.const holdEntranceRef = useRef<() => void>(() => {});const releaseEntranceRef = useRef<(() => void) | null>(null);+ // The trigger press that asks the menu to open. The show holds the trigger+ // as the invoker through that press; that hold is set below, once the+ // popover exists.+ const openingPressRef = useRef<{gesture: number} | null>(null);+ const holdOpeningPressRef = useRef<() => void>(() => {});// Submenu flyouts are `popover="manual"` elements nested inside the menu's// `popover="auto"` element, so the browser's light dismiss of the menu never@@ -1070,6 +1080,7 @@ function DropdownMenuPopover({const handleLayerShow = useCallback(() => {acceptedOpenRef.current = true;+ holdOpeningPressRef.current();holdEntranceRef.current();resetFocusReturn();if (renderTrigger != null) {@@ -1385,6 +1396,25 @@ function DropdownMenuPopover({? controlledIsOpen === true: popover.isOpen;+ // The menu is `popover="auto"`. The browser's light dismiss reads a release+ // outside the popover as a dismissal, also the release of the press that+ // opened it. This holds for a mouse and for a finger after the long-press+ // delay, and also when the show waited for another popover operation. So+ // the trigger stays the popover's invoker through that press, as+ // useKeepLayerOpenProps does for controls beside an open layer.+ const holdOpeningPress = useCallback(() => {+ const press = openingPressRef.current;+ openingPressRef.current = null;+ if (+ press != null &&+ press.gesture === currentGesture() &&+ isPressInFlight()+ ) {+ holdInvokerThroughPress(buttonRef.current, popover.id);+ }+ }, [popover.id]);+ holdOpeningPressRef.current = holdOpeningPress;+// A mouse opens on press-down; a finger held on the trigger opens after// the long-press delay. Pressing the trigger of an open menu closes it, and// the click of that same gesture — reported by `isTriggerClickFromPress` —@@ -1411,20 +1441,29 @@ function DropdownMenuPopover({// popover the state a click-open already has: the trigger is where// Escape or a pick returns focus (the APG menu-button pattern).buttonRef.current?.focus({preventScroll: true});+ openingPressRef.current = {gesture: currentGesture()};const didOpen = openAndFocus('pointer', true);- if (didOpen) {- // The menu is `popover="auto"`: the browser's light dismiss would- // read the release of this very press, on the trigger outside the- // popover, as a dismissal — a mouse's release, and as much a- // finger's after the long-press delay opened the menu under it.- // Holding the invoker relationship through the press exempts the- // trigger, the way useKeepLayerOpenProps does for controls beside- // an open layer.- holdInvokerThroughPress(buttonRef.current, popover.id);+ // A mouse can release away from the trigger, or the trigger can move+ // away under it. So the layer claims a mouse's press, and that release+ // lands on the layer; over the trigger, the trigger keeps it. Only a+ // show accepted here claims it. After a show that waited, the press+ // model no longer tracks the press, and a settled release outside must+ // still close the menu.+ const layer = listRef.current?.closest('[popover]');+ if (didOpen && pointerType === 'mouse' && layer instanceof HTMLElement) {+ claimPress(layer, {releaseTarget: buttonRef.current});}return didOpen;},- [isMenuOpenNow, isControlled, onClick, onOpenChange, openAndFocus, popover],+ [+ isMenuOpenNow,+ isControlled,+ listRef,+ onClick,+ onOpenChange,+ openAndFocus,+ popover,+ ],);// The press model: the row under a release acts, the highlight follows adiff --git a/packages/core/src/DropdownMenu/__tests__/DropdownMenuOpeningRelease.interaction.browser.spec.ts b/packages/core/src/DropdownMenu/__tests__/DropdownMenuOpeningRelease.interaction.browser.spec.tsnew file mode 100644index 0000000000..95d1dacc3b--- /dev/null+++ b/packages/core/src/DropdownMenu/__tests__/DropdownMenuOpeningRelease.interaction.browser.spec.ts@@ -0,0 +1,425 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file DropdownMenuOpeningRelease.interaction.browser.spec.ts+ * @input The built Default and LabSelectableSizes DropdownMenu stories on a+ * desktop profile, with a real mouse in Chromium and WebKit+ * @output Proof that the release of the press that opens a menu does what the+ * press model decides. The browser's light dismiss does not undo it. A+ * release before the settle time leaves the menu open, also off the trigger+ * or after the trigger moved away. A settled release outside still closes+ * the menu, and a later press outside dismisses it. A plain click still+ * aims its pointerup and click at the trigger. After a show that waited+ * for another popover operation, a release on the trigger leaves the menu+ * open, and a settled release outside closes it. After the menu closes, the+ * page listens as it did at rest.+ * @position Evidence for useMenuPress FR8's opening release with native light+ * dismiss; the press model's own states are in menuPressGesture.test.ts+ */++import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ frames,+ openStory,+ withStorybook,+} from '@astryxdesign/interaction-harness';+import {MENU_PRESS_SETTLE_MS} from '../../hooks/menuPressGesture';++const storybook = withStorybook(test);++test.use({+ viewport: {width: 1280, height: 800},+ isMobile: false,+ hasTouch: false,+});++// A press this close to the settle time cannot be judged: the page's clock+// and the press model's clock can differ by this much.+const SETTLE_MARGIN_MS = 10;++/** The element's rendered box; a missing one fails the spec. */+async function boxOf(locator: Locator) {+ const box = await locator.boundingBox();+ if (box == null) {+ throw new Error('the element has no rendered box');+ }+ return box;+}++function centerOf(box: {x: number; y: number; width: number; height: number}) {+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};+}++// The press model times a press with `Date.now()` in its handlers. The page+// reads the same clock as the press starts and as it ends.+async function installPressClock(page: Page) {+ await page.evaluate(() => {+ const w = window as unknown as {__press: {down: number; up: number}};+ w.__press = {down: 0, up: 0};+ addEventListener(+ 'pointerdown',+ () => {+ w.__press = {down: Date.now(), up: 0};+ },+ true,+ );+ addEventListener(+ 'pointerup',+ () => {+ w.__press.up = Date.now();+ },+ true,+ );+ });+}++async function menuState(page: Page, trigger: Locator) {+ return {+ expanded: await trigger.getAttribute('aria-expanded'),+ open: await page.locator('[data-layer-anchored]:popover-open').count(),+ };+}++// The menu must be in the state the press model decides for this release.+// A release outside the menu before the settle time leaves it open; after+// the settle time it closes it.+async function expectModelOutcome(page: Page, trigger: Locator) {+ const {down, up} = await page.evaluate(+ () => (window as unknown as {__press: {down: number; up: number}}).__press,+ );+ expect(down, 'the press start was seen').toBeGreaterThan(0);+ expect(up, 'the press end was seen').toBeGreaterThan(0);+ const lasted = up - down;+ if (Math.abs(lasted - MENU_PRESS_SETTLE_MS) <= SETTLE_MARGIN_MS) {+ throw new Error(+ `The press lasted ${lasted} ms, within ${SETTLE_MARGIN_MS} ms of the ${MENU_PRESS_SETTLE_MS} ms settle time, so its outcome cannot be judged`,+ );+ }+ const isSettled = lasted > MENU_PRESS_SETTLE_MS;+ expect(+ await menuState(page, trigger),+ `a press of ${lasted} ms released outside the menu`,+ ).toEqual(+ isSettled ? {expanded: 'false', open: 0} : {expanded: 'true', open: 1},+ );+ return isSettled;+}++test('a quick drag off the trigger, released on the page, leaves the menu open', async ({+ page,+}) => {+ await openStory(page, storybook(), 'core-dropdownmenu--default');+ await installPressClock(page);+ const trigger = page.getByRole('button', {name: 'Actions'});+ const start = centerOf(await boxOf(trigger));+ await page.mouse.move(start.x, start.y);+ await page.mouse.down();+ await page.mouse.move(start.x - 200, start.y, {steps: 2});+ await page.mouse.up();+ await frames(page, 2);+ const isSettled = await expectModelOutcome(page, trigger);+ if (!isSettled) {+ // The press is over, and its claim with it: a later press outside+ // dismisses the menu.+ await page.mouse.click(start.x - 200, start.y + 200);+ await frames(page, 2);+ expect(await menuState(page, trigger)).toEqual({+ expanded: 'false',+ open: 0,+ });+ }+});++test('the trigger moving away under a still pointer before the release leaves the menu open', async ({+ page,+}) => {+ await openStory(page, storybook(), 'core-dropdownmenu--default');+ await installPressClock(page);+ const trigger = page.getByRole('button', {name: 'Actions'});+ const start = centerOf(await boxOf(trigger));+ await page.mouse.move(start.x, start.y);+ await page.mouse.down();+ // The panel that holds the trigger moves 120 px, and the pointer stays.+ const under = await page.evaluate(({x, y}) => {+ const panel = document.querySelector('#storybook-root') as HTMLElement;+ panel.style.translate = '-120px 0';+ const element = document.elementFromPoint(x, y);+ return {+ isOnTrigger: element?.closest('button') != null,+ isInMenu: element?.closest('[popover]') != null,+ };+ }, start);+ expect(under, 'the release point is off the trigger and the menu').toEqual({+ isOnTrigger: false,+ isInMenu: false,+ });+ await page.mouse.up();+ await frames(page, 2);+ await expectModelOutcome(page, trigger);+});++test('a press held past the settle time and released on the page closes the menu', async ({+ page,+}) => {+ await openStory(page, storybook(), 'core-dropdownmenu--default');+ await installPressClock(page);+ const trigger = page.getByRole('button', {name: 'Actions'});+ const start = centerOf(await boxOf(trigger));+ await page.mouse.move(start.x, start.y);+ await page.mouse.down();+ await page.mouse.move(start.x - 200, start.y, {steps: 2});+ // The input itself: the press lasts past the settle time.+ await page.waitForTimeout(MENU_PRESS_SETTLE_MS + 150);+ await page.mouse.up();+ await frames(page, 2);+ expect(await expectModelOutcome(page, trigger), 'the press settled').toBe(+ true,+ );+});++// Forces a show that waits: another menu's hide runs as the next press starts,+// and the browser refuses the first show once. The layer runtime then replays+// the show once that hide ends, during the press. Returns the trigger to press.+async function forceOneWaitingShow(page: Page): Promise<Locator> {+ await openStory(page, storybook(), 'core-dropdownmenu--lab-selectable-sizes');+ const other = page.getByRole('button', {name: 'Small menu'});+ await other.click();+ await expect(other).toHaveAttribute('aria-expanded', 'true');+ await frames(page, 2);+ await page.evaluate(() => {+ const otherLayer = document.querySelector(+ '[data-layer-anchored]:popover-open',+ ) as HTMLElement;+ const w = window as unknown as {__refused: number};+ w.__refused = 0;+ addEventListener(+ 'pointerdown',+ () => {+ otherLayer.hidePopover();+ },+ {capture: true, once: true},+ );+ const show = HTMLElement.prototype.showPopover;+ HTMLElement.prototype.showPopover = function (+ this: HTMLElement,+ ...args: Parameters<HTMLElement['showPopover']>+ ) {+ if (this !== otherLayer && w.__refused === 0) {+ w.__refused += 1;+ throw new DOMException('refused once by the test', 'InvalidStateError');+ }+ show.apply(this, args);+ };+ });+ return page.getByRole('button', {name: 'Large menu'});+}++async function expectReplayedShow(page: Page, trigger: Locator) {+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');+ expect(+ await page.evaluate(+ () => (window as unknown as {__refused: number}).__refused,+ ),+ 'the first show was refused, so the open was a replay',+ ).toBe(1);+}++test('FORCED DEFERRAL: after a show that waited, a release on the trigger leaves the menu open', async ({+ page,+}) => {+ const trigger = await forceOneWaitingShow(page);+ const start = centerOf(await boxOf(trigger));+ await page.mouse.move(start.x, start.y);+ await page.mouse.down();+ await expectReplayedShow(page, trigger);+ await page.mouse.up();+ await frames(page, 2);+ expect(await menuState(page, trigger)).toEqual({expanded: 'true', open: 1});+});++test('FORCED DEFERRAL: after a show that waited, a settled press released on the page closes the menu', async ({+ page,+}) => {+ const trigger = await forceOneWaitingShow(page);+ await installPressClock(page);+ const start = centerOf(await boxOf(trigger));+ await page.mouse.move(start.x, start.y);+ await page.mouse.down();+ await expectReplayedShow(page, trigger);+ await page.mouse.move(start.x, start.y + 300, {steps: 2});+ // The input itself: the press lasts past the settle time.+ await page.waitForTimeout(MENU_PRESS_SETTLE_MS + 150);+ await page.mouse.up();+ await frames(page, 2);+ expect(await expectModelOutcome(page, trigger), 'the press settled').toBe(+ true,+ );+});++test('a plain click on the trigger still aims its pointerup and click at the trigger', async ({+ page,+}) => {+ // Registered before any page script, so it sees the click before the+ // press model's click guard swallows it, as it does on every press-open.+ await page.addInitScript(() => {+ const w = window as unknown as {__aimedAt: string[]};+ w.__aimedAt = [];+ for (const type of ['pointerup', 'click']) {+ addEventListener(+ type,+ event => {+ const target = event.target instanceof Element ? event.target : null;+ const at =+ target?.closest('[popover]') != null+ ? 'layer'+ : target?.closest('button') != null+ ? 'trigger'+ : 'page';+ w.__aimedAt.push(`${type} ${at}`);+ },+ true,+ );+ }+ });+ await openStory(page, storybook(), 'core-dropdownmenu--default');+ const trigger = page.getByRole('button', {name: 'Actions'});+ // What a caller's own pointerup handler on the trigger sees.+ await trigger.evaluate(element => {+ const w = window as unknown as {__onTrigger: number};+ w.__onTrigger = 0;+ element.addEventListener('pointerup', () => {+ w.__onTrigger += 1;+ });+ });+ await page.evaluate(() => {+ (window as unknown as {__aimedAt: string[]}).__aimedAt.length = 0;+ });+ await trigger.click();+ await frames(page, 2);+ expect(+ await page.evaluate(() => {+ const w = window as unknown as {__aimedAt: string[]; __onTrigger: number};+ return {aimedAt: w.__aimedAt, onTrigger: w.__onTrigger};+ }),+ ).toEqual({aimedAt: ['pointerup trigger', 'click trigger'], onTrigger: 1});+ expect(await menuState(page, trigger)).toEqual({expanded: 'true', open: 1});+});++// The page's listeners of the types a press claim uses, on the window and the+// document, as `target type` with an id per listener. The init script records+// them before any page script runs.+const CLAIM_TYPES = [+ 'pointermove',+ 'pointerup',+ 'pointercancel',+ 'contextmenu',+ 'scroll',+ 'resize',+];++async function recordPageListeners(page: Page) {+ await page.addInitScript(types => {+ interface Entry {+ target: EventTarget;+ type: string;+ listener: unknown;+ capture: boolean;+ removed: boolean;+ }+ const log: Entry[] = [];+ (window as unknown as {__listeners: Entry[]}).__listeners = log;+ const captureOf = (options: boolean | EventListenerOptions | undefined) =>+ typeof options === 'boolean' ? options : Boolean(options?.capture);+ const add = EventTarget.prototype.addEventListener;+ const remove = EventTarget.prototype.removeEventListener;+ EventTarget.prototype.addEventListener = function (+ type: string,+ listener: EventListenerOrEventListenerObject | null,+ options?: boolean | AddEventListenerOptions,+ ) {+ if ((this === window || this === document) && types.includes(type)) {+ log.push({+ target: this,+ type,+ listener,+ capture: captureOf(options),+ removed: false,+ });+ }+ return add.call(this, type, listener, options);+ };+ EventTarget.prototype.removeEventListener = function (+ type: string,+ listener: EventListenerOrEventListenerObject | null,+ options?: boolean | EventListenerOptions,+ ) {+ const capture = captureOf(options);+ // The latest matching add is the listener this call removes.+ for (let index = log.length - 1; index >= 0; index -= 1) {+ const entry = log[index];+ if (+ !entry.removed &&+ entry.target === this &&+ entry.type === type &&+ entry.listener === listener &&+ entry.capture === capture+ ) {+ entry.removed = true;+ break;+ }+ }+ return remove.call(this, type, listener, options);+ };+ }, CLAIM_TYPES);+}++async function pageListeners(page: Page): Promise<string[]> {+ return page.evaluate(() =>+ (+ window as unknown as {+ __listeners: {target: EventTarget; type: string; removed: boolean}[];+ }+ ).__listeners.flatMap((e, id) =>+ e.removed+ ? []+ : [`${id} ${e.target === window ? 'window' : 'document'} ${e.type}`],+ ),+ );+}++// Closes the menu wherever a release left it. The other cases judge whether+// it stays open; this one counts listeners.+async function closeWhereverReleased(page: Page, trigger: Locator) {+ await frames(page, 2);+ if ((await trigger.getAttribute('aria-expanded')) === 'true') {+ await page.keyboard.press('Escape');+ }+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');+}++test('the menu opening on a press and closing leaves the page listening as it did at rest', async ({+ page,+}) => {+ await recordPageListeners(page);+ await openStory(page, storybook(), 'core-dropdownmenu--default');+ await frames(page, 2);+ const atRest = await pageListeners(page);+ const trigger = page.getByRole('button', {name: 'Actions'});+ const start = centerOf(await boxOf(trigger));+ // A quick press released off the trigger, which the menu claims.+ await page.mouse.move(start.x, start.y);+ await page.mouse.down();+ await page.mouse.move(start.x - 200, start.y, {steps: 2});+ await page.mouse.up();+ await closeWhereverReleased(page, trigger);+ // A plain click, which the trigger keeps.+ await page.mouse.click(start.x, start.y);+ await closeWhereverReleased(page, trigger);+ await frames(page, 2);+ expect(await pageListeners(page)).toEqual(atRest);+});diff --git a/packages/core/src/Layer/gestureCounter.test.ts b/packages/core/src/Layer/gestureCounter.test.tsindex 2a1617a1e8..d3d4eb9f3e 100644--- a/packages/core/src/Layer/gestureCounter.test.ts+++ b/packages/core/src/Layer/gestureCounter.test.ts@@ -2,16 +2,25 @@/*** @file gestureCounter.test.ts- * @input claimContextMenuPress with a stubbed layer box, stubbed pointer- * capture, and a layer inside an open shadow root+ * @input claimPress and claimContextMenuPress with a stubbed layer box,+ * stubbed pointer capture, and a layer inside an open shadow root* @output The claim compares the pointer with the layer's box read once (no* hit test or layout read per move), lets go over the layer, and ends when- * the layer closes while the button is still down+ * the layer closes while the button is still down. A primary press's claim+ * ends at its release and runs once per press and layer. A release target+ * holds the pointer while the pointer is over it, and no window listener+ * stays after the press. The context-menu claim takes only a press that+ * fired `contextmenu`* @position Unit test of packages/core/src/Layer/gestureCounter.ts*/import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';-import {claimContextMenuPress, currentGesture} from './gestureCounter';+import {+ claimContextMenuPress,+ claimPress,+ currentGesture,+ isPressInFlight,+} from './gestureCounter';/** A pointer event of `type` for `pointerId`, which jsdom's events lack. */function pointerEvent(@@ -170,3 +179,156 @@ describe('claimContextMenuPress', () => {expect(captured).toEqual([7]);});});++describe('claimPress', () => {+ let captured: number[];+ let released: number[];++ beforeEach(() => {+ captured = [];+ released = [];+ HTMLElement.prototype.setPointerCapture = (pointerId: number) => {+ captured.push(pointerId);+ };+ HTMLElement.prototype.hasPointerCapture = () => true;+ HTMLElement.prototype.releasePointerCapture = (pointerId: number) => {+ released.push(pointerId);+ };+ });++ afterEach(() => {+ document.dispatchEvent(pointerEvent('pointerup', 7));+ document.body.replaceChildren();+ vi.restoreAllMocks();+ delete (HTMLElement.prototype as Partial<HTMLElement>).setPointerCapture;+ delete (HTMLElement.prototype as Partial<HTMLElement>).hasPointerCapture;+ delete (HTMLElement.prototype as Partial<HTMLElement>)+ .releasePointerCapture;+ });++ /** A trigger and a layer whose box spans 100 to 200 on both axes. */+ function mountLayer() {+ const trigger = document.createElement('button');+ const layer = document.createElement('div');+ document.body.append(trigger, layer);+ vi.spyOn(layer, 'getBoundingClientRect').mockReturnValue(+ new DOMRect(100, 100, 100, 100),+ );+ // Reading the gesture installs its listeners before the press.+ currentGesture();+ return {trigger, layer};+ }++ it('captures a primary press outside the layer, lets go over it, and ends at the release', () => {+ const {trigger, layer} = mountLayer();+ trigger.dispatchEvent(pointerEvent('pointerdown', 7));+ expect(isPressInFlight()).toBe(true);+ claimPress(layer);+ expect(captured).toEqual([7]);++ layer.dispatchEvent(pointerEvent('pointermove', 7, {x: 150, y: 150}));+ expect(released).toEqual([7]);+ trigger.dispatchEvent(pointerEvent('pointermove', 7, {x: 20, y: 20}));+ expect(captured).toEqual([7, 7]);++ trigger.dispatchEvent(pointerEvent('pointerup', 7, {x: 20, y: 20}));+ expect(isPressInFlight()).toBe(false);+ // The claim ended with its press.+ trigger.dispatchEvent(pointerEvent('pointermove', 7, {x: 20, y: 20}));+ expect(captured).toEqual([7, 7]);+ });++ it('claims a press once for a layer', () => {+ const {trigger, layer} = mountLayer();+ trigger.dispatchEvent(pointerEvent('pointerdown', 7));+ claimPress(layer);+ claimPress(layer);+ expect(captured).toEqual([7]);+ // One claim follows the pointer, not two.+ trigger.dispatchEvent(pointerEvent('pointermove', 7, {x: 20, y: 20}));+ expect(captured).toEqual([7, 7]);+ });++ it('claims nothing when no press is down', () => {+ const {trigger, layer} = mountLayer();+ trigger.dispatchEvent(pointerEvent('pointerdown', 7));+ trigger.dispatchEvent(pointerEvent('pointerup', 7));+ claimPress(layer);+ expect(captured).toEqual([]);+ });++ it('gives the pointer to the release target over it, lets go over the layer, and gives it to the layer outside both', () => {+ const {trigger, layer} = mountLayer();+ vi.spyOn(trigger, 'getBoundingClientRect').mockReturnValue(+ new DOMRect(0, 0, 50, 20),+ );+ // One element holds the pointer at a time, as in a browser.+ let holder: Element | null = null;+ const holders: Element[] = [];+ const take = (element: Element) => {+ holder = element;+ holders.push(element);+ };+ const letGo = (element: Element) => {+ if (holder === element) {+ holder = null;+ }+ };+ HTMLElement.prototype.setPointerCapture = function (this: HTMLElement) {+ take(this);+ };+ HTMLElement.prototype.hasPointerCapture = function (this: HTMLElement) {+ return holder === this;+ };+ HTMLElement.prototype.releasePointerCapture = function (this: HTMLElement) {+ letGo(this);+ };+ trigger.dispatchEvent(pointerEvent('pointerdown', 7));+ claimPress(layer, {releaseTarget: trigger});+ // The press began on the release target, so it holds the pointer.+ expect(holders).toEqual([trigger]);++ layer.dispatchEvent(pointerEvent('pointermove', 7, {x: 150, y: 150}));+ expect(holder).toBeNull();+ document.body.dispatchEvent(+ pointerEvent('pointermove', 7, {x: 300, y: 300}),+ );+ expect(holder).toBe(layer);+ trigger.dispatchEvent(pointerEvent('pointermove', 7, {x: 10, y: 10}));+ expect(holder).toBe(trigger);+ expect(holders).toEqual([trigger, layer, trigger]);+ });++ it('leaves the window listening as before once its press ends', () => {+ const {trigger, layer} = mountLayer();+ // Spies that pass through: each add and remove still reaches the window.+ const add = vi.spyOn(window, 'addEventListener');+ const remove = vi.spyOn(window, 'removeEventListener');+ trigger.dispatchEvent(pointerEvent('pointerdown', 7));+ claimPress(layer, {releaseTarget: trigger});+ trigger.dispatchEvent(pointerEvent('pointermove', 7, {x: 300, y: 300}));+ trigger.dispatchEvent(pointerEvent('pointerup', 7, {x: 300, y: 300}));+ const listening = new Map<string, number>();+ for (const [type] of add.mock.calls) {+ listening.set(type, (listening.get(type) ?? 0) + 1);+ }+ for (const [type] of remove.mock.calls) {+ listening.set(type, (listening.get(type) ?? 0) - 1);+ }+ // Every window listener the press and its claim added is gone.+ expect(add).toHaveBeenCalled();+ expect([...listening].filter(([, n]) => n !== 0)).toEqual([]);+ });++ it('claims a press for the context menu only once that press fired contextmenu', () => {+ const {trigger, layer} = mountLayer();+ trigger.dispatchEvent(pointerEvent('pointerdown', 7));+ claimContextMenuPress(layer);+ expect(captured).toEqual([]);+ trigger.dispatchEvent(+ new MouseEvent('contextmenu', {bubbles: true, composed: true}),+ );+ claimContextMenuPress(layer);+ expect(captured).toEqual([7]);+ });+});diff --git a/packages/core/src/Layer/gestureCounter.ts b/packages/core/src/Layer/gestureCounter.tsindex 5a59516038..1bdbc7b1bc 100644--- a/packages/core/src/Layer/gestureCounter.ts+++ b/packages/core/src/Layer/gestureCounter.ts@@ -6,10 +6,13 @@* @file gestureCounter.ts* @input Pointer and context-menu events through the shared input stream;* keydown and click on the document- * @output Exports the gesture identity, whether its click has run, and- * claimContextMenuPress- * @position Internal to Layer; used by useLayer to tell a click that belongs- * to a dismissing press from a fresh one+ * @output Exports the gesture identity, whether its click has run, whether a+ * press is down, and the press claims (claimPress, claimContextMenuPress)+ * @position Internal to the package, not exported. useLayer reads it to tell+ * a click that belongs to a dismissing press from a fresh one.+ * useTouchTrigger, useMenuPress, ContextMenu and DropdownMenu read the+ * gesture too. A layer or a menu that opens on a press claims that press+ * here** A browser light-dismiss and the trigger's own click come from ONE press, and* which of them React sees first is a race. Comparing timestamps against a@@ -25,6 +28,11 @@ let gesture = 0;let clickedGesture: number | null = null;let contextMenuGesture: number | null = null;let pressPointerId: number | null = null;+let claimedPress: {+ layer: HTMLElement;+ pointerId: number;+ gesture: number;+} | null = null;let isListening = false;function advance() {@@ -98,36 +106,66 @@ export function currentGestureHasClicked(): boolean {return clickedGesture === gesture;}+/** Whether a press is down, its release not yet seen by the page. */+export function isPressInFlight(): boolean {+ listen();+ return pressPointerId !== null;+}+/**- * Keeps the release of the press in flight from dismissing `layer`, when that- * press opened a context menu (a right click). The browser's light dismiss- * reads a release outside every open popover as a dismissal, also the release- * of the press that opened the popover. While the pointer is outside the- * layer, the layer captures it, so a release there lands on the layer. Over- * the layer the capture lets go, so hover works and a release there is inside- * anyway. The claim ends at that press's release, or when the layer closes; a- * later press dismisses as usual.+ * Keeps the release of the press in flight from dismissing `layer`. The+ * browser's light dismiss reads a release outside every open popover as a+ * dismissal, also the release of the press that opened the popover. While the+ * pointer is outside the layer, the layer captures it, so a release there+ * lands on the layer. Over the layer the capture lets go, so hover works and a+ * release there is inside anyway. The claim ends at that press's release, or+ * when the layer closes; a later press dismisses as usual. A second claim of+ * the same press for the same layer does nothing.+ *+ * `releaseTarget` is the control the press began on, which the caller keeps+ * as the popover's invoker. It holds the pointer while the pointer is over+ * it, so its own pointerup and click still reach it. It still gets them when+ * it moves away under a pointer that stays still.*/-export function claimContextMenuPress(layer: HTMLElement): void {+export function claimPress(+ layer: HTMLElement,+ {releaseTarget = null}: {releaseTarget?: HTMLElement | null} = {},+): void {listen();const pointerId = pressPointerId;const view = layer.ownerDocument.defaultView;- if (pointerId === null || contextMenuGesture !== gesture || view == null) {+ if (pointerId === null || view == null) {return;}- const holdCapture = (isOutside: boolean) => {+ if (+ claimedPress !== null &&+ claimedPress.layer === layer &&+ claimedPress.pointerId === pointerId &&+ claimedPress.gesture === gesture+ ) {+ return;+ }+ const claim = {layer, pointerId, gesture};+ claimedPress = claim;+ // Gives the pointer to `holder`, or lets it go when `holder` is null.+ const holdCapture = (holder: HTMLElement | null) => {try {- if (isOutside) {- layer.setPointerCapture(pointerId);- } else if (layer.hasPointerCapture(pointerId)) {- layer.releasePointerCapture(pointerId);+ if (holder !== null) {+ holder.setPointerCapture(pointerId);+ return;+ }+ for (const element of [layer, releaseTarget]) {+ if (element?.hasPointerCapture(pointerId) === true) {+ element.releasePointerCapture(pointerId);+ }}} catch {// The pointer is no longer active (its release did not reach the// page), so no release can dismiss the layer.}};- holdCapture(true);+ // The press began on the release target, so the pointer is over it now.+ holdCapture(releaseTarget ?? layer);// A move of the pointer reads no layout. The claim reads the layer's box,// and the box of each popover open in it (a sub-menu), once. It reads them// again only after a scroll, a resize or a toggle in the layer.@@ -147,12 +185,33 @@ export function claimContextMenuPress(layer: HTMLElement): void {box => x >= box.left && x < box.right && y >= box.top && y < box.bottom,);};+ let targetBox: DOMRect | null = null;+ const isOverTarget = (x: number, y: number): boolean => {+ targetBox ??= releaseTarget?.getBoundingClientRect() ?? null;+ if (targetBox === null) {+ return false;+ }+ return (+ x >= targetBox.left &&+ x < targetBox.right &&+ y >= targetBox.top &&+ y < targetBox.bottom+ );+ };const invalidate = () => {boxes = null;+ targetBox = null;};const followPointer = (event: PointerEvent) => {if (event.pointerId === pointerId) {- holdCapture(!isOverLayer(event.clientX, event.clientY));+ const {clientX: x, clientY: y} = event;+ if (isOverLayer(x, y)) {+ holdCapture(null);+ } else if (releaseTarget !== null && isOverTarget(x, y)) {+ holdCapture(releaseTarget);+ } else {+ holdCapture(layer);+ }}};const unsubscribes: (() => void)[] = [];@@ -161,6 +220,9 @@ export function claimContextMenuPress(layer: HTMLElement): void {unsubscribe();}unsubscribes.length = 0;+ if (claimedPress === claim) {+ claimedPress = null;+ }};const endClaim = (event: PointerEvent) => {if (event.pointerId === pointerId) {@@ -174,7 +236,7 @@ export function claimContextMenuPress(layer: HTMLElement): void {event.target === layer &&(event as Event & {newState?: string}).newState === 'closed') {- holdCapture(false);+ holdCapture(null);stop();return;}@@ -190,3 +252,14 @@ export function claimContextMenuPress(layer: HTMLElement): void {() => layer.removeEventListener('toggle', onToggle, true),);}++/**+ * Claims the press in flight for `layer` (`claimPress`) when that press opened+ * a context menu (a right click).+ */+export function claimContextMenuPress(layer: HTMLElement): void {+ listen();+ if (contextMenuGesture === gesture) {+ claimPress(layer);+ }+}