Skip to content

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

TypeScript

fix(DropdownMenu): on a phone or a tablet, a tap while the menu enters is ignored, as on iOS (#8458)

Christopher Chedeau5b54b834c936
diff --git a/.changeset/dropdownmenu-entrance-hold.md b/.changeset/dropdownmenu-entrance-hold.md
new file mode 100644
index 0000000000..3ea9772593
--- /dev/null
+++ b/.changeset/dropdownmenu-entrance-hold.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] On a phone or a tablet, a finger's tap or drag that lands while a DropdownMenu is still opening is now ignored, as on iOS: the menu finishes opening, stays open and keeps focus, and nothing under the tap reacts. The finger that opened the menu still picks a row. Keys and assistive technology stay live. A mouse, a finger on a touchscreen laptop and `presentation="popover"` are unchanged.
+
+@vjeux
diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md
index 68d6e47bc8..d228f7f81f 100644
--- a/docs/specs/AST-094-touch-presentations/spec.md
+++ b/docs/specs/AST-094-touch-presentations/spec.md
@@ -927,10 +927,11 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and
let a scrim or overlay tap close at any time (`spec:AST-003` FR10 and
`architecture:layer-runtime` INV14 leave dismissal to the component). Toast and a non-modal sheet (`component:BottomSheetSwitcher` FR5 and its
Non-modal state) do not hold the page: the page behind them stays live, and
- only the sheet itself holds a tap or a drag while it enters. Dialog, Drawer
- and MobileNav hold an entrance only under a coarse primary pointer: where
- the primary pointer is fine and the screen also takes touch (a touchscreen
- laptop), a finger's tap or drag during the entrance is not held. After a
+ only the sheet itself holds a tap or a drag while it enters. Dialog, Drawer,
+ MobileNav and DropdownMenu hold an entrance only under a coarse primary
+ pointer: where the primary pointer is fine and the screen also takes touch
+ (a touchscreen laptop), a finger's tap or drag during the entrance is not
+ held. After a
finger, the first press of a mouse that has not moved since lands on the
entering presentation's shield and does nothing, where FR35 keeps today's
behavior for a mouse (DEC-16); a move of the mouse lowers the shield first.
diff --git a/docs/specs/components/DropdownMenu/DropdownMenu.spec.md b/docs/specs/components/DropdownMenu/DropdownMenu.spec.md
index d918a131bb..665078b673 100644
--- a/docs/specs/components/DropdownMenu/DropdownMenu.spec.md
+++ b/docs/specs/components/DropdownMenu/DropdownMenu.spec.md
@@ -143,6 +143,7 @@ component-local concepts; each keeps its released default.
| FR17 | A disabled menu row MUST be reached by the keyboard and stay inert (DEC-11): in DropdownMenu, its sub-menus, MoreMenu, ContextMenu and NavHeadingMenu, ArrowDown, ArrowUp, Home, End and type-ahead visit a disabled row as they visit any other row, the row takes focus and exposes `aria-disabled="true"`, and Enter, Space or a click on it does nothing and leaves the menu open. Opening a menu from the keyboard still lands on an enabled row: the first, or the last after ArrowUp on the trigger (FR12, AR4). Implementation gap: the arrow keys and type-ahead skip disabled rows today. | DEC-11; WAI-ARIA Menu pattern |
| FR20 | With `header` or `footer` on a sub-menu (`DropdownMenuSubMenu`), its surface is a modal dialog named by its row (AR7), holding the header, the sub-menu's `role="menu"` (rows only), then the footer. It sits in a host `DropdownMenu` renders beside its menu, never inside a menu; under a root with no such host (`ContextMenu`) the sub-menu shows its rows alone. On a fine pointer the dialog is the flyout; on a compact touch display, the drilled-in view, which replaces the root's menu and regions until popped. A region keeps its own keys and presses. The rows are one Tab stop: Tab and Shift+Tab walk the header's controls, the rows, then the footer's, and wrap; from a deeper flyout, that flyout closes and the walk goes on from the rows. An open lands as for any sub-menu (FR11, FR12), not on a region. Escape in the dialog, outside an IME composition and unless a control there handled it, returns focus to the row and leaves the root open. A pointer leaving the flyout keeps it open until focus leaves, and it closes with the flyout holding its row. Without either prop nothing changes. | Current behavior; FR15; AR5 |
| FR21 | Under a finger, in the touch modes (`presentation` not pinned to `'popover'`), the pointer menu MUST grow out of the Trigger button on the theme's entrance duration and easing tokens and collapse back into it on the theme's exit duration and easing (`spec:AST-094` FR7, FR31, FR45), and MUST close as a pan that starts outside it begins (FR32); a pinned `'popover'` keeps the layer's own entrance. A pan dismissal is the menu's own close: focus that was in the menu returns to the Trigger button, whose `aria-expanded` turns false. A mouse keeps the layer's own entrance and exit. Implementation gap: the menu keeps the layer's own entrance and exit under a finger too, and has no pan-outside dismissal of its own. | `spec:AST-094` FR31, FR32; `family:overlay-dismissal` AV6 |
+| FR22 | Under a finger, in the touch modes, where the primary pointer is coarse (a phone or a tablet), a tap or a drag that lands while the pointer menu enters MUST reach nothing: it closes nothing, scrolls nothing, moves no focus and clicks nothing (`spec:AST-094` FR35). The finger that opened the menu still picks the row it lifts on (FR8). Keys and assistive technology stay live. A mouse, a pinned `'popover'` and a finger where the primary pointer is fine (a touchscreen laptop) hold nothing, as for `component:Drawer`. | `spec:AST-094` FR35; `architecture:layer-runtime` |
### Allowed variation
@@ -337,8 +338,8 @@ than adding a DropdownMenu-owned heading target.
adoption gaps.
- `family:navigation-destinations` owns link-row destinations and blocked
schemes (FR10).
-- `spec:AST-094` owns the touch press, open, grow, and dismissal rules (FR5,
- FR8, FR11, FR21).
+- `spec:AST-094` owns the touch press, open, grow, entrance, and dismissal
+ rules (FR5, FR8, FR11, FR21, FR22).
## Verification map
@@ -361,6 +362,7 @@ than adding a DropdownMenu-owned heading target.
| FR17, AR6 | DropdownMenu, MoreMenu, ContextMenu and NavHeadingMenu keyboard tests, plus a real-browser keyboard check of focus order and blocked activation and a real-browser accessibility-tree check that a focused disabled row is announced as disabled (`spec:AST-085` Platform support); disabled-row cases | Disabled rows | A disabled row that runs a caller handler, closes the menu, is skipped by the arrow keys or type-ahead, or is not announced as disabled fails. | `audit:DropdownMenu/accessibility` |
| FR20, AR7 | `DropdownMenuSubMenu.test.tsx` header and footer cases, including "on a phone"; `SubMenuHeaderFooter.a11y.chromium.spec.ts`; `ContextMenu.test.tsx` "shows a sub-menu with a header or footer as its rows alone, and says why in development" | Fine pointer and phone; Escape paths; nested flyouts; pointer leaving | A region inside a menu, an unnamed dialog, a Tab walk that does not wrap, an Escape that closes the root, or a flyout that closes while focus is inside fails. | `audit:DropdownMenu/accessibility` |
| FR21 | Evidence gap: no test, matching the FR21 gap | — | — | `audit:DropdownMenu/behavior` |
+| FR22 | `DropdownMenu.test.tsx` "DropdownMenu entrance under a finger" cases; `useMenuPress.test.tsx` "an input hold over the menu" cases; `DropdownMenuEntranceHold.interaction.browser.spec.ts` | A tap outside and a finger's slide while the menu enters; a mouse click | A tap during the entrance that closes the menu, clicks the page or moves focus, a slide that picks nothing, or a held mouse fails. | `audit:DropdownMenu/behavior` |
| PR1 | Evidence gap: no test asserts the listener and observer bounds | — | — | `audit:DropdownMenu/behavior` |
| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and targets | Missing, extra, prefixed, stale, or alias-backed mappings fail repository validation. | `audit:DropdownMenu/theming` |
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index 81ee1d9da8..f0c2a4140d 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -38,6 +38,7 @@ import {spacingVars} from '../theme/tokens.stylex';
import {COMPACT_TOUCH_PRESENTATION_QUERY} from '../hooks/useAdaptivePresentation';
import {MENU_PRESS_LONG_PRESS_MS} from '../hooks/useMenuPress';
import {MENU_PRESS_SETTLE_MS} from '../hooks/menuPressGesture';
+import {isInHeldLayer} from '../Layer/inputHold';
import {TOUCH_QUERY} from '../utils/touchPresentation';
import {UIKIT_GESTURES} from '../motion/uikit/gestures';
@@ -2932,6 +2933,115 @@ describe('DropdownMenu data/compound parity', () => {
});
});
+describe('DropdownMenu entrance under a finger', () => {
+ function renderMenu(presentation?: 'popover') {
+ render(
+ <DropdownMenu
+ button={{label: 'Actions'}}
+ presentation={presentation}
+ items={[
+ {label: 'Edit', onClick: () => {}},
+ {label: 'Delete', onClick: () => {}},
+ ]}
+ />,
+ );
+ return screen.getByRole('button', {name: /Actions/});
+ }
+
+ const item = (name: string) =>
+ screen.getByRole('menuitem', {name, hidden: true});
+
+ // The primary pointer: a phone's finger, or a desktop's mouse.
+ function stubPointer(pointer: 'coarse' | 'fine') {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockImplementation((query: string) => ({
+ matches: pointer === 'coarse' && query === TOUCH_QUERY,
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ );
+ }
+
+ /**
+ * Gives each popover a running entrance (Web Animations' `getAnimations()`,
+ * which jsdom lacks) whose end the test decides.
+ */
+ function stubEntrance() {
+ let end = () => {};
+ const finished = new Promise<void>(resolve => {
+ end = resolve;
+ });
+ const entrance = {
+ playState: 'running',
+ finished,
+ effect: {getComputedTiming: () => ({endTime: 165})},
+ };
+ Object.defineProperty(Element.prototype, 'getAnimations', {
+ configurable: true,
+ value(this: Element) {
+ return this.matches('[popover]') ? [entrance] : [];
+ },
+ });
+ return {
+ async end() {
+ await act(async () => {
+ end();
+ });
+ },
+ };
+ }
+
+ afterEach(() => {
+ Reflect.deleteProperty(Element.prototype, 'getAnimations');
+ });
+
+ it('takes no touch while it enters: the layer is held until the entrance ends (spec:AST-094 FR35)', async () => {
+ stubPointer('coarse');
+ const entrance = stubEntrance();
+ const user = userEvent.setup();
+ await user.click(renderMenu());
+ expect(isInHeldLayer(item('Edit'))).toBe(true);
+
+ await entrance.end();
+ expect(isInHeldLayer(item('Edit'))).toBe(false);
+ });
+
+ it('lets go at once when it closes during its entrance', async () => {
+ stubPointer('coarse');
+ stubEntrance();
+ const user = userEvent.setup();
+ const trigger = renderMenu();
+ await user.click(trigger);
+ expect(isInHeldLayer(item('Edit'))).toBe(true);
+
+ await user.keyboard('{Escape}');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(isInHeldLayer(item('Edit'))).toBe(false);
+ });
+
+ it('under a fine primary pointer (a mouse, or a finger on a touchscreen laptop), holds nothing: the layer\u2019s own entrance plays', async () => {
+ stubPointer('fine');
+ stubEntrance();
+ const user = userEvent.setup();
+ await user.click(renderMenu());
+ expect(isInHeldLayer(item('Edit'))).toBe(false);
+ });
+
+ it('pinned to presentation="popover", holds nothing under a finger', async () => {
+ stubPointer('coarse');
+ stubEntrance();
+ const user = userEvent.setup();
+ await user.click(renderMenu('popover'));
+ expect(isInHeldLayer(item('Edit'))).toBe(false);
+ });
+});
+
describe('DropdownMenu press model', () => {
const mouse = {pointerType: 'mouse', pointerId: 1, button: 0};
const touch = {pointerType: 'touch', pointerId: 1};
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index 5e170fe2a7..b33c453243 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -5,7 +5,8 @@
/**
* @file DropdownMenu.tsx
* @input Uses React, StyleX, usePopover, MenuBottomSheet (lazy), Button, List,
- * useListFocus, and the shared viewport-safe menu-width resolver
+ * useListFocus, the shared viewport-safe menu-width resolver, and the
+ * layer runtime's entrance hold
* @output Exports DropdownMenu with caller-selected popover or bottom-sheet
* presentation
* @position Core implementation; consumed by index.ts
@@ -47,6 +48,7 @@ import React, {
import {readAccessibleName} from '../utils/accessibleName';
import * as stylex from '@stylexjs/stylex';
import {usePopover} from '../Popover/usePopover';
+import {holdEntranceInput} from '../Layer/holdEntranceInput';
import {Button, type ButtonProps} from '../Button';
import {Heading} from '../Heading';
import {Icon} from '../Icon';
@@ -956,6 +958,10 @@ function DropdownMenuPopover({
// The press model is mounted below (it needs the popover); the hide path
// above it ends the gesture in flight through this ref.
const cancelMenuPressRef = useRef<() => void>(() => {});
+ // The entrance hold starts as the layer shows. Its start is set below, once
+ // the list ref exists, and its release is kept for the close.
+ const holdEntranceRef = useRef<() => void>(() => {});
+ const releaseEntranceRef = useRef<(() => void) | null>(null);
// Submenu flyouts are `popover="manual"` elements nested inside the menu's
// `popover="auto"` element, so the browser's light dismiss of the menu never
@@ -1001,6 +1007,8 @@ function DropdownMenuPopover({
// keyboard (the modality tracker decides; the suppressed style hides the
// pointer case, which Safari would otherwise paint after a touch pick).
const handleLayerHide = useCallback(() => {
+ releaseEntranceRef.current?.();
+ releaseEntranceRef.current = null;
// Whatever closed the menu — light dismiss, the dismissal stack, Escape
// or a controlled close — its flyouts close with it.
hideOpenFlyouts();
@@ -1061,6 +1069,7 @@ function DropdownMenuPopover({
const handleLayerShow = useCallback(() => {
acceptedOpenRef.current = true;
+ holdEntranceRef.current();
resetFocusReturn();
if (renderTrigger != null) {
setTriggerName(readAccessibleName(buttonRef.current));
@@ -1202,6 +1211,28 @@ function DropdownMenuPopover({
});
}, [popover.isOpen, focusFirst, focusLast, listRef]);
+ // Under a finger, where the primary pointer is coarse, a tap or a drag during
+ // the entrance reaches nothing, as in UIMenu. Keys and assistive technology
+ // stay live.
+ const holdEntrance = useCallback(() => {
+ releaseEntranceRef.current?.();
+ const layer =
+ pressTouchModel === 'uikit'
+ ? listRef.current?.closest('[popover]')
+ : null;
+ releaseEntranceRef.current =
+ layer == null ? null : holdEntranceInput(layer);
+ }, [listRef, pressTouchModel]);
+ holdEntranceRef.current = holdEntrance;
+ // The layer runtime's input hold: an unmount during the entrance releases it.
+ useEffect(
+ () => () => {
+ releaseEntranceRef.current?.();
+ releaseEntranceRef.current = null;
+ },
+ [],
+ );
+
// With a header or footer the popover is a modal dialog: Tab and Shift+Tab
// walk the header's controls, the menu as one stop, then the footer's
// controls, and wrap at either end. The key is handled here in full, so the
diff --git a/packages/core/src/DropdownMenu/__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts b/packages/core/src/DropdownMenu/__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts
index 1f7075b674..fe45b26467 100644
--- a/packages/core/src/DropdownMenu/__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts
+++ b/packages/core/src/DropdownMenu/__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts
@@ -44,6 +44,15 @@ async function mount(page: Page) {
await expect(page.getByTestId('drill-in-fixture')).toBeVisible();
}
+/**
+ * The open popovers a person can perceive. While a menu enters under a
+ * finger, the layer runtime's input hold keeps an aria-hidden shield in the
+ * top layer. That shield is not a menu box.
+ */
+function perceivablePopovers(page: Page) {
+ return page.locator('[popover]:popover-open:not([aria-hidden="true"])');
+}
+
/** The rows a person can see: not under a hidden wrapper, not in a closed popover. */
function shownRows(page: Page) {
return page.locator('[role="menuitem"]:visible');
@@ -69,7 +78,7 @@ test.describe('on a phone (coarse pointer)', () => {
const rootMenu = page.getByRole('menu', {name: 'Actions'});
await expect(rootMenu).toBeVisible();
await expect(shownRows(page)).toHaveText(['Rename', 'Move to', 'Delete']);
- const popoversBefore = await page.locator('[popover]:popover-open').count();
+ const popoversBefore = await perceivablePopovers(page).count();
// Drill in with a finger.
const moveTo = page.getByRole('menuitem', {name: 'Move to'});
@@ -89,9 +98,7 @@ test.describe('on a phone (coarse pointer)', () => {
'Actions',
),
).toBe(true);
- expect(await page.locator('[popover]:popover-open').count()).toBe(
- popoversBefore,
- );
+ expect(await perceivablePopovers(page).count()).toBe(popoversBefore);
await expect(shownRows(page)).toHaveText([
'Back to Actions',
'Folder A',
@@ -211,16 +218,14 @@ test.describe('on a laptop (fine pointer)', () => {
const trigger = page.getByRole('button', {name: 'Actions'});
await trigger.click();
await expect(trigger).toHaveAttribute('aria-expanded', 'true');
- const popoversBefore = await page.locator('[popover]:popover-open').count();
+ const popoversBefore = await perceivablePopovers(page).count();
const moveTo = page.getByRole('menuitem', {name: 'Move to'});
await moveTo.click();
const flyout = page.getByRole('menu', {name: 'Move to'});
await expect(flyout).toBeVisible();
// A popover of its own, beside the row; the parent rows stay shown.
- expect(await page.locator('[popover]:popover-open').count()).toBe(
- popoversBefore + 1,
- );
+ expect(await perceivablePopovers(page).count()).toBe(popoversBefore + 1);
await expect(page.getByRole('menuitem', {name: 'Rename'})).toBeVisible();
await expect(page.getByRole('menuitem', {name: /^Back to/})).toHaveCount(0);
await expect(page.getByRole('menuitem', {name: 'Folder A'})).toBeFocused();
diff --git a/packages/core/src/DropdownMenu/__tests__/DropdownMenuEntranceHold.interaction.browser.spec.ts b/packages/core/src/DropdownMenu/__tests__/DropdownMenuEntranceHold.interaction.browser.spec.ts
new file mode 100644
index 0000000000..ce88142a97
--- /dev/null
+++ b/packages/core/src/DropdownMenu/__tests__/DropdownMenuEntranceHold.interaction.browser.spec.ts
@@ -0,0 +1,243 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DropdownMenuEntranceHold.interaction.browser.spec.ts
+ * @input The built Default DropdownMenu story under the harness's phone
+ * profile, with real touch input (Chromium CDP / WebKit's input command),
+ * and a mouse on a desktop profile. The menu's entrance is lengthened to
+ * 10 s, so input lands inside it on any box.
+ * @output Proof that a menu that enters under a finger takes no new input. A
+ * tap that lands then neither closes it nor reaches the page nor moves
+ * focus. Once the entrance ends, a tap outside dismisses it. The finger
+ * that opened the menu still picks the row it lifts on. A mouse is not held.
+ * @position Evidence for DropdownMenu's entrance hold; the layer runtime's
+ * hold has its own spec in Layer/__tests__
+ */
+
+import {
+ expect,
+ test,
+ type Locator,
+ type Page,
+} from '@astryxdesign/a11y-spec/playwright';
+import {
+ frames,
+ openStory,
+ path,
+ touchDriver,
+ waitForRest,
+ withStorybook,
+} from '@astryxdesign/interaction-harness';
+import {UIKIT_GESTURES} from '../../motion/uikit/gestures';
+
+const storybook = withStorybook(test);
+
+const HANDOFF_PX = UIKIT_GESTURES.menuPress.handoff.value;
+
+/** 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;
+}
+
+/** Page-side capture of the rows the story reports as picked. */
+async function installPickLog(page: Page) {
+ await page.evaluate(() => {
+ const picked: string[] = [];
+ (window as unknown as {__picked: string[]}).__picked = picked;
+ // The story reports a pick by logging "<label> clicked".
+ // eslint-disable-next-line no-console -- see above
+ const original = console.log.bind(console);
+ // eslint-disable-next-line no-console -- see above
+ console.log = (...args: unknown[]) => {
+ if (typeof args[0] === 'string' && args[0].endsWith(' clicked')) {
+ picked.push(args[0].replace(' clicked', ''));
+ }
+ original(...args);
+ };
+ });
+}
+
+const readPicked = async (page: Page) =>
+ page.evaluate(() => (window as unknown as {__picked: string[]}).__picked);
+
+interface LoggedClick {
+ insideLayer: boolean;
+ onTrigger: boolean;
+}
+
+/**
+ * Page-side log of every click: in the menu's layer, on its trigger, or
+ * elsewhere.
+ */
+async function installClickLog(page: Page) {
+ await page.evaluate(() => {
+ const clicks: {insideLayer: boolean; onTrigger: boolean}[] = [];
+ (window as unknown as {__clicks: typeof clicks}).__clicks = clicks;
+ document.addEventListener(
+ 'click',
+ event => {
+ const layer = document.querySelector('[popover]:has([role="menu"])');
+ const trigger = document.querySelector(
+ '[aria-haspopup][aria-expanded]',
+ );
+ const target = event.target instanceof Node ? event.target : null;
+ clicks.push({
+ insideLayer: layer?.contains(target) === true,
+ onTrigger: trigger?.contains(target) === true,
+ });
+ },
+ true,
+ );
+ });
+}
+
+const readClicks = async (page: Page) =>
+ page.evaluate(
+ () => (window as unknown as {__clicks: LoggedClick[]}).__clicks,
+ );
+
+const activeDescription = async (page: Page) =>
+ page.evaluate(() => {
+ const active = document.activeElement;
+ return active == null
+ ? 'none'
+ : `${active.tagName}#${active.id}[${active.getAttribute('role') ?? ''}]`;
+ });
+
+const menuLayer = (page: Page) =>
+ page.locator('[popover]:has([role="menu"])').first();
+
+/** Makes every popover's entrance last 10 s, so input lands inside it. */
+async function lengthenEntrance(page: Page) {
+ await page.addStyleTag({
+ content: '[popover] { animation-duration: 10s !important; }',
+ });
+}
+
+/** How many entrance animations run on the menu's layer now. */
+const runningEntrances = async (layer: Locator) =>
+ layer.evaluate(
+ element =>
+ element
+ .getAnimations()
+ .filter(animation => animation.playState === 'running').length,
+ );
+
+/** Ends the layer's entrance at once, as if its time had run out. */
+async function finishEntrance(page: Page, layer: Locator) {
+ await layer.evaluate(element => {
+ for (const animation of element.getAnimations()) {
+ animation.finish();
+ }
+ });
+ await frames(page, 2);
+}
+
+test('a tap that lands while the menu enters is ignored: it finishes, stays open and keeps focus; once it is in, a tap outside dismisses it (spec:AST-094 FR35)', async ({
+ page,
+}) => {
+ await openStory(page, storybook(), 'core-dropdownmenu--default');
+ await installClickLog(page);
+ await lengthenEntrance(page);
+ const driver = await touchDriver(page);
+ const trigger = page.getByRole('button', {name: 'Actions'});
+ const box = await boxOf(trigger);
+ await driver.tap({
+ x: Math.round(box.x + box.width / 2),
+ y: Math.round(box.y + box.height / 2),
+ });
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ const layer = menuLayer(page);
+ // The menu is on screen and still entering.
+ await expect(page.getByRole('menuitem', {name: 'Edit'})).toBeVisible();
+ expect(await runningEntrances(layer)).toBeGreaterThan(0);
+ await frames(page, 2);
+ const focused = await activeDescription(page);
+ const viewport = page.viewportSize() ?? {width: 402, height: 714};
+ const outside = {x: 20, y: viewport.height - 20};
+
+ await driver.tap(outside);
+ await frames(page, 2);
+ // The menu stays: nothing beneath was clicked, and focus did not move.
+ // The opening tap's own click lands on the trigger, whenever it arrives.
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ expect(
+ (await readClicks(page)).filter(
+ click => !click.insideLayer && !click.onTrigger,
+ ),
+ ).toEqual([]);
+ expect(await activeDescription(page)).toBe(focused);
+
+ // Once it is in, a tap outside is the browser's light dismiss again.
+ await finishEntrance(page, layer);
+ await driver.tap(outside);
+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');
+});
+
+test('the finger that opened the menu still picks the row it lifts on while the menu enters (spec:AST-094 FR29, FR35)', async ({
+ page,
+}) => {
+ await openStory(page, storybook(), 'core-dropdownmenu--default');
+ await installPickLog(page);
+ const driver = await touchDriver(page);
+ const trigger = page.getByRole('button', {name: 'Actions'});
+ const box = await boxOf(trigger);
+ const x = Math.round(box.x + box.width / 2);
+ // Measure the open menu's rows once its entrance has come to rest.
+ await driver.tap({x, y: Math.round(box.y + box.height / 2)});
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ const layer = menuLayer(page);
+ await waitForRest(layer);
+ const duplicate = await boxOf(
+ page.getByRole('menuitem', {name: 'Duplicate'}),
+ );
+ await page.keyboard.press('Escape');
+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ await waitForRest(layer);
+ await lengthenEntrance(page);
+
+ // The finger rests on the trigger's edge nearest the menu until the menu
+ // is open under it. Then it travels past the handoff onto a row and lifts
+ // there, all within the entrance.
+ const start = {x, y: Math.floor(box.y + box.height) - 1};
+ const end = {x, y: Math.round(duplicate.y + duplicate.height / 2)};
+ expect(end.y - start.y).toBeGreaterThan(HANDOFF_PX);
+ await driver.play(
+ path(progress => ({x, y: start.y + (end.y - start.y) * progress}), {
+ holdMs: 800,
+ durationMs: 250,
+ hz: 60,
+ restMs: 100,
+ }),
+ );
+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ await frames(page, 2);
+ expect(await readPicked(page)).toEqual(['Duplicate']);
+});
+
+test.describe('under a desktop mouse', () => {
+ test.use({
+ isMobile: false,
+ hasTouch: false,
+ viewport: {width: 1280, height: 720},
+ deviceScaleFactor: 1,
+ });
+
+ test('a click outside while the menu enters closes it: a mouse is not held', async ({
+ page,
+ }) => {
+ await openStory(page, storybook(), 'core-dropdownmenu--default');
+ await lengthenEntrance(page);
+ const trigger = page.getByRole('button', {name: 'Actions'});
+ await trigger.click();
+ await expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ await expect(page.getByRole('menuitem', {name: 'Edit'})).toBeVisible();
+ expect(await runningEntrances(menuLayer(page))).toBeGreaterThan(0);
+ await page.mouse.click(20, 700);
+ await expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+});
diff --git a/packages/core/src/DropdownMenu/__tests__/MenuPress.a11y.chromium.spec.ts b/packages/core/src/DropdownMenu/__tests__/MenuPress.a11y.chromium.spec.ts
index 299224b3d1..e903035e21 100644
--- a/packages/core/src/DropdownMenu/__tests__/MenuPress.a11y.chromium.spec.ts
+++ b/packages/core/src/DropdownMenu/__tests__/MenuPress.a11y.chromium.spec.ts
@@ -47,6 +47,24 @@ async function mount(page: Page, story: string) {
await expect(page.locator('#storybook-root')).toBeVisible();
}
+/**
+ * Waits until the open menu has finished entering. Under a finger, input that
+ * lands during the entrance is held, as UIMenu takes none until it is shown.
+ */
+async function presented(page: Page) {
+ const layer = page.locator('[popover]:has([role="menu"])').first();
+ await expect
+ .poll(async () =>
+ layer.evaluate(
+ element =>
+ element
+ .getAnimations()
+ .filter(animation => animation.playState === 'running').length,
+ ),
+ )
+ .toBe(0);
+}
+
/** The story items log `<label> clicked`; that line is the activation. */
function collectActivations(page: Page): string[] {
const seen: string[] = [];
@@ -306,6 +324,7 @@ test.describe('DropdownMenu press model (Chromium)', () => {
await touch.tap(cdp, await center(page, TRIGGER));
const menu = page.getByRole('menu');
await expect(menu).toBeVisible();
+ await presented(page);
const edit = await center(page, 'menuitem', 'Edit');
const del = await center(page, 'menuitem', 'Delete');
@@ -328,6 +347,7 @@ test.describe('DropdownMenu press model (Chromium)', () => {
await mount(page, MENU_STORY);
await touch.tap(cdp, await center(page, TRIGGER));
await expect(page.getByRole('menu')).toBeVisible();
+ await presented(page);
await touch.tap(cdp, await center(page, 'menuitem', 'Duplicate'));
await page.waitForTimeout(500);
expect(activations).toEqual(['Duplicate clicked']);
@@ -342,6 +362,7 @@ test.describe('DropdownMenu press model (Chromium)', () => {
await touch.tap(cdp, await center(page, TRIGGER));
const menu = page.getByRole('menu');
await expect(menu).toBeVisible();
+ await presented(page);
const edit = await center(page, 'menuitem', 'Edit');
await touch.start(cdp, edit);
await touch.slide(cdp, edit, {x: edit.x + 400, y: edit.y + 200});
@@ -378,6 +399,7 @@ test.describe('DropdownMenu press model (Chromium)', () => {
await touch.tap(cdp, await center(page, TRIGGER));
const menu = page.getByRole('menu');
await expect(menu).toBeVisible();
+ await presented(page);
await expect
.poll(async () =>
menu.evaluate(el => el.scrollHeight > el.clientHeight + 1),
diff --git a/packages/core/src/Layer/holdEntranceInput.ts b/packages/core/src/Layer/holdEntranceInput.ts
index 07128b34d3..aaee5fa248 100644
--- a/packages/core/src/Layer/holdEntranceInput.ts
+++ b/packages/core/src/Layer/holdEntranceInput.ts
@@ -8,10 +8,12 @@
* @output holdEntranceInput: under a coarse primary pointer, a finger's or a
* pen's input held away from the layer until its entrance ends
* @position The entrance hold for layers that enter through CSS (Dialog,
- * Drawer, MobileNav), on the Layer module's input hold (inputHold.ts)
+ * Drawer, MobileNav, DropdownMenu), on the Layer module's input hold
+ * (inputHold.ts)
*
* SYNC: When modified, update holdEntranceInput.test.ts and its callers
- * (Dialog.tsx, Drawer/useDrawerDialogPresence.ts, MobileNav/MobileNav.tsx).
+ * (Dialog.tsx, Drawer/useDrawerDialogPresence.ts, MobileNav/MobileNav.tsx,
+ * DropdownMenu/DropdownMenu.tsx).
*/
import {isCoarsePointer} from '../utils/coarsePointer';
diff --git a/packages/core/src/hooks/useMenuPress.test.tsx b/packages/core/src/hooks/useMenuPress.test.tsx
index 8be9db06d1..d78c85cb2b 100644
--- a/packages/core/src/hooks/useMenuPress.test.tsx
+++ b/packages/core/src/hooks/useMenuPress.test.tsx
@@ -24,6 +24,7 @@ import {
useMenuPress,
} from './useMenuPress';
import {MENU_PRESS_HANDOFF_PX, MENU_PRESS_SETTLE_MS} from './menuPressGesture';
+import {holdInput, isInputShield} from '../Layer/inputHold';
import {
isMenuPressLit,
isMenuPressPaintHeld,
@@ -137,6 +138,71 @@ afterEach(() => {
vi.useRealTimers();
});
+describe('useMenuPress — an input hold over the menu', () => {
+ afterEach(() => {
+ Reflect.deleteProperty(document, 'elementFromPoint');
+ Reflect.deleteProperty(document, 'elementsFromPoint');
+ });
+
+ it('its shield does not hide the rows from the finger already in the gesture (spec:AST-094 FR29, FR35)', () => {
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ const menu = screen.getByRole('menu');
+ // The finger is pressed before the hold starts, as the finger that opened
+ // the menu is.
+ fireEvent.pointerDown(row('A'), touch());
+ // The layer runtime's hold covers the viewport while the menu enters. A
+ // hit test there answers with its shield, which is not content.
+ const release = holdInput(menu, {
+ until: new Promise(() => {}),
+ scope: 'viewport',
+ });
+ try {
+ const shield = [...menu.children].find(isInputShield);
+ expect(shield).toBeDefined();
+ Object.defineProperty(document, 'elementFromPoint', {
+ configurable: true,
+ value: () => shield,
+ });
+ Object.defineProperty(document, 'elementsFromPoint', {
+ configurable: true,
+ value: () => [shield, row('B'), menu, document.body],
+ });
+ fireEvent.pointerMove(row('A'), {...touch(), clientX: 5, clientY: 20});
+ expect(row('B')).toHaveFocus();
+ fireEvent.pointerUp(row('A'), {...touch(), clientX: 5, clientY: 20});
+ expect(onSelect).toHaveBeenCalledWith('B');
+ } finally {
+ release();
+ }
+ });
+
+ it('anything else over the menu still covers it: only a hold\u2019s shield is seen through', () => {
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ const menu = screen.getByRole('menu');
+ const overlay = document.createElement('div');
+ document.body.append(overlay);
+ try {
+ Object.defineProperty(document, 'elementFromPoint', {
+ configurable: true,
+ value: () => overlay,
+ });
+ Object.defineProperty(document, 'elementsFromPoint', {
+ configurable: true,
+ value: () => [overlay, row('B'), menu, document.body],
+ });
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerMove(row('A'), {...touch(), clientX: 5, clientY: 20});
+ expect(row('B')).not.toHaveFocus();
+ fireEvent.pointerUp(row('A'), {...touch(), clientX: 5, clientY: 20});
+ expect(onSelect).not.toHaveBeenCalled();
+ } finally {
+ overlay.remove();
+ }
+ });
+});
+
describe('useMenuPress — tracking inside the menu', () => {
it('acts on the row under the RELEASE, not the row the press began on', () => {
const onSelect = vi.fn();
diff --git a/packages/core/src/hooks/useMenuPress.ts b/packages/core/src/hooks/useMenuPress.ts
index 733cd87867..ac04c3f04c 100644
--- a/packages/core/src/hooks/useMenuPress.ts
+++ b/packages/core/src/hooks/useMenuPress.ts
@@ -28,6 +28,7 @@ import {
type RefObject,
} from 'react';
import {currentGesture} from '../Layer/gestureCounter';
+import {isInputShield} from '../Layer/inputHold';
import {
IDLE_MENU_PRESS,
menuPressTransition,
@@ -403,13 +404,25 @@ export function useDropdownMenuPress(
// Hit-test in the menu's own tree: inside a shadow root the document
// answers with the shadow host, never the row under the pointer.
const tree = menu?.getRootNode();
- const scope: Pick<Document, 'elementFromPoint'> =
+ const scope: Pick<Document, 'elementFromPoint' | 'elementsFromPoint'> =
tree != null &&
tree !== doc &&
typeof (tree as ShadowRoot).elementFromPoint === 'function'
? (tree as ShadowRoot)
: doc;
element = scope.elementFromPoint(event.clientX, event.clientY);
+ if (
+ isInputShield(element) &&
+ typeof scope.elementsFromPoint === 'function'
+ ) {
+ // An input hold's shield covers the viewport while the menu enters.
+ // It keeps new input away, but the press in flight still reaches the
+ // row under it. So the hit test sees through that shield only.
+ element =
+ scope
+ .elementsFromPoint(event.clientX, event.clientY)
+ .find(candidate => !isInputShield(candidate)) ?? null;
+ }
} else {
element = event.target instanceof Element ? event.target : null;
}