Skip to content

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

TypeScript

feat(menus): act on the row under the pointer at release, and follow a held finger (#6681)

Christopher Chedeau8c50bc3fa65e
diff --git a/.changeset/menu-press-model.md b/.changeset/menu-press-model.md
new file mode 100644
index 0000000000..9c1e14a295
--- /dev/null
+++ b/.changeset/menu-press-model.md
@@ -0,0 +1,18 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Menus and pickers act on the row under the pointer at release, and the highlight follows a held finger or mouse.
+
+`DropdownMenu`, `ContextMenu`, `DropdownMenuSubMenu`, `Selector` and the menu
+bottom sheet share one press model, the one macOS and iOS menus use: the row
+under the pointer when it is released is the row that acts, and the highlight
+follows a held pointer across the rows. A finger that lands on one row and
+lifts on another acts on the second — once; the click the browser aims at the
+first row is swallowed. A mouse released outside a menu closes it; a finger
+released outside leaves it open. A menu whose rows fit declares
+`touch-action: none` so a slide stays a slide; one that scrolls lets the
+browser pan it and ends the gesture. Menu rows no longer paint a pressed look
+where hover does not exist. New public hook: `useMenuPress`.
+
+@vjeux
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index 3c8eb9980e..2b74460732 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -3780,6 +3780,11 @@
"path": "hooks/use-media-query",
"aliases": []
},
+ {
+ "name": "hook-use-menu-press",
+ "path": "hooks/use-menu-press",
+ "aliases": []
+ },
{
"name": "hook-use-merged-refs",
"path": "hooks/use-merged-refs",
diff --git a/packages/cli/test/doc-routes.ids.json b/packages/cli/test/doc-routes.ids.json
index 333e0b97df..6d922c99e1 100644
--- a/packages/cli/test/doc-routes.ids.json
+++ b/packages/cli/test/doc-routes.ids.json
@@ -216,6 +216,7 @@
"useLocale",
"useLongPress",
"useMediaQuery",
+ "useMenuPress",
"useMergedRefs",
"useOverflow",
"usePopover",
diff --git a/packages/cli/test/doc-routes.json b/packages/cli/test/doc-routes.json
index 520785771e..f2c63f4441 100644
--- a/packages/cli/test/doc-routes.json
+++ b/packages/cli/test/doc-routes.json
@@ -4381,7 +4381,7 @@
"kind": "hook",
"id": "@astryxdesign/core/hook",
"provider": "@astryxdesign/core",
- "count": 55,
+ "count": 56,
"oldCliRoute": "astryx hook <id>",
"oldDocsiteUrl": "/components/<id>",
"placement": "generated:@astryxdesign/core/hook",
diff --git a/packages/core/src/ContextMenu/ContextMenu.spec.md b/packages/core/src/ContextMenu/ContextMenu.spec.md
index 10ddaae962..770344bb3b 100644
--- a/packages/core/src/ContextMenu/ContextMenu.spec.md
+++ b/packages/core/src/ContextMenu/ContextMenu.spec.md
@@ -77,12 +77,13 @@ presentation policy remain documented in `ContextMenu.doc.mjs`.
## Behavioral and layout contract
-| ID | Candidate invariant | Basis | Draft review state |
-| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------------------------------------------------- |
-| FR1 | Every render contains a caller-provided Trigger area. Pointer presentation opens a Pointer menu surface at the current local cursor anchor; touch presentation opens a Touch sheet frame containing a Touch menu surface and, for data mode, a Touch action list and Touch action rows. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
-| FR2 | The current `context-menu` target remains on the painted Pointer menu surface and alternative Touch menu surface, not on the Trigger area or cursor anchor. | Current source, docs, and tests | Verified current inventory; no target change |
-| FR3 | Pointer action rows retain DropdownMenu ownership. The touch frame retains BottomSheet ownership, while data-driven touch lists and rows retain List ownership. | Current source and owner docs | Verified current delegation; no ownership change |
-| FR4 | Compound `menuContent` remains a caller-supplied pointer-menu interior and may also render inside the touch frame; the data-driven touch path instead converts the same item data to List and ListItem presentation. | Current source and tests | Verified current branches; no behavior change |
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------- |
+| FR1 | Every render contains a caller-provided Trigger area. Pointer presentation opens a Pointer menu surface at the current local cursor anchor; touch presentation opens a Touch sheet frame containing a Touch menu surface and, for data mode, a Touch action list and Touch action rows. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
+| FR2 | The current `context-menu` target remains on the painted Pointer menu surface and alternative Touch menu surface, not on the Trigger area or cursor anchor. | Current source, docs, and tests | Verified current inventory; no target change |
+| FR3 | Pointer action rows retain DropdownMenu ownership. The touch frame retains BottomSheet ownership, while data-driven touch lists and rows retain List ownership. | Current source and owner docs | Verified current delegation; no ownership change |
+| FR4 | Compound `menuContent` remains a caller-supplied pointer-menu interior and may also render inside the touch frame; the data-driven touch path instead converts the same item data to List and ListItem presentation. | Current source and tests | Verified current branches; no behavior change |
+| FR5 | The Pointer menu surface carries `data-astryx-menu-press` and follows `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the stray click never acts, and `touch-action` follows overflow. Right-click, Shift+F10, long-press invocation and keyboard navigation are unchanged. | `module:DropdownMenu/useMenuPress`; `ContextMenu.test.tsx` press model suite | Proposed; verified in jsdom |
### Allowed variation
@@ -116,9 +117,10 @@ presentation policy remain documented in `ContextMenu.doc.mjs`.
## Accessibility contract
-This draft does not change or extend ContextMenu's existing menu and dialog
-naming, keyboard invocation, long-press path, focus movement, item semantics, or
-dismissal behavior.
+This draft does not change ContextMenu's menu and dialog naming, keyboard
+invocation, long-press path, keyboard navigation, item semantics, focus
+return, or dismissal ordering. While a pointer is held in the pointer menu,
+the highlight is DOM focus per `module:DropdownMenu/useMenuPress` AR1.
## Design relationships
@@ -189,12 +191,14 @@ anchor is positioning infrastructure rather than consumer anatomy.
| FR2 | ContextMenu target tests, source inspection, and theming target inventories | Pointer and touch menu surfaces | Moving `context-menu` to the trigger or removing it from a painted branch fails evidence. | `audit:ContextMenu/theming` |
| FR3 | ContextMenu, DropdownMenu, BottomSheet, and List owner tests | Pointer rows, touch frame, touch list/rows | A composed part loses its owner target or is documented as a new ContextMenu target. | `audit:ContextMenu/theming` |
| Layer relationships | `ContextMenu.test.tsx` and current layer/dismissal architecture records | Outside click, Escape, context anchor, sheet | Documentation claims shared dismissal where current source retains local behavior. | `audit:ContextMenu/behavior` |
+| FR5 | `ContextMenu.test.tsx` press model case; `module:DropdownMenu/useMenuPress` map | Finger slide across rows, stray click | A row acting on the press row or the stray click fails. | `audit:ContextMenu/behavior` |
| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:ContextMenu/theming` |
## Decision log
-None. This draft records current facts and introduces no component-local design,
-API, theming, modality, or layer-system decision.
+None component-local. The press model decision lives in
+`module:DropdownMenu/useMenuPress`; this record introduces no design,
+theming, or layer-system decision of its own.
## Open questions
diff --git a/packages/core/src/ContextMenu/ContextMenu.test.tsx b/packages/core/src/ContextMenu/ContextMenu.test.tsx
index 143ce1ca08..e2a8509ed8 100644
--- a/packages/core/src/ContextMenu/ContextMenu.test.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.test.tsx
@@ -1032,3 +1032,34 @@ describe('ContextMenu keyboard access for menuitemradio/menuitemcheckbox (#3829)
).toHaveFocus();
});
});
+
+describe('ContextMenu press model', () => {
+ const touch = {pointerType: 'touch', pointerId: 1};
+ const item = (name: string) =>
+ screen.getByRole('menuitem', {name, hidden: true});
+ it('acts on the row under a finger release, once, and swallows the stray click', () => {
+ const onCut = vi.fn();
+ const onPaste = vi.fn();
+ render(
+ <ContextMenu
+ items={[
+ {label: 'Cut', onClick: onCut},
+ {label: 'Copy'},
+ {label: 'Paste', onClick: onPaste},
+ ]}>
+ <div>Right-click me</div>
+ </ContextMenu>,
+ );
+ fireEvent.contextMenu(screen.getByText('Right-click me'));
+ expect(screen.getByRole('menu', {hidden: true})).toHaveAttribute(
+ 'data-astryx-menu-press',
+ );
+ fireEvent.pointerDown(item('Cut'), touch);
+ fireEvent.pointerMove(item('Paste'), touch);
+ expect(item('Paste')).toHaveFocus();
+ fireEvent.pointerUp(item('Paste'), touch);
+ fireEvent.click(item('Cut'), {detail: 1});
+ expect(onPaste).toHaveBeenCalledTimes(1);
+ expect(onCut).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/src/ContextMenu/ContextMenu.tsx b/packages/core/src/ContextMenu/ContextMenu.tsx
index e6cccc7496..75d32843cf 100644
--- a/packages/core/src/ContextMenu/ContextMenu.tsx
+++ b/packages/core/src/ContextMenu/ContextMenu.tsx
@@ -58,7 +58,9 @@ import {
MENU_ITEM_SELECTOR,
MENU_BOUNDARY_SELECTOR,
} from '../DropdownMenu/menuItemRoles';
+import {useMenuOverflow} from '../DropdownMenu/useMenuOverflow';
import {useListFocus} from '../hooks/useListFocus';
+import {useMenuPress} from '../hooks/useMenuPress';
import {useTypeahead} from '../hooks/useTypeahead';
import {useLongPress} from '../hooks/useLongPress';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
@@ -133,6 +135,15 @@ const styles = stylex.create({
transitionDuration: durationVars['--duration-fast'],
transitionTimingFunction: easeVars['--ease-standard'],
userSelect: 'none',
+ WebkitTouchCallout: 'none',
+ },
+ // Scroll ownership by the browser's own signal; see DropdownMenu.
+ touchNone: {
+ touchAction: 'none',
+ },
+ touchPanY: {
+ touchAction: 'pan-y',
+ overscrollBehavior: 'contain',
},
popover: {
minWidth: '160px',
@@ -572,6 +583,22 @@ export function ContextMenu({
const resolvedMenuContent =
itemsProp !== undefined ? renderDropdownItems(items) : menuContent;
+ const hasOverflow = useMenuOverflow(
+ listRef,
+ resolvedMenuContent,
+ isOpen && !usesBottomSheet,
+ );
+
+ // The press model: the row under a release acts, the highlight follows a
+ // held pointer, a mouse released outside dismisses and a finger leaves the
+ // menu open.
+ const menuPress = useMenuPress({
+ menuRef: listRef,
+ itemSelector: MENU_ITEM_SELECTOR,
+ onDismiss: closeMenu,
+ isEnabled: !usesBottomSheet,
+ });
+
const renderedMenu = (
<div
ref={listRef}
@@ -582,9 +609,15 @@ export function ContextMenu({
aria-label={label}
onKeyDown={listKeyDown}
onContextMenu={e => e.preventDefault()}
+ {...menuPress.menuProps}
{...mergeProps(
themeProps('context-menu'),
- stylex.props(usesBottomSheet ? styles.sheetMenu : styles.menu, xstyle),
+ stylex.props(
+ usesBottomSheet ? styles.sheetMenu : styles.menu,
+ !usesBottomSheet &&
+ (hasOverflow ? styles.touchPanY : styles.touchNone),
+ xstyle,
+ ),
className,
style,
)}>
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
index fb03508737..92b78cc8a1 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
@@ -252,7 +252,7 @@ export const docs = {
usage: {
anatomy,
description:
- 'A dropdown menu that displays a list of actionable items in a popup triggered by a button. Use to present action options as a next step in a process, or to offer contextual actions without cluttering the interface.',
+ 'A dropdown menu that displays a list of actionable items in a popup triggered by a button. Use to present action options as a next step in a process, or to offer contextual actions without cluttering the interface. Like the menus of macOS and iOS, the row under the pointer when it is released is the row that acts, and the highlight follows a held mouse or finger.',
bestPractices: [
{
guidance: true,
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.spec.md b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
index 7f70f25d2a..aa84e23adc 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.spec.md
+++ b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
@@ -21,7 +21,7 @@ verified_by:
packages/core/src/Icon/Icon.test.tsx,
scripts/check-knowledge.mjs,
]
-modules: []
+modules: [module:DropdownMenu/useMenuPress]
families: [family:overlay-dismissal]
design_specs: []
architecture:
@@ -41,15 +41,17 @@ system_specs: []
DropdownMenu presents actions from a visible Button trigger in either an
anchored pointer menu or a BottomSheet-hosted touch action list. This draft
records current consumer anatomy, presentation-specific ownership, and theming
-reachability without changing runtime behavior, styling, targets, or public API.
+reachability. Its press model — the row under the release acts and the
+highlight follows the pointer — is contracted by
+`module:DropdownMenu/useMenuPress`, which both presentations mount.
## Compatibility and migration
- Released default preserved: `yes`
-- Compatibility class: additive documentation only; runtime, DOM, styling,
- targets, and public API remain unchanged
+- Compatibility class: additive documentation; the press-model behavior
+ delta is recorded in `module:DropdownMenu/useMenuPress` (DEC-3)
- Controlled/uncontrolled behavior: unchanged
-- Migration decision: none
+- Migration decision: `module:DropdownMenu/useMenuPress/DEC-3`
Consumer migration instructions belong in consumer docs and release notes.
@@ -64,6 +66,8 @@ Consumer migration instructions belong in consumer docs and release notes.
current DropdownMenu targets.
- Selecting between the current pointer and touch render paths after presentation
policy resolves.
+- Mounting the shared press model on both menu surfaces; the model itself is
+ owned by `module:DropdownMenu/useMenuPress`.
**Does not own / non-goals**
@@ -82,12 +86,13 @@ subcomponents, and presentation policy remain documented in
## Behavioral and layout contract
-| ID | Candidate invariant | Basis | Draft review state |
-| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------------------------------------------------- |
-| FR1 | Every current render contains a Trigger button. Pointer presentation renders a Pointer menu surface with pointer-owned rows and optional pointer headings, dividers, indicators, and nested flyouts. Touch presentation renders a Touch sheet frame containing a Touch menu surface, Touch heading, Touch action list, and Touch action rows. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
-| FR2 | The six current local targets are `dropdown-menu`, `dropdown-menu-item`, `dropdown-menu-radio`, `dropdown-menu-section-heading`, `dropdown-menu-divider`, and `dropdown-menu-indicator-icon`; every target remains on its current painted element. | Current source, docs, and tests | Verified current inventory; no target change |
-| FR3 | Button owns the Trigger button, BottomSheet owns the Touch sheet frame, List owns the Touch action list and Touch action rows, Indicator owns checkbox chrome, and Icon owns ordinary rendered icons. | Current source and owner docs | Verified current delegation; no ownership change |
-| FR4 | The same `dropdown-menu` target reaches the alternative Pointer menu surface and Touch menu surface. Pointer action rows retain `dropdown-menu-item`; touch action rows instead use List's `list-item` target. | Current source and tests | Verified modality split; no target change |
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | -------------------------------------------------- |
+| FR1 | Every current render contains a Trigger button. Pointer presentation renders a Pointer menu surface with pointer-owned rows and optional pointer headings, dividers, indicators, and nested flyouts. Touch presentation renders a Touch sheet frame containing a Touch menu surface, Touch heading, Touch action list, and Touch action rows. | Current source, docs, and tests | Verified current behavior; no new behavior decided |
+| FR2 | The six current local targets are `dropdown-menu`, `dropdown-menu-item`, `dropdown-menu-radio`, `dropdown-menu-section-heading`, `dropdown-menu-divider`, and `dropdown-menu-indicator-icon`; every target remains on its current painted element. | Current source, docs, and tests | Verified current inventory; no target change |
+| FR3 | Button owns the Trigger button, BottomSheet owns the Touch sheet frame, List owns the Touch action list and Touch action rows, Indicator owns checkbox chrome, and Icon owns ordinary rendered icons. | Current source and owner docs | Verified current delegation; no ownership change |
+| FR4 | The same `dropdown-menu` target reaches the alternative Pointer menu surface and Touch menu surface. Pointer action rows retain `dropdown-menu-item`; touch action rows instead use List's `list-item` target. | Current source and tests | Verified modality split; no target change |
+| FR5 | Both menu surfaces carry `data-astryx-menu-press` and follow `module:DropdownMenu/useMenuPress` FR1–FR7: the row under the release acts, the highlight follows a held pointer, a mouse released outside closes and a finger leaves the menu open, the browser's stray click never acts, and the Pointer menu surface declares `touch-action` by overflow. Trigger opening and keyboard navigation are unchanged. | `module:DropdownMenu/useMenuPress`; `DropdownMenu.test.tsx` press model suite | Proposed; verified in jsdom and real Chromium |
### Allowed variation
@@ -121,9 +126,10 @@ subcomponents, and presentation policy remain documented in
## Accessibility contract
-This draft does not change or extend DropdownMenu's existing trigger naming,
-menu and dialog roles, focus movement, keyboard navigation, item semantics, or
-dismissal behavior.
+This draft does not change DropdownMenu's trigger naming, menu and dialog
+roles, keyboard navigation, item semantics, focus return, or dismissal
+ordering. While a pointer is held, the highlight is DOM focus per
+`module:DropdownMenu/useMenuPress` AR1.
## Design relationships
@@ -222,18 +228,20 @@ than adding a DropdownMenu-owned heading target.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | --------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ----------------------------- |
-| FR1, FR4 | `DropdownMenu.test.tsx` pointer, bottom-sheet, adaptive, section, divider, and drill-in suites | Root pointer, nested pointer, root touch, drill-in | Collapsing presentation-specific parts or owners fails structure, target, or role assertions. | `audit:DropdownMenu/anatomy` |
-| FR2 | DropdownMenu target suites, source inspection, and theming target inventories | All six local targets | Removing, renaming, or assigning a current target to the wrong part fails evidence or inventory. | `audit:DropdownMenu/theming` |
-| FR3 | `DropdownMenuSelectable.test.tsx` plus BottomSheet, List, Indicator, Icon, and Divider owner tests | Trigger, touch actions, icons, checkbox, radio | A composed part loses its owner target or is documented as a new local target. | `audit:DropdownMenu/theming` |
-| Layer relationships | `DropdownMenu.test.tsx`, `DropdownMenuSubMenu.test.tsx`, and current layer/dismissal architecture records | Light dismiss, nested flyout, sheet dismissal | Documentation claims a shared owner where current source retains local behavior, or the reverse. | `audit:DropdownMenu/behavior` |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target inventory | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:DropdownMenu/theming` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------- | ----------------------------- |
+| FR1, FR4 | `DropdownMenu.test.tsx` pointer, bottom-sheet, adaptive, section, divider, and drill-in suites | Root pointer, nested pointer, root touch, drill-in | Collapsing presentation-specific parts or owners fails structure, target, or role assertions. | `audit:DropdownMenu/anatomy` |
+| FR2 | DropdownMenu target suites, source inspection, and theming target inventories | All six local targets | Removing, renaming, or assigning a current target to the wrong part fails evidence or inventory. | `audit:DropdownMenu/theming` |
+| FR3 | `DropdownMenuSelectable.test.tsx` plus BottomSheet, List, Indicator, Icon, and Divider owner tests | Trigger, touch actions, icons, checkbox, radio | A composed part loses its owner target or is documented as a new local target. | `audit:DropdownMenu/theming` |
+| Layer relationships | `DropdownMenu.test.tsx`, `DropdownMenuSubMenu.test.tsx`, and current layer/dismissal architecture records | Light dismiss, nested flyout, sheet dismissal | Documentation claims a shared owner where current source retains local behavior, or the reverse. | `audit:DropdownMenu/behavior` |
+| FR5 | `DropdownMenu.test.tsx` press model suite; the module record's own map | Finger slide across rows, outside release by mouse and finger, `touch-action`, root marker | A row acting on the press or the stray click, a lost `touch-action`, or a finger release that closes fails. | `audit:DropdownMenu/behavior` |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target inventory | Missing, extra, prefixed, stale, or unclassified mappings fail repository validation. | `audit:DropdownMenu/theming` |
## Decision log
-None. This draft records current facts and introduces no component-local design,
-API, theming, modality, or layer-system decision.
+None component-local. The press model decision lives in
+`module:DropdownMenu/useMenuPress` DEC-3; this record introduces no design,
+theming, or layer-system decision of its own.
## Open questions
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index b114311ebc..1ba7a63bc4 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -2244,3 +2244,71 @@ describe('DropdownMenu data/compound parity', () => {
expect(item).toHaveAccessibleName('Rename');
});
});
+
+describe('DropdownMenu press model', () => {
+ const mouse = {pointerType: 'mouse', pointerId: 1, button: 0};
+ const touch = {pointerType: 'touch', pointerId: 1};
+
+ function renderMenu(onPick: (label: string) => void = () => {}) {
+ render(
+ <DropdownMenu button={{label: 'Actions'}}>
+ <DropdownMenuItem label="Edit" onClick={() => onPick('Edit')} />
+ <DropdownMenuItem
+ label="Duplicate"
+ onClick={() => onPick('Duplicate')}
+ />
+ <DropdownMenuItem label="Delete" onClick={() => onPick('Delete')} />
+ </DropdownMenu>,
+ );
+ return screen.getByRole('button', {name: /Actions/});
+ }
+
+ const item = (name: string) =>
+ screen.getByRole('menuitem', {name, hidden: true});
+ it('a finger that lands on one row and lifts on another acts on the second, once', async () => {
+ const onPick = vi.fn();
+ const user = userEvent.setup();
+ const trigger = renderMenu(onPick);
+ await user.click(trigger);
+ fireEvent.pointerDown(item('Edit'), touch);
+ fireEvent.pointerMove(item('Delete'), touch);
+ expect(item('Delete')).toHaveFocus();
+ fireEvent.pointerUp(item('Delete'), touch);
+ // The WebKit tail: a click aimed at the row the touch began on.
+ fireEvent.click(item('Edit'), {detail: 1});
+ expect(onPick).toHaveBeenCalledTimes(1);
+ expect(onPick).toHaveBeenCalledWith('Delete');
+ });
+
+ it('a mouse released outside closes the menu; a finger released outside leaves it open', async () => {
+ const user = userEvent.setup();
+ const trigger = renderMenu();
+ await user.click(trigger);
+ fireEvent.pointerDown(item('Edit'), touch);
+ fireEvent.pointerUp(document.body, touch);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ fireEvent.pointerDown(item('Edit'), mouse);
+ fireEvent.pointerUp(document.body, mouse);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('marks the menu as carrying the press model and owns touch scrolling', async () => {
+ const user = userEvent.setup();
+ const trigger = renderMenu();
+ await user.click(trigger);
+ const menu = screen.getByRole('menu', {hidden: true});
+ expect(menu).toHaveAttribute('data-astryx-menu-press');
+ // jsdom does not compute `touch-action`; StyleX class names are a hash of
+ // property and value, so the same declaration yields the same class (the
+ // dev build prefixes a debug name; the hash is the last token).
+ const touchStyles = stylex.create({
+ none: {touchAction: 'none'},
+ panY: {touchAction: 'pan-y'},
+ });
+ const hash = (style: stylex.StyleXStyles) =>
+ stylex.props(style).className!.split(' ').pop()!;
+ expect(menu).toHaveClass(hash(touchStyles.none));
+ expect(menu).not.toHaveClass(hash(touchStyles.panY));
+ });
+});
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index 75a05f7aec..443a757912 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -57,6 +57,7 @@ import {
} from './DropdownMenuContext';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {useListFocus} from '../hooks/useListFocus';
+import {useMenuPress} from '../hooks/useMenuPress';
import {useTypeahead} from '../hooks/useTypeahead';
import {useFocusReturnVisibility} from '../hooks/useFocusReturnVisibility';
import {useMenuOverflow} from './useMenuOverflow';
@@ -109,6 +110,10 @@ const styles = stylex.create({
// stay owned by the menu. It is an internal focus target, not a control,
// so suppress the browser ring; keyboard focus moves to an item instead.
outline: 'none',
+ // Menu rows never offer the browser's held-press link preview or text
+ // selection: a held finger is driving the highlight.
+ WebkitTouchCallout: 'none',
+ userSelect: 'none',
maxInlineSize: stylex.firstThatWorks(
MENU_MAX_INLINE_SIZE,
MENU_MAX_INLINE_SIZE_FALLBACK,
@@ -131,6 +136,16 @@ const styles = stylex.create({
overflowX: 'hidden',
overscrollBehavior: 'contain',
},
+ // Scroll ownership by the browser's own signal. A menu whose rows fit keeps
+ // every finger: a slide over its rows stays a slide. One that scrolls lets
+ // the browser pan it vertically and cancel the press when it does.
+ touchNone: {
+ touchAction: 'none',
+ },
+ touchPanY: {
+ touchAction: 'pan-y',
+ overscrollBehavior: 'contain',
+ },
popoverViewport: {
boxSizing: 'border-box',
maxBlockSize: stylex.firstThatWorks(
@@ -611,6 +626,9 @@ function DropdownMenuPopover({
const suppressControlledRollbackHideRef = useRef(false);
useInteractionModalityTracking();
+ // 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>(() => {});
// Keyboard dismissal returns focus to the trigger. Pointer dismissal leaves
// focus where the browser put it; Safari can otherwise paint a focus-visible
@@ -621,6 +639,7 @@ function DropdownMenuPopover({
suppressControlledRollbackHideRef.current = false;
return;
}
+ cancelMenuPressRef.current();
pendingControlledOpenRef.current = false;
onOpenChange?.(false);
if (!isControlled) {
@@ -818,6 +837,17 @@ function DropdownMenuPopover({
[isControlled, popover],
);
+ // The press model: the row under a release acts, the highlight follows a
+ // held pointer. A mouse released outside the menu dismisses it; a finger
+ // released outside leaves it open, so the hook never calls onDismiss then.
+ const menuPress = useMenuPress({
+ menuRef: listRef,
+ triggerRef: buttonRef,
+ itemSelector: MENU_ITEM_SELECTOR,
+ onDismiss: closeMenu,
+ });
+ cancelMenuPressRef.current = menuPress.cancel;
+
const handleButtonClick = useCallback(
(e: React.MouseEvent<HTMLButtonElement>) => {
// detail === 0 marks a synthesized click (screen reader / AT
@@ -949,10 +979,12 @@ function DropdownMenuPopover({
// menu (menus-13).
aria-label={button.label}
onKeyDown={listKeyDown}
+ {...menuPress.menuProps}
{...mergeProps(
themeProps('dropdown-menu'),
stylex.props(
styles.dropdown,
+ hasOverflow ? styles.touchPanY : styles.touchNone,
hasOverflow && styles.scrollable,
xstyle,
),
diff --git a/packages/core/src/DropdownMenu/DropdownMenuItem.tsx b/packages/core/src/DropdownMenu/DropdownMenuItem.tsx
index e2d548b309..0eab43234c 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuItem.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuItem.tsx
@@ -52,8 +52,14 @@ const menuItemStyles = stylex.create({
backgroundColor: {
default: 'transparent',
':focus': colorVars['--color-overlay-hover'],
- ':active:where(:not(:disabled,[aria-disabled="true"]))':
- colorVars['--color-overlay-pressed'],
+ // The pressed look only where hover exists. Under a finger the row a
+ // press BEGAN on would otherwise stay painted while the highlight (focus)
+ // moves to the row under the finger — two rows lit.
+ '@media (hover: hover)': {
+ default: null,
+ ':active:where(:not(:disabled,[aria-disabled="true"]))':
+ colorVars['--color-overlay-pressed'],
+ },
},
borderWidth: 0,
borderStyle: 'none',
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
index 8ac517a5e2..a0d697125f 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx
@@ -906,3 +906,50 @@ describe('DropdownMenuSubMenu hover/click guard', () => {
).toHaveFocus();
});
});
+
+describe('DropdownMenuSubMenu press model', () => {
+ it('a press released on the sub-menu row opens it and keeps the menu', async () => {
+ const user = userEvent.setup();
+ render(<MoveMenu />);
+ const root = screen.getByRole('button', {name: /Actions/});
+ await user.click(root);
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ const rename = screen.getByRole('menuitem', {name: 'Rename', hidden: true});
+ fireEvent.pointerDown(rename, {pointerType: 'touch', pointerId: 1});
+ fireEvent.pointerMove(trigger, {pointerType: 'touch', pointerId: 1});
+ fireEvent.pointerUp(trigger, {pointerType: 'touch', pointerId: 1});
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ expect(root).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('a release inside the flyout acts on the flyout row and closes the whole menu', async () => {
+ const onMove = vi.fn();
+ const user = userEvent.setup();
+ render(<MoveMenu onMove={onMove} />);
+ const root = screen.getByRole('button', {name: /Actions/});
+ await user.click(root);
+ const trigger = screen.getByRole('menuitem', {
+ name: /Move to/,
+ hidden: true,
+ });
+ await user.click(trigger);
+ const folderB = screen.getByRole('menuitem', {
+ name: 'Folder B',
+ hidden: true,
+ });
+ const folderA = screen.getByRole('menuitem', {
+ name: 'Folder A',
+ hidden: true,
+ });
+ fireEvent.pointerDown(folderA, {pointerType: 'touch', pointerId: 1});
+ fireEvent.pointerMove(folderB, {pointerType: 'touch', pointerId: 1});
+ fireEvent.pointerUp(folderB, {pointerType: 'touch', pointerId: 1});
+ fireEvent.click(folderA, {detail: 1});
+ expect(onMove).toHaveBeenCalledTimes(1);
+ expect(onMove).toHaveBeenCalledWith('b');
+ expect(root).toHaveAttribute('aria-expanded', 'false');
+ });
+});
diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
index e1589a0ba2..f514a317ff 100644
--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx
@@ -56,6 +56,7 @@ import {useLayer} from '../Layer/useLayer';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
import {useListFocus} from '../hooks/useListFocus';
import {useMenuHover} from '../hooks/useMenuHover';
+import {useMenuPress} from '../hooks/useMenuPress';
import {useTypeahead} from '../hooks/useTypeahead';
import {useMenuOverflow} from './useMenuOverflow';
import {resolveMenuWidth} from './menuWidth';
@@ -165,12 +166,24 @@ const flyoutStyles = stylex.create({
transitionProperty: 'opacity',
transitionDuration: durationVars['--duration-fast'],
transitionTimingFunction: easeVars['--ease-standard'],
+ // A held finger drives the highlight; the browser's held-press callout
+ // and text selection must not compete with it.
+ WebkitTouchCallout: 'none',
+ userSelect: 'none',
},
scrollable: {
overflowY: 'auto',
overflowX: 'hidden',
overscrollBehavior: 'contain',
},
+ // Scroll ownership by the browser's own signal; see DropdownMenu.
+ touchNone: {
+ touchAction: 'none',
+ },
+ touchPanY: {
+ touchAction: 'pan-y',
+ overscrollBehavior: 'contain',
+ },
popoverViewport: {
boxSizing: 'border-box',
// Keep the inline viewport cap on the menu surface above. Applying it to
@@ -519,6 +532,15 @@ export function DropdownMenuSubMenu(
[menuSize, close, menuCtx],
);
+ // The press model for this flyout: the row under a release acts, the
+ // highlight follows a held pointer. A mouse released outside every level
+ // dismisses the whole menu; a finger leaves it open.
+ const menuPress = useMenuPress({
+ menuRef,
+ itemSelector: MENU_ITEM_SELECTOR,
+ onDismiss: nestedMenuContext.closeMenu,
+ });
+
const endAffordance = hasSpinner ? (
<span {...stylex.props(triggerStyles.caret)}>
<Spinner size="sm" />
@@ -596,10 +618,12 @@ export function DropdownMenuSubMenu(
onMouseEnter={contentProps.onMouseEnter}
onMouseLeave={contentProps.onMouseLeave}
data-testid={menuDataTestId}
+ {...menuPress.menuProps}
{...mergeProps(
themeProps('dropdown-menu'),
stylex.props(
flyoutStyles.menu,
+ hasOverflow ? flyoutStyles.touchPanY : flyoutStyles.touchNone,
hasOverflow && flyoutStyles.scrollable,
),
)}>
diff --git a/packages/core/src/DropdownMenu/MenuBottomSheetActionList.tsx b/packages/core/src/DropdownMenu/MenuBottomSheetActionList.tsx
index 599984512a..4ee8994c3e 100644
--- a/packages/core/src/DropdownMenu/MenuBottomSheetActionList.tsx
+++ b/packages/core/src/DropdownMenu/MenuBottomSheetActionList.tsx
@@ -9,18 +9,28 @@
* @position Shared implementation for menu bottom-sheet presentations
*/
-import type {ReactElement} from 'react';
+import {useRef, type ReactElement} from 'react';
import * as stylex from '@stylexjs/stylex';
import {Divider} from '../Divider';
import {Heading} from '../Heading';
import {Icon, renderIconSlot} from '../Icon';
import {List, ListItem} from '../List';
+import {useMenuPress} from '../hooks/useMenuPress';
import {colorVars, spacingVars} from '../theme/tokens.stylex';
import {rtlStyles} from '../utils';
import {getInteractionModality} from '../utils/interactionModality';
import type {DropdownMenuItemData, DropdownMenuOption} from './DropdownMenu';
+/** The action rows: ListItem renders its action as a button (or a link). */
+const SHEET_ROW_SELECTOR = 'button:not(:disabled), a[href]';
+
const styles = stylex.create({
+ // The row under a held finger is the highlight; the browser's held-press
+ // callout and text selection must not compete with it.
+ list: {
+ WebkitTouchCallout: 'none',
+ userSelect: 'none',
+ },
destructiveAction: {
'--_item-label-color': colorVars['--color-error'],
'--_item-description-color': colorVars['--color-error'],
@@ -55,6 +65,15 @@ export function MenuBottomSheetActionList({
onSelect: (item: DropdownMenuItemData) => void;
onOpenSubmenu: (item: DropdownMenuItemData) => void;
}) {
+ const listRef = useRef<HTMLUListElement>(null);
+ // The press model: the row under a finger's RELEASE acts, and the
+ // highlight (focus) follows the finger across the rows. The sheet is modal,
+ // so a release outside it is the scrim's, not a dismissal of ours.
+ const menuPress = useMenuPress({
+ menuRef: listRef,
+ itemSelector: SHEET_ROW_SELECTOR,
+ });
+
const renderItem = (
item: DropdownMenuItemData,
index: number,
@@ -104,7 +123,11 @@ export function MenuBottomSheetActionList({
};
return (
- <List density="spacious">
+ <List
+ ref={listRef}
+ density="spacious"
+ xstyle={styles.list}
+ {...menuPress.menuProps}>
{items.map((option, index) => {
if ('type' in option && option.type === 'divider') {
return (
diff --git a/packages/core/src/DropdownMenu/__tests__/MenuPress.a11y.chromium.spec.ts b/packages/core/src/DropdownMenu/__tests__/MenuPress.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..340b8ab0fe
--- /dev/null
+++ b/packages/core/src/DropdownMenu/__tests__/MenuPress.a11y.chromium.spec.ts
@@ -0,0 +1,401 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file MenuPress.a11y.chromium.spec.ts
+ * @input Built DropdownMenu and Selector stories and real Chromium mouse,
+ * touch (CDP) and pen (CDP) input
+ * @output Browser evidence for the menu press model: the row under the
+ * release acts once, the highlight follows the pointer, a release outside
+ * closes under a mouse and not under a finger, a touch pan in an
+ * overflowing menu cancels the gesture, and a pen behaves like a finger
+ * @position Real-engine proof for module:DropdownMenu/useMenuPress — the
+ * paths jsdom cannot exercise (hit testing, touch synthesis, scrolling)
+ */
+
+import {expect, test, type Page, type CDPSession} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+let storybook: StaticServer;
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+const MENU_STORY = 'core-dropdownmenu--default';
+const OVERFLOW_STORY = 'core-dropdownmenu--with-sections';
+const SELECTOR_STORY = 'core-selector--default';
+
+async function mount(page: Page, story: string) {
+ await page.goto(`${storybook.origin}/iframe.html?id=${story}&viewMode=story`);
+ await expect(page.locator('#storybook-root')).toBeVisible();
+}
+
+/** The story items log `<label> clicked`; that line is the activation. */
+function collectActivations(page: Page): string[] {
+ const seen: string[] = [];
+ page.on('console', message => {
+ const text = message.text();
+ if (text.endsWith(' clicked')) {
+ seen.push(text);
+ }
+ });
+ return seen;
+}
+
+async function center(page: Page, selector: string, name?: string) {
+ const locator =
+ name == null
+ ? page.locator(selector)
+ : page.getByRole(selector as 'menuitem' | 'option', {
+ name,
+ exact: true,
+ });
+ const box = await locator.boundingBox();
+ if (box == null) {
+ throw new Error(`${selector} ${name ?? ''} has no rendered bounds`);
+ }
+ return {x: box.x + box.width / 2, y: box.y + box.height / 2};
+}
+
+/** The story's own controls, not Storybook's addon buttons. */
+const TRIGGER = '#storybook-root [aria-haspopup="menu"]';
+const COMBOBOX = '#storybook-root [role="combobox"]';
+
+async function enableTouch(page: Page): Promise<CDPSession> {
+ const cdp = await page.context().newCDPSession(page);
+ await cdp.send('Emulation.setTouchEmulationEnabled', {
+ enabled: true,
+ maxTouchPoints: 2,
+ });
+ await cdp.send('Emulation.setEmitTouchEventsForMouse', {
+ enabled: false,
+ });
+ return cdp;
+}
+
+const touch = {
+ async start(cdp: CDPSession, p: {x: number; y: number}) {
+ await cdp.send('Input.dispatchTouchEvent', {
+ type: 'touchStart',
+ touchPoints: [{x: p.x, y: p.y, id: 1}],
+ });
+ },
+ async move(cdp: CDPSession, p: {x: number; y: number}) {
+ await cdp.send('Input.dispatchTouchEvent', {
+ type: 'touchMove',
+ touchPoints: [{x: p.x, y: p.y, id: 1}],
+ });
+ },
+ async end(cdp: CDPSession) {
+ await cdp.send('Input.dispatchTouchEvent', {
+ type: 'touchEnd',
+ touchPoints: [],
+ });
+ },
+ async tap(cdp: CDPSession, p: {x: number; y: number}) {
+ await touch.start(cdp, p);
+ await touch.end(cdp);
+ },
+ /** A slide in steps, so the browser sees real movement. */
+ async slide(
+ cdp: CDPSession,
+ from: {x: number; y: number},
+ to: {x: number; y: number},
+ steps = 6,
+ ) {
+ for (let i = 1; i <= steps; i++) {
+ await touch.move(cdp, {
+ x: from.x + ((to.x - from.x) * i) / steps,
+ y: from.y + ((to.y - from.y) * i) / steps,
+ });
+ }
+ },
+};
+
+const pen = {
+ async press(cdp: CDPSession, p: {x: number; y: number}) {
+ await cdp.send('Input.dispatchMouseEvent', {
+ type: 'mousePressed',
+ x: p.x,
+ y: p.y,
+ button: 'left',
+ buttons: 1,
+ clickCount: 1,
+ pointerType: 'pen',
+ });
+ },
+ async move(cdp: CDPSession, p: {x: number; y: number}) {
+ await cdp.send('Input.dispatchMouseEvent', {
+ type: 'mouseMoved',
+ x: p.x,
+ y: p.y,
+ button: 'left',
+ buttons: 1,
+ pointerType: 'pen',
+ });
+ },
+ async release(cdp: CDPSession, p: {x: number; y: number}) {
+ await cdp.send('Input.dispatchMouseEvent', {
+ type: 'mouseReleased',
+ x: p.x,
+ y: p.y,
+ button: 'left',
+ buttons: 0,
+ clickCount: 1,
+ pointerType: 'pen',
+ });
+ },
+};
+
+async function openMenuWithMouse(page: Page) {
+ await page.getByRole('button', {name: /Actions|File/}).click();
+ const menu = page.getByRole('menu');
+ await expect(menu).toBeVisible();
+ await expect(menu).toHaveAttribute('data-astryx-menu-press', '');
+ return menu;
+}
+
+async function activeRowName(page: Page) {
+ return page.evaluate(() => {
+ const active = document.activeElement;
+ const row = active?.closest('[role^="menuitem"], [role="option"]');
+ return row?.textContent?.trim() ?? null;
+ });
+}
+
+test.describe('DropdownMenu press model (Chromium)', () => {
+ test('mouse: a drag from one row released over another acts on the second, once', async ({
+ page,
+ }) => {
+ const activations = collectActivations(page);
+ await mount(page, MENU_STORY);
+ const menu = await openMenuWithMouse(page);
+
+ const edit = await center(page, 'menuitem', 'Edit');
+ const del = await center(page, 'menuitem', 'Delete');
+ await page.mouse.move(edit.x, edit.y);
+ await page.mouse.down();
+ await page.mouse.move(del.x, del.y, {steps: 6});
+ expect(await activeRowName(page)).toBe('Delete');
+ await page.mouse.up();
+
+ await expect.poll(() => activations).toEqual(['Delete clicked']);
+ await expect(menu).toBeHidden();
+ });
+
+ test('mouse: a release outside the menu acts on nothing and closes it', async ({
+ page,
+ }) => {
+ const activations = collectActivations(page);
+ await mount(page, MENU_STORY);
+ const menu = await openMenuWithMouse(page);
+ const edit = await center(page, 'menuitem', 'Edit');
+ await page.mouse.move(edit.x, edit.y);
+ await page.mouse.down();
+ await page.mouse.move(edit.x + 400, edit.y + 200, {steps: 6});
+ await page.mouse.up();
+ await expect(menu).toBeHidden();
+ expect(activations).toEqual([]);
+ });
+
+ test('touch: a finger that lands on Edit and lifts on Delete acts on Delete, once; the highlight followed it', async ({
+ page,
+ }) => {
+ const activations = collectActivations(page);
+ const cdp = await enableTouch(page);
+ await mount(page, MENU_STORY);
+ await touch.tap(cdp, await center(page, TRIGGER));
+ const menu = page.getByRole('menu');
+ await expect(menu).toBeVisible();
+
+ const edit = await center(page, 'menuitem', 'Edit');
+ const del = await center(page, 'menuitem', 'Delete');
+ await touch.start(cdp, edit);
+ expect(await activeRowName(page)).toBe('Edit');
+ await touch.slide(cdp, edit, del);
+ expect(await activeRowName(page)).toBe('Delete');
+ await touch.end(cdp);
+
+ await expect.poll(() => activations).toEqual(['Delete clicked']);
+ await expect(menu).toBeHidden();
+ // Give the browser's own click for the gesture every chance to arrive.
+ await page.waitForTimeout(500);
+ expect(activations).toEqual(['Delete clicked']);
+ });
+
+ test('touch: a tap on a row acts exactly once', async ({page}) => {
+ const activations = collectActivations(page);
+ const cdp = await enableTouch(page);
+ await mount(page, MENU_STORY);
+ await touch.tap(cdp, await center(page, TRIGGER));
+ await expect(page.getByRole('menu')).toBeVisible();
+ await touch.tap(cdp, await center(page, 'menuitem', 'Duplicate'));
+ await page.waitForTimeout(500);
+ expect(activations).toEqual(['Duplicate clicked']);
+ });
+
+ test('touch: a finger released outside acts on nothing and leaves the menu open', async ({
+ page,
+ }) => {
+ const activations = collectActivations(page);
+ const cdp = await enableTouch(page);
+ await mount(page, MENU_STORY);
+ await touch.tap(cdp, await center(page, TRIGGER));
+ const menu = page.getByRole('menu');
+ await expect(menu).toBeVisible();
+ 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});
+ await touch.end(cdp);
+ await page.waitForTimeout(300);
+ await expect(menu).toBeVisible();
+ expect(activations).toEqual([]);
+ });
+
+ test('touch: a vertical pan in an overflowing menu scrolls it and acts on nothing', async ({
+ page,
+ }) => {
+ const activations = collectActivations(page);
+ const cdp = await enableTouch(page);
+ // A short viewport caps the menu below its content so it overflows.
+ await page.setViewportSize({width: 800, height: 220});
+ await mount(page, OVERFLOW_STORY);
+ await touch.tap(cdp, await center(page, TRIGGER));
+ const menu = page.getByRole('menu');
+ await expect(menu).toBeVisible();
+ await expect
+ .poll(async () =>
+ menu.evaluate(el => el.scrollHeight > el.clientHeight + 1),
+ )
+ .toBe(true);
+ await expect
+ .poll(async () => menu.evaluate(el => getComputedStyle(el).touchAction))
+ .toBe('pan-y');
+
+ const first = await center(page, 'menuitem', 'New File');
+ const scrollBefore = await menu.evaluate(el => el.scrollTop);
+ await touch.start(cdp, first);
+ await touch.slide(cdp, first, {x: first.x, y: first.y - 80}, 8);
+ await touch.end(cdp);
+ await page.waitForTimeout(400);
+
+ const scrollAfter = await menu.evaluate(el => el.scrollTop);
+ expect(scrollAfter).toBeGreaterThan(scrollBefore);
+ expect(activations).toEqual([]);
+ await expect(menu).toBeVisible();
+ });
+
+ test('touch: a menu whose rows fit declares touch-action none, so a slide stays a slide', async ({
+ page,
+ }) => {
+ await enableTouch(page);
+ await mount(page, MENU_STORY);
+ await openMenuWithMouse(page);
+ const menu = page.getByRole('menu');
+ await expect
+ .poll(async () => menu.evaluate(el => getComputedStyle(el).touchAction))
+ .toBe('none');
+ });
+
+ test('pen: a drag released over another row acts on it once; a release outside leaves the menu open', async ({
+ page,
+ }) => {
+ const activations = collectActivations(page);
+ const cdp = await page.context().newCDPSession(page);
+ await mount(page, MENU_STORY);
+ const menu = await openMenuWithMouse(page);
+
+ const edit = await center(page, 'menuitem', 'Edit');
+ const dup = await center(page, 'menuitem', 'Duplicate');
+ await pen.press(cdp, edit);
+ await pen.move(cdp, dup);
+ expect(await activeRowName(page)).toBe('Duplicate');
+ await pen.release(cdp, dup);
+ await expect.poll(() => activations).toEqual(['Duplicate clicked']);
+ await expect(menu).toBeHidden();
+ await page.waitForTimeout(400);
+ expect(activations).toEqual(['Duplicate clicked']);
+
+ // Reopen and release outside: a pen is "a finger" — the menu stays.
+ await openMenuWithMouse(page);
+ const edit2 = await center(page, 'menuitem', 'Edit');
+ await pen.press(cdp, edit2);
+ await pen.move(cdp, {x: edit2.x + 400, y: edit2.y + 200});
+ await pen.release(cdp, {x: edit2.x + 400, y: edit2.y + 200});
+ await page.waitForTimeout(300);
+ await expect(page.getByRole('menu')).toBeVisible();
+ expect(activations).toEqual(['Duplicate clicked']);
+ });
+});
+
+test.describe('Selector press model (Chromium)', () => {
+ test('touch: a finger that lands on Apple and lifts on Orange selects Orange; the combobox keeps focus', async ({
+ page,
+ }) => {
+ const cdp = await enableTouch(page);
+ await mount(page, SELECTOR_STORY);
+ const combobox = page.getByRole('combobox');
+ await touch.tap(cdp, await center(page, COMBOBOX));
+ const listbox = page.getByRole('listbox');
+ await expect(listbox).toBeVisible();
+ await expect(listbox).toHaveAttribute('data-astryx-menu-press', '');
+
+ const apple = await center(page, 'option', 'Apple');
+ const orange = await center(page, 'option', 'Orange');
+ await touch.start(cdp, apple);
+ await touch.slide(cdp, apple, orange);
+ // The highlight moved through aria-activedescendant; focus never left
+ // the combobox.
+ const orangeId = await page
+ .getByRole('option', {name: 'Orange', exact: true})
+ .getAttribute('id');
+ await expect(combobox).toHaveAttribute(
+ 'aria-activedescendant',
+ orangeId ?? '',
+ );
+ expect(
+ await page.evaluate(
+ () => document.activeElement?.getAttribute('role') ?? null,
+ ),
+ ).toBe('combobox');
+ await touch.end(cdp);
+
+ await expect(listbox).toBeHidden();
+ await expect(combobox).toHaveText(/Orange/);
+ await page.waitForTimeout(400);
+ await expect(combobox).toHaveText(/Orange/);
+ });
+
+ test('mouse: a release outside closes the list without selecting; a finger release outside leaves it open', async ({
+ page,
+ }) => {
+ const cdp = await enableTouch(page);
+ await mount(page, SELECTOR_STORY);
+ const combobox = page.getByRole('combobox');
+ await combobox.click();
+ const listbox = page.getByRole('listbox');
+ await expect(listbox).toBeVisible();
+
+ const apple = await center(page, 'option', 'Apple');
+ await touch.start(cdp, apple);
+ await touch.slide(cdp, apple, {x: apple.x + 400, y: apple.y + 200});
+ await touch.end(cdp);
+ await page.waitForTimeout(300);
+ await expect(listbox).toBeVisible();
+
+ await page.mouse.move(apple.x, apple.y);
+ await page.mouse.down();
+ await page.mouse.move(apple.x + 400, apple.y + 200, {steps: 6});
+ await page.mouse.up();
+ await expect(listbox).toBeHidden();
+ await expect(combobox).toHaveText(/Select a fruit/);
+ });
+});
diff --git a/packages/core/src/DropdownMenu/modules/useMenuPress.spec.md b/packages/core/src/DropdownMenu/modules/useMenuPress.spec.md
new file mode 100644
index 0000000000..9dead61944
--- /dev/null
+++ b/packages/core/src/DropdownMenu/modules/useMenuPress.spec.md
@@ -0,0 +1,274 @@
+---
+schema_version: 3
+template_version: 3
+kind: module
+id: module:DropdownMenu/useMenuPress
+authority: current
+archive_reason: null
+superseded_by: null
+approved_by: cixzhang
+approved_at: 2026-10-02
+owners: [cixzhang, vjeux]
+review_triggers: [public-api, behavior, accessibility]
+verified_by:
+ [
+ packages/core/src/hooks/menuPressGesture.test.ts,
+ packages/core/src/hooks/useMenuPress.test.tsx,
+ packages/core/src/DropdownMenu/DropdownMenu.test.tsx,
+ packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx,
+ packages/core/src/ContextMenu/ContextMenu.test.tsx,
+ packages/core/src/Selector/Selector.test.tsx,
+ packages/core/src/DropdownMenu/__tests__/MenuPress.a11y.chromium.spec.ts,
+ ]
+parent_component: component:DropdownMenu
+references:
+ [
+ architecture:interaction-modality,
+ architecture:public-component-api,
+ architecture:layer-runtime,
+ family:overlay-dismissal,
+ ]
+---
+
+# useMenuPress module contract
+
+## Contract at a glance
+
+| Area | Contract |
+| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | New public hook `useMenuPress` and the pure `menuPressStep` machine it drives, exported from `@astryxdesign/core/hooks`; the marker `data-astryx-menu-press` on every menu or listbox root that mounts it. No consumer prop of DropdownMenu, ContextMenu, DropdownMenuSubMenu or Selector changes. |
+| Behavior | The row under the pointer when it is RELEASED is the row that acts; the highlight follows a held mouse, finger or pen; a mouse released outside closes the menu and a finger leaves it open; the browser's stray click for a tracked gesture never acts; the menu root declares `touch-action` by overflow so the browser decides when a finger is scrolling. |
+| End-user impact | A finger that lands on one menu row and lifts on another acts on the second, once, instead of on the first; a drag inside an open menu picks where it lets go; a mouse that lets go outside dismisses, a finger does not. Keyboard behavior, trigger opening and sub-menu hover are unchanged. |
+| Builder impact | None for consumers of the five surfaces: they mount the model themselves. A component CAN adopt this model only when it meets the eligibility criteria below, and its component contract MUST explicitly name this module and the governed surfaces before mounting `useMenuPress`. The builder supplies an enabled-row selector and a `touch-action` declaration. |
+| Compatibility/readiness | Additive public hook; existing consumer props unchanged; shipped keyboard and trigger behavior unchanged. One deliberate shipped-behavior change (DEC-3): a mouse released outside a menu now dismisses it. jsdom evidence is complete, and real-Chromium evidence covers the touch pan, the finger slide and its stray click; iOS WebKit evidence is not required for this module. Authority: current; `cixzhang` approved the model for explicitly adopting components on 2026-10-02. |
+| Review checks | Reject a row that acts on `pointerdown` or from the browser's click after a tracked release; a second activation reaching a row for one gesture; a highlight that lights two rows; a finger release outside that closes the menu, or a mouse release outside that leaves it open; a menu root without a `touch-action` declaration; a picker whose listbox takes DOM focus for the highlight. |
+| Governing rules | `architecture:interaction-modality` INV2–INV4 (one operable path per modality, hover as enhancement, menus may move focus with the pointer); `architecture:public-component-api` for the new public hook; `architecture:layer-runtime` for the native light dismiss the model leaves in place; `family:overlay-dismissal` for Escape ordering, which this module does not change. |
+
+This table is a review projection; the body below is authoritative.
+
+## Intent
+
+Astryx menus and pickers previously answered the basic pointer questions on their
+own, and none of them watched the finger: a row acted when the browser reported a
+`click`, which a touch browser aims at the row where the touch BEGAN. Sliding from
+one row to another and lifting acted on the first row. This module owns one reusable
+press model: the release decides and the highlight follows the pointer. It is a
+design-system behavior for components that explicitly adopt it, so no product
+carries a separate press controller for an eligible surface.
+
+The module contracts the press model only. Menu anatomy, theming,
+presentation policy, keyboard navigation, trigger opening and item semantics
+stay with the owning component records.
+
+### Adoption eligibility
+
+A component CAN adopt this module only when all of these are true:
+
+- Its open surface presents discrete action or option rows.
+- Moving a held pointer across those rows means previewing the eventual choice.
+- Releasing the pointer identifies one unambiguous enabled row.
+- Dragging has no separate component meaning such as reordering, scrubbing, or
+ direct manipulation.
+
+Eligibility does not cause adoption. Each adopting component contract MUST
+explicitly name `module:DropdownMenu/useMenuPress` and the surfaces and claims
+it governs. Exporting `useMenuPress` does not make every eligible component an
+adopter.
+
+## Compatibility and migration
+
+- Released default preserved: `no` for one behavior (DEC-3: a mouse released
+ outside a menu now dismisses it); `yes` for every consumer prop and every
+ item, divider, section and presentation API
+- Compatibility class: additive public hook and types; behavior change inside
+ the menu family
+- Migration decision: `module:DropdownMenu/useMenuPress/DEC-3`
+
+Consumer migration instructions belong in consumer docs and release notes.
+
+## Ownership boundary
+
+**Owns**
+
+- The gesture state machine (`menuPressStep`): tracking, release and cancel.
+- Document-level pointer tracking by `pointerId` for the gesture in flight.
+- Moving the highlight while a pointer is held: DOM focus in a menu, a
+ caller-supplied callback in a picker.
+- Activating the row under the release the way its own click would, with the
+ release's button and modifier keys, and swallowing the browser's stray click
+ for that gesture.
+- Ending the gesture with nothing acting on `pointercancel`, a second
+ pointer, or the window losing focus.
+- Edge autoscroll of an overflowing menu while a press is tracked in it.
+- The marker `data-astryx-menu-press` on the menu root.
+
+**Does not own / non-goals**
+
+- Aggregate menu anatomy, presentation resolution, item rendering, theming
+ targets — owned by `component:DropdownMenu`, `component:ContextMenu`,
+ `component:Selector`.
+- Whether a row closes the menu when it acts — owned by the row
+ (`hasCloseOnSelect`, checkbox and radio items).
+- Scrolling. The browser decides when a finger is scrolling through the
+ `touch-action` the menu root declares; the module never re-implements a
+ scroll and never listens for `scroll`.
+- Native light dismiss, Escape ordering and focus trapping — owned by
+ `architecture:layer-runtime` and `family:overlay-dismissal`.
+- Opening a menu from its trigger, by any pointer or key — owned by the
+ component that renders the trigger.
+- Keyboard navigation, typeahead and Enter/Space activation — owned by
+ `useListFocus`, `useTypeahead` and the component records.
+- Hover-to-open of sub-menu flyouts — owned by `useMenuHover`.
+- The right mouse button inside a menu: it is not modelled.
+
+## Public API and concepts
+
+| Concept | Closed values or states | Meaning | Default | Owner | Stability |
+| ------------------------ | ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | ---------------------------------- | --------- |
+| gesture phase | `idle`, `tracking` | where the press in flight stands | `idle` | `module:DropdownMenu/useMenuPress` | stable |
+| effect | `none`, `highlight`, `clear`, `act`, `settle` | what one event makes the host do; `settle` carries `stray` (swallow the browser's click) and `dismiss` (close the menu) | — | `module:DropdownMenu/useMenuPress` | stable |
+| pointer type | `mouse`, `touch`, `pen` | the gesture's own pointer; `touch` and `pen` are "a finger" | from the event | `module:DropdownMenu/useMenuPress` | stable |
+| enabled-row selector | caller string | the rows a release may act on; anything else inside the root highlights nothing | required | `module:DropdownMenu/useMenuPress` | stable |
+| highlight | DOM focus, or a caller callback | one lit row; focus with `preventScroll` in a menu, `aria-activedescendant` in a picker | focus | `module:DropdownMenu/useMenuPress` | stable |
+| stray-click window | 400 ms, or the next `pointerdown` | how long after a tracked release the browser's click is still swallowed | `MENU_PRESS_STRAY_CLICK_MS` | `module:DropdownMenu/useMenuPress` | stable |
+| `data-astryx-menu-press` | present or absent | the root carries this model; a host controller of its own stands aside | present on every mounted root | `module:DropdownMenu/useMenuPress` | stable |
+| activation click | `click` with `detail: 0`, the release's button and modifiers | how the model acts on a row, marked for the synchronous extent by `isMenuPressActivation()`; `detail === 0` alone therefore no longer means "keyboard" on a menu row | — | `module:DropdownMenu/useMenuPress` | stable |
+
+## Behavioral contract
+
+| ID | Invariant | Basis | Verification state |
+| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | ------------------ |
+| FR1 | A row MUST act when a press is released over it, never because the press began on it. A press that never left its row is a tap and acts on that row. | macOS and iOS menu behavior; `menuPressGesture.test.ts`, `useMenuPress.test.tsx` | verify |
+| FR2 | While a press is held inside a menu, the highlighted row MUST be the enabled row under the pointer, and nothing MUST be highlighted over a divider, a heading, a disabled row, or outside the menu. A mouse moving with no button down moves the highlight the same way (existing hover-to-focus). | `architecture:interaction-modality` allowed variation for menus; `useMenuPress.test.tsx` | verify |
+| FR3 | A press that began inside a menu and is released outside it MUST act on nothing. Under a mouse the menu MUST then close; under a finger or pen it MUST stay open. | DEC-3; `useMenuPress.test.tsx`, `DropdownMenu.test.tsx`, `Selector.test.tsx` | verify |
+| FR4 | A menu whose rows fit MUST declare `touch-action: none`; one that scrolls MUST declare `touch-action: pan-y` and `overscroll-behavior: contain`. The model MUST treat `pointercancel` and a second pointer as the end of the gesture with nothing acting, and MUST NOT re-implement scrolling. | Browser scroll ownership; `DropdownMenu.test.tsx` touch-action case, `useMenuPress.test.tsx` | verify |
+| FR5 | The click the browser reports for a gesture this model tracked MUST NOT act on any row; only the release acts. A click with no tracked gesture behind it, or one whose `detail` is 0, MUST act on its target as before. The swallower arms at a tracked release and disarms at the next `pointerdown` or after the stray-click window. | One gesture, one activation; `useMenuPress.test.tsx` FR5 suite | verify |
+| FR6 | At most one row of a menu is lit. Under a finger the row a press began on MUST NOT keep a pressed or hovered look once the pointer left it, so menu rows paint `:active` only under `(hover: hover)`. | `DropdownMenuItem.tsx` styles | verify |
+| FR7 | While a press is tracked in a menu that scrolls, a pointer resting within the edge zone of the menu's top or bottom MUST scroll the menu toward that edge and re-read the row under the pointer as the rows move. | `useMenuPress.test.tsx` autoscroll case | verify |
+
+### Transformation and precedence order
+
+- **ORD1 — One press, innermost owner.** A `pointerdown` inside a menu is
+ claimed by the innermost root carrying `data-astryx-menu-press` (a flyout
+ before its parent); the outermost root decides what counts as "inside the
+ menu" for the release.
+- **ORD2 — Release resolution.** Enabled row under the point → `act`; inside
+ the menu or on the trigger with no row → `settle` (stray click swallowed,
+ menu stays); outside → `settle` with `dismiss` only for a mouse.
+- **ORD3 — Activation dispatch.** The model's activation is a `click` with
+ `detail: 0` carrying the release's button and modifiers, dispatched inside
+ a synchronous activation mark; a row that re-dispatches to a control inside
+ it passes; the browser's later click for the gesture is stopped at the
+ window in the capture phase.
+
+### Performance and resources
+
+- **PR1 — Listeners per gesture.** Document listeners for `pointermove`,
+ `pointerup`, `pointercancel`, `pointerdown` and window `blur` are attached
+ at press and removed when the gesture ends; none are live while idle.
+- **PR2 — One swallower.** The window capture `click` listener is installed
+ once per document and armed per gesture.
+- **PR3 — Autoscroll.** One interval while a tracked pointer rests in an
+ edge zone of an overflowing menu; it stops when the pointer leaves the zone,
+ the scroller reaches its edge, or the gesture ends.
+
+## Accessibility contract
+
+- **AR1 — Highlight is focus in a menu.** In a menu the highlighted row is the
+ focused row, moved with `preventScroll`, so keyboard, mouse and finger share
+ one highlight and one paint; a row whose root takes no focus is highlighted
+ through the control inside it.
+- **AR2 — A picker keeps its combobox focus.** In a Selector listbox the model
+ drives `highlightedIndex` and `aria-activedescendant`; DOM focus never moves
+ into the listbox.
+- **AR3 — Assistive activation passes.** A click with `detail === 0` — a
+ keyboard's, a screen reader's, or the model's own dispatch — is never
+ swallowed, so assistive technology activates rows as before. A row that
+ must tell the model's pointer activation from a keyboard's reads
+ `isMenuPressActivation()`, not `detail`.
+- **AR4 — Focus after a pick is the component's.** The model activates the
+ row as its own click would; where focus goes once the menu closes stays
+ with the owning component record and is unchanged by this module.
+
+## Design relationships
+
+No visual representation is introduced. FR6 removes the coarse-pointer
+pressed paint from menu rows so the single focus highlight is the only lit
+row under a finger; the highlight paint itself is the existing focus overlay
+owned by the item components.
+
+## Parent and system relationships
+
+- `component:DropdownMenu` owns the aggregate menu anatomy, presentation
+ resolution, targets and item pipeline; `component:ContextMenu`,
+ `component:Selector` and the sub-menu flyout mount this module and record
+ their own press claims by reference to it.
+- `architecture:interaction-modality` owns modality tracking and focus-return
+ visibility; this module reads them and adds no modality definition.
+- `architecture:layer-runtime` owns native light dismiss, which this module
+ leaves in place: a press outside a `popover="auto"` menu still dismisses it
+ through the browser.
+- `family:overlay-dismissal` owns Escape ordering; unchanged here.
+
+## Verification map
+
+| Contract | Verification | Representative states | Mutation or failure expectation |
+| ---------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- |
+| FR1–FR3, FR5 | `menuPressGesture.test.ts` (one case per transition of the diagram) | idle, tracking; mouse and touch; releases over a row, over chrome, on the trigger, outside; cancel | Acting on the press row, on the stray click, or dismissing under a finger fails a transition case |
+| FR1–FR5, FR7, AR1, AR3 | `useMenuPress.test.tsx` with an injected hit test | release over another row, tap, stray click, `detail: 0`, mouse/finger outside, pointercancel, second pointer, autoscroll | A second activation, a swallowed assistive click, a wrong dismissal, or a dead autoscroll fails |
+| FR1, FR3–FR5 | `DropdownMenu.test.tsx`, `DropdownMenuSubMenu.test.tsx`, `ContextMenu.test.tsx` press suites | finger slide across rows, outside release by mouse and finger, `touch-action`, flyout release, root marker | Each removed behavior fails its named case |
+| FR1, FR3, AR2 | `Selector.test.tsx` press model suite | finger release over another option, finger/mouse release outside, listbox marker | A listbox that takes focus, acts on the press option, or closes under a finger fails |
+| 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 |
+
+## Decision log
+
+### DEC-3 — A release outside closes under a mouse and stays under a finger
+
+**Reference:** `module:DropdownMenu/useMenuPress/DEC-3`
+**Decider:** `vjeux`, `2026-09-27`
+
+macOS ends a menu's tracking on mouse-up: a release outside dismisses. iOS
+leaves a menu presented when the finger that slid off it lifts; a later tap
+outside dismisses. Each pointer keeps its platform's answer. Closing for both
+would make a finger that slid off need a second gesture to reopen; staying
+open for both would surprise a mouse user.
+
+### DEC-6 — The highlight is DOM focus in a menu, `aria-activedescendant` in a picker
+
+**Reference:** `module:DropdownMenu/useMenuPress/DEC-6`
+**Decider:** `vjeux`, `2026-09-27`
+
+Menus already keep one highlight by moving focus on hover; the finger moves
+the same focus with `preventScroll`, so keyboard, mouse and touch share one
+state and one paint. A picker's list belongs to a combobox and must not take
+focus from it. The coarse-pointer pressed paint on menu rows is dropped
+because it would light a second row (FR6). This record does not decide where
+focus goes after a pick.
+
+### DEC-7 — Eligibility permits adoption; component contracts opt in
+
+**Reference:** `module:DropdownMenu/useMenuPress/DEC-7`
+**Decider:** `cixzhang`, `2026-10-02`
+
+A component may adopt this model when its open surface presents discrete action
+or option rows, a held pointer moving across rows previews the eventual choice,
+and release identifies one unambiguous enabled row. A component whose drag has
+a separate meaning, such as reordering, scrubbing, or direct manipulation, is
+not eligible. Eligibility never causes adoption: each component contract names
+this module and the surfaces and claims it governs. The public hook's
+availability alone does not make a component an adopter.
+
+## Open questions
+
+None. OQ1 (browser-only evidence) is resolved: the touch pan, the finger
+slide and its stray click cannot be exercised in jsdom, and real-Chromium
+evidence for them now exists in
+`packages/core/src/DropdownMenu/__tests__/MenuPress.a11y.chromium.spec.ts`.
+`cixzhang` ruled on 2026-10-02 that iOS WebKit evidence is not required for
+this module, now or later; real Chromium is the evidence bar.
+
+## Content boundary
+
+This record does not duplicate `useMenuPress.doc.mjs` signatures, the owning
+components' anatomy or theming, layer or dismissal rules, or implementation
+steps. It links to their canonical owners.
diff --git a/packages/core/src/Selector/Selector.spec.md b/packages/core/src/Selector/Selector.spec.md
index 1a96161e47..85f3227717 100644
--- a/packages/core/src/Selector/Selector.spec.md
+++ b/packages/core/src/Selector/Selector.spec.md
@@ -96,14 +96,15 @@ and examples remain in `Selector.doc.mjs`.
These requirements describe shipped behavior on current `main`.
-| ID | Shipped invariant | Evidence |
-| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
-| FR1 | Selecting an enabled option updates the one selected value, closes the active presentation, and returns the trigger to its stable closed state. | Consumer docs and selection interaction tests |
-| FR2 | Without explicit placement, a non-search popover aligns the selected row over the trigger and clamps it to the viewport. Search popovers and explicit placement use normal Layer positioning. | Consumer docs, implementation, and geometry tests |
-| FR3 | An option whose resolved selection indicator draws no content reserves no mark-column space. Visible selected or themed replacement indicators remain in layout at `indicatorPosition`; the resulting state-dependent label position or available width is intentional, and row content keeps its existing overflow behavior. | `itemMarkColumn`, focused indicator tests, and Chromium evidence stories |
-| FR4 | `popover` uses an anchored Popover. `bottom-sheet` uses a modal BottomSheet. `adaptive` resolves to the modal bottom sheet on compact coarse-pointer screens and Popover otherwise. | Presentation controller and adaptive-presentation tests |
-| FR5 | While `isLoading` is true, the trigger exposes busy state and the listbox suppresses empty and no-results output. | Loading, empty-state, and announcement tests |
-| FR6 | While `isReadOnly` is true, the selected value remains focusable and form-submittable, while the selection surface, clear action, disclosure indicator, and every value-change path are unavailable. | Read-only interaction, form, and accessibility tests |
+| ID | Shipped invariant | Evidence |
+| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
+| FR1 | Selecting an enabled option updates the one selected value, closes the active presentation, and returns the trigger to its stable closed state. | Consumer docs and selection interaction tests |
+| FR2 | Without explicit placement, a non-search popover aligns the selected row over the trigger and clamps it to the viewport. Search popovers and explicit placement use normal Layer positioning. | Consumer docs, implementation, and geometry tests |
+| FR3 | An option whose resolved selection indicator draws no content reserves no mark-column space. Visible selected or themed replacement indicators remain in layout at `indicatorPosition`; the resulting state-dependent label position or available width is intentional, and row content keeps its existing overflow behavior. | `itemMarkColumn`, focused indicator tests, and Chromium evidence stories |
+| FR4 | `popover` uses an anchored Popover. `bottom-sheet` uses a modal BottomSheet. `adaptive` resolves to the modal bottom sheet on compact coarse-pointer screens and Popover otherwise. | Presentation controller and adaptive-presentation tests |
+| FR5 | While `isLoading` is true, the trigger exposes busy state and the listbox suppresses empty and no-results output. | Loading, empty-state, and announcement tests |
+| FR6 | While `isReadOnly` is true, the selected value remains focusable and form-submittable, while the selection surface, clear action, disclosure indicator, and every value-change path are unavailable. | Read-only interaction, form, and accessibility tests |
+| FR7 | The listbox carries `data-astryx-menu-press` and follows `module:DropdownMenu/useMenuPress` FR1–FR3, FR5 and AR2: the option under a pointer's release is the one selected, the highlight follows a held pointer through `aria-activedescendant` while DOM focus stays on the combobox, a mouse released outside closes the list and a finger leaves it open, and the browser's stray click never selects. Trigger opening, arrow clamping and closed-trigger typeahead are unchanged. | `module:DropdownMenu/useMenuPress`; `Selector.test.tsx` press model suite |
### Allowed variation
@@ -272,6 +273,10 @@ new theming target.
size, end-control, disabled-reason, and status-placement policy. Selector
keeps its DEC-1 standalone inline-size exception; this component contract
owns selection behavior inside that boundary.
+- `module:DropdownMenu/useMenuPress` owns the listbox press model FR7 adopts
+ (release-to-select, pointer-following highlight, outside-release split,
+ stray-click swallowing); Selector keeps arrow clamping and its combobox
+ focus (module AR2).
## Verification map
@@ -284,6 +289,7 @@ new theming target.
| AR1, AV2 | `Selector.listbox.a11y.test.tsx` and `Listbox.a11y.chromium.spec.ts` against the shared Listbox contract | popover/sheet, flat/grouped, selected/unselected, disabled, search, loading, custom RTL | A new or wider loss of role, listbox/option name, state, or ownership gates; the exact unnamed no-search sheet state remains known debt | `audit:Selector/accessibility` |
| FR5 | loading, empty-state, and live-region tests | empty options, unmatched search, loading | Empty/no-results output appears or is announced while loading | `audit:Selector/behavior` |
| FR6, AR4 | read-only interaction, form, ARIA, and theme-state tests | search/non-search, clearable, open→read-only, disabled precedence | A value changes, popup or edit affordance remains, form value disappears, or read-only semantics are absent | `audit:Selector/accessibility` |
+| FR7 | `Selector.test.tsx` press model suite | finger release over another option, finger/mouse release outside, listbox marker | The press option is selected, the listbox takes focus, a finger release outside closes the list, or the stray click selects | `audit:Selector/behavior` |
| source-build contract | `Selector.source-build.test.mjs` | package source compiled by consumer Babel | Moving evaluated StyleX values outside the supported source form fails compilation | `audit:Selector/code-health` |
## Decision log
diff --git a/packages/core/src/Selector/Selector.test.tsx b/packages/core/src/Selector/Selector.test.tsx
index 84ec70f995..c19a862bb4 100644
--- a/packages/core/src/Selector/Selector.test.tsx
+++ b/packages/core/src/Selector/Selector.test.tsx
@@ -4396,3 +4396,104 @@ describe('Selector option descriptions and trigger value', () => {
expect(trigger).not.toHaveTextContent('Anyone at the company can join.');
});
});
+
+describe('Selector press model', () => {
+ const touch = {pointerType: 'touch', pointerId: 1};
+ const h = {hidden: true};
+
+ it('a finger release over an option selects it, not the option the press began on', async () => {
+ const onChange = vi.fn();
+ const user = userEvent.setup();
+ render(<Selector label="Fruit" options={OPTIONS} onChange={onChange} />);
+ const trigger = screen.getByRole('combobox');
+ await user.click(trigger);
+
+ const apple = screen.getByRole('option', {name: /Apple/, ...h});
+ const cherry = screen.getByRole('option', {name: /Cherry/, ...h});
+ fireEvent.pointerDown(apple, touch);
+ fireEvent.pointerMove(cherry, touch);
+ // The highlight moves through aria-activedescendant; focus stays put.
+ expect(trigger).toHaveAttribute('aria-activedescendant', cherry.id);
+ expect(cherry).not.toHaveFocus();
+ fireEvent.pointerUp(cherry, touch);
+ // The WebKit tail: a click aimed at the option the touch began on.
+ fireEvent.click(apple, {detail: 1});
+
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith('Cherry');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('a finger released outside acts on nothing and leaves the list open; a mouse closes it', async () => {
+ const onChange = vi.fn();
+ const user = userEvent.setup();
+ render(<Selector label="Fruit" options={OPTIONS} onChange={onChange} />);
+ const trigger = screen.getByRole('combobox');
+ await user.click(trigger);
+ const apple = screen.getByRole('option', {name: /Apple/, ...h});
+
+ fireEvent.pointerDown(apple, touch);
+ fireEvent.pointerUp(document.body, touch);
+ expect(onChange).not.toHaveBeenCalled();
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ fireEvent.pointerDown(apple, {
+ pointerType: 'mouse',
+ pointerId: 2,
+ button: 0,
+ });
+ fireEvent.pointerUp(document.body, {pointerType: 'mouse', pointerId: 2});
+ expect(onChange).not.toHaveBeenCalled();
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('a pointer-driven highlight never scrolls the option into view (the rows would move under the finger)', async () => {
+ const scrollIntoView = vi.fn();
+ const original = Element.prototype.scrollIntoView;
+ Element.prototype.scrollIntoView = scrollIntoView;
+ try {
+ const user = userEvent.setup();
+ render(<Selector label="Fruit" options={OPTIONS} onChange={() => {}} />);
+ await user.click(screen.getByRole('combobox'));
+ scrollIntoView.mockClear();
+ const apple = screen.getByRole('option', {name: /Apple/, ...h});
+ const cherry = screen.getByRole('option', {name: /Cherry/, ...h});
+ fireEvent.pointerDown(apple, touch);
+ fireEvent.pointerMove(cherry, touch);
+ expect(screen.getByRole('combobox')).toHaveAttribute(
+ 'aria-activedescendant',
+ cherry.id,
+ );
+ expect(scrollIntoView).not.toHaveBeenCalled();
+ } finally {
+ Element.prototype.scrollIntoView = original;
+ }
+ });
+
+ it('the listbox owns touch scrolling: touch-action none while the options fit', async () => {
+ const user = userEvent.setup();
+ render(<Selector label="Fruit" options={OPTIONS} onChange={() => {}} />);
+ await user.click(screen.getByRole('combobox'));
+ const listbox = screen.getByRole('listbox', h);
+ // jsdom does not compute `touch-action`; StyleX class names hash the
+ // declaration, so the same declaration yields the same class (the dev
+ // build prefixes a debug name; the hash is the last token).
+ const touchStyles = stylex.create({
+ none: {touchAction: 'none'},
+ panY: {touchAction: 'pan-y'},
+ });
+ const hash = (style: stylex.StyleXStyles) =>
+ stylex.props(style).className!.split(' ').pop()!;
+ expect(listbox).toHaveClass(hash(touchStyles.none));
+ expect(listbox).not.toHaveClass(hash(touchStyles.panY));
+ });
+
+ it('marks the listbox as carrying the press model', async () => {
+ const user = userEvent.setup();
+ render(<Selector label="Fruit" options={OPTIONS} onChange={() => {}} />);
+ await user.click(screen.getByRole('combobox'));
+ expect(screen.getByRole('listbox', h)).toHaveAttribute(
+ 'data-astryx-menu-press',
+ );
+ });
+});
diff --git a/packages/core/src/Selector/Selector.tsx b/packages/core/src/Selector/Selector.tsx
index ffb5eee0e7..f87136df9f 100644
--- a/packages/core/src/Selector/Selector.tsx
+++ b/packages/core/src/Selector/Selector.tsx
@@ -71,6 +71,8 @@ import {
getSelectableOptions,
} from './utils';
import {useCombobox, useSelectedItemOffset} from './hooks';
+import {useMenuPress} from '../hooks/useMenuPress';
+import {useMenuOverflow} from '../DropdownMenu/useMenuOverflow';
import {useTypeahead} from '../hooks/useTypeahead';
import {useResolvedRequired} from '../hooks/useResolvedRequired';
import {SelectorOption} from './SelectorOption';
@@ -297,6 +299,17 @@ const styles = stylex.create({
// pixel in the menu; the borderless ghost variant needs no correction.
paddingInline: `calc(${spacingVars['--spacing-1']} + ${borderVars['--border-width']})`,
},
+ // Scroll ownership by the browser's own signal, as the menus declare it: a
+ // list whose options fit keeps every finger, so a slide over the options
+ // stays a slide; one that scrolls lets the browser pan it vertically and
+ // cancel the press when it does.
+ touchNone: {
+ touchAction: 'none',
+ },
+ touchPanY: {
+ touchAction: 'pan-y',
+ overscrollBehavior: 'contain',
+ },
// Same correction for the search row's gutter, so the search field and the
// option rows share one left edge.
searchRowInput: {
@@ -1253,6 +1266,48 @@ export function Selector<T extends SelectorOptionType>(
});
resetTypeaheadRef.current = typeahead.reset;
+ // The press model for the listbox: the option under a finger's or
+ // a mouse's RELEASE is the one picked, and the highlight follows a held
+ // pointer through `highlightedIndex` — DOM focus stays on the trigger, as a
+ // combobox's must. A mouse released outside dismisses the list; a finger
+ // leaves it open.
+ const optionIndexFromRow = useCallback((row: HTMLElement): number => {
+ const match = /-item-(\d+)$/.exec(row.id);
+ return match == null ? -1 : Number(match[1]);
+ }, []);
+ // Re-measured when the option set changes; the count is the dependency.
+ const listboxHasOverflow = useMenuOverflow(
+ listboxRef,
+ filteredItems.length,
+ surface.isOpen,
+ );
+ const listboxPress = useMenuPress({
+ menuRef: listboxRef,
+ itemSelector: '[role="option"]:not([aria-disabled="true"])',
+ onHighlight: row => {
+ if (row == null) {
+ setHighlightedIndex(-1);
+ return;
+ }
+ // The hover path, not the raw setter: a pointer-driven highlight must
+ // never scroll the option into view, or the rows move under the
+ // stationary finger and the highlight runs away (the same rule hover
+ // follows).
+ const index = optionIndexFromRow(row);
+ const item = filteredItems[index];
+ if (item != null) {
+ onItemMouseEnter(item, index);
+ }
+ },
+ onActivate: row => {
+ const item = filteredItems[optionIndexFromRow(row)];
+ if (item != null) {
+ onItemSelect(item);
+ }
+ },
+ onDismiss: surface.hide,
+ });
+
const handleTriggerKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (isDisabled || isEffectivelyReadOnly) {
@@ -1639,8 +1694,10 @@ export function Selector<T extends SelectorOptionType>(
id={listboxId}
role="listbox"
aria-labelledby={triggerId}
+ {...listboxPress.menuProps}
{...stylex.props(
styles.dropdown,
+ listboxHasOverflow ? styles.touchPanY : styles.touchNone,
surface.activePresentation === 'popover' &&
variant !== 'ghost' &&
styles.dropdownInput,
@@ -1653,6 +1710,7 @@ export function Selector<T extends SelectorOptionType>(
ref={listboxRef}
id={listboxId}
role="listbox"
+ {...listboxPress.menuProps}
// The bottom sheet is a modal layer, so Chromium drops the trigger
// outside it from the accessibility tree and a reference to it yields
// no name. Name only this no-search sheet directly from the component's
@@ -1677,6 +1735,7 @@ export function Selector<T extends SelectorOptionType>(
}
{...stylex.props(
styles.dropdown,
+ listboxHasOverflow ? styles.touchPanY : styles.touchNone,
surface.activePresentation === 'popover' &&
variant !== 'ghost' &&
styles.dropdownInput,
diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.ts
index 6f2bcf51b1..24603d4524 100644
--- a/packages/core/src/hooks/index.ts
+++ b/packages/core/src/hooks/index.ts
@@ -38,6 +38,21 @@ export type {Hotkey} from './useHotkeys';
export {useTypeahead} from './useTypeahead';
+export {
+ useMenuPress,
+ MENU_PRESS_MARKER,
+ isMenuPressActivation,
+} from './useMenuPress';
+export type {UseMenuPressOptions, UseMenuPressReturn} from './useMenuPress';
+export {menuPressStep} from './menuPressGesture';
+export type {
+ MenuPressEffect,
+ MenuPressEvent,
+ MenuPressGesture,
+ MenuPressPointerType,
+ MenuPressStep,
+} from './menuPressGesture';
+
export {useKeyboardHint} from './useKeyboardHint';
export type {
UseKeyboardHintOptions,
diff --git a/packages/core/src/hooks/menuPressGesture.test.ts b/packages/core/src/hooks/menuPressGesture.test.ts
new file mode 100644
index 0000000000..43bb2e0117
--- /dev/null
+++ b/packages/core/src/hooks/menuPressGesture.test.ts
@@ -0,0 +1,127 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file menuPressGesture.test.ts
+ * @input vitest, the pure menuPressStep machine
+ * @output One test per transition of the press-model state diagram (a press
+ * inside the menu; the trigger states have their own suite)
+ * @position Testing; validates menuPressGesture.ts without a browser
+ */
+
+import {describe, it, expect} from 'vitest';
+import {
+ IDLE_MENU_PRESS,
+ menuPressStep,
+ type MenuPressEvent,
+ type MenuPressGesture,
+} from './menuPressGesture';
+
+type Row = 'A' | 'B';
+
+function run(events: MenuPressEvent<Row>[]) {
+ let gesture: MenuPressGesture<Row> = IDLE_MENU_PRESS;
+ const effects = [];
+ for (const event of events) {
+ const step = menuPressStep(gesture, event);
+ gesture = step.gesture;
+ effects.push(step.effect);
+ }
+ return {gesture, effects, last: effects[effects.length - 1]};
+}
+
+const downInMenu = (
+ row: Row | null,
+ pointerType: 'mouse' | 'touch' = 'touch',
+) => ({type: 'down', pointerType, row, time: 0}) as const;
+const move = (row: Row | null, isInMenu = true, time = 10) =>
+ ({type: 'move', row, isInMenu, time}) as const;
+const up = (
+ row: Row | null,
+ {
+ isInMenu = row != null,
+ isOnTrigger = false,
+ time = 20,
+ }: {isInMenu?: boolean; isOnTrigger?: boolean; time?: number} = {},
+) => ({type: 'up', row, isInMenu, isOnTrigger, time}) as const;
+
+describe('menuPressStep — inside the menu', () => {
+ it('Idle → Tracking: a pointer down inside the menu highlights the row under it', () => {
+ const {gesture, last} = run([downInMenu('A')]);
+ expect(gesture.phase).toBe('tracking');
+ expect(last).toEqual({type: 'highlight', row: 'A'});
+ });
+
+ it('Idle → Tracking: a pointer down over a divider highlights nothing', () => {
+ const {gesture, last} = run([downInMenu(null)]);
+ expect(gesture.phase).toBe('tracking');
+ expect(last).toEqual({type: 'clear'});
+ });
+
+ it('Tracking → Tracking: a move onto another row moves the highlight', () => {
+ const {last} = run([downInMenu('A'), move('B')]);
+ expect(last).toEqual({type: 'highlight', row: 'B'});
+ });
+
+ it('Tracking → Tracking: a move over a disabled row or a heading clears the highlight', () => {
+ const {last} = run([downInMenu('A'), move(null)]);
+ expect(last).toEqual({type: 'clear'});
+ });
+
+ it('Tracking → Tracking: a move within the same row changes nothing', () => {
+ const {last} = run([downInMenu('A'), move('A')]);
+ expect(last).toEqual({type: 'none'});
+ });
+
+ it('Tracking → Acted: a release over an enabled row acts on THAT row, not the one pressed', () => {
+ const {gesture, last} = run([downInMenu('A'), move('B'), up('B')]);
+ expect(last).toEqual({type: 'act', row: 'B'});
+ expect(gesture.phase).toBe('idle');
+ });
+
+ it('a tap that never left its row acts on that row and swallows nothing else', () => {
+ const {last} = run([downInMenu('A'), up('A')]);
+ expect(last).toEqual({type: 'act', row: 'A'});
+ });
+
+ it('Tracking → Idle: a release over a divider, heading or disabled row acts on nothing and keeps the menu', () => {
+ const {last} = run([
+ downInMenu('A'),
+ move(null),
+ up(null, {isInMenu: true}),
+ ]);
+ expect(last).toEqual({type: 'settle', stray: true, dismiss: false});
+ });
+
+ it('Tracking → Released → Idle: a MOUSE released outside acts on nothing and dismisses', () => {
+ const {last} = run([
+ downInMenu('A', 'mouse'),
+ move(null, false),
+ up(null, {isInMenu: false}),
+ ]);
+ expect(last).toEqual({type: 'settle', stray: true, dismiss: true});
+ });
+
+ it('Tracking → Released → Idle: a FINGER released outside acts on nothing and leaves the menu open', () => {
+ const {last} = run([
+ downInMenu('A', 'touch'),
+ move(null, false),
+ up(null, {isInMenu: false}),
+ ]);
+ expect(last).toEqual({type: 'settle', stray: true, dismiss: false});
+ });
+
+ it('Tracking → Idle: a cancel (scroll, second pointer, browser) acts on nothing', () => {
+ const {gesture, last} = run([downInMenu('A'), move('B'), {type: 'cancel'}]);
+ expect(gesture.phase).toBe('idle');
+ expect(last).toEqual({type: 'settle', stray: false, dismiss: false});
+ });
+
+ it('ignores a move or a release with no gesture live', () => {
+ expect(menuPressStep(IDLE_MENU_PRESS, move('A')).effect).toEqual({
+ type: 'none',
+ });
+ expect(menuPressStep(IDLE_MENU_PRESS, up('A')).effect).toEqual({
+ type: 'none',
+ });
+ });
+});
diff --git a/packages/core/src/hooks/menuPressGesture.ts b/packages/core/src/hooks/menuPressGesture.ts
new file mode 100644
index 0000000000..6ddc353313
--- /dev/null
+++ b/packages/core/src/hooks/menuPressGesture.ts
@@ -0,0 +1,162 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file menuPressGesture.ts
+ * @input A menu press gesture and one pointer event, both as plain data
+ * @output Exports the pure `menuPressStep` state machine, its state, event and
+ * effect types, and the settle constant
+ * @position Pure module under `useMenuPress`; no DOM, no React, so every
+ * transition is unit-testable without a browser
+ *
+ * The press model shared by every Astryx menu and picker: the row under the
+ * pointer when it is RELEASED is the row that acts, and the highlight follows
+ * the pointer while it is held. It is the model of macOS and iOS menus.
+ *
+ * States:
+ * - `idle` — no gesture is live.
+ * - `tracking` — a pointer is held inside the menu and the highlight follows
+ * it.
+ *
+ * Rows are opaque (`T`): the machine never touches the DOM. The hook resolves
+ * the enabled row under the pointer and feeds it in; `null` means the pointer
+ * is over a divider, a heading, a disabled row, or outside the menu.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/hooks/menuPressGesture.test.ts
+ * - /packages/core/src/hooks/useMenuPress.ts
+ */
+
+export type MenuPressPointerType = 'mouse' | 'touch' | 'pen';
+
+export type MenuPressGesture<T> =
+ | {phase: 'idle'}
+ | {
+ phase: 'tracking';
+ pointerType: MenuPressPointerType;
+ /** The enabled row currently under the pointer, if any. */
+ row: T | null;
+ };
+
+export type MenuPressEvent<T> =
+ | {
+ type: 'down';
+ pointerType: MenuPressPointerType;
+ /** The enabled row under the press, if any. */
+ row: T | null;
+ time: number;
+ }
+ | {type: 'move'; row: T | null; isInMenu: boolean; time: number}
+ | {
+ type: 'up';
+ row: T | null;
+ isInMenu: boolean;
+ isOnTrigger: boolean;
+ time: number;
+ }
+ /** The browser took the gesture: pointercancel, a second pointer, a scroll. */
+ | {type: 'cancel'};
+
+export type MenuPressEffect<T> =
+ | {type: 'none'}
+ | {type: 'highlight'; row: T}
+ | {type: 'clear'}
+ | {type: 'act'; row: T}
+ /**
+ * The gesture ended without a row acting. `stray` says whether the browser
+ * will still report a `click` for this gesture that must not act; `dismiss`
+ * says the menu should close (a mouse released outside it).
+ */
+ | {type: 'settle'; stray: boolean; dismiss: boolean};
+
+export interface MenuPressStep<T> {
+ gesture: MenuPressGesture<T>;
+ effect: MenuPressEffect<T>;
+}
+
+export const IDLE_MENU_PRESS: MenuPressGesture<never> = {phase: 'idle'};
+
+const NONE: MenuPressEffect<never> = {type: 'none'};
+
+function idle<T>(effect: MenuPressEffect<T>): MenuPressStep<T> {
+ return {gesture: {phase: 'idle'}, effect};
+}
+
+function highlightEffect<T>(row: T | null): MenuPressEffect<T> {
+ return row == null ? {type: 'clear'} : {type: 'highlight', row};
+}
+
+/**
+ * Resolve a release while the highlight is tracking the pointer: over an
+ * enabled row it acts, over the menu's chrome it acts on nothing, outside the
+ * menu it acts on nothing and — under a mouse — dismisses the menu (a
+ * finger leaves it open). A release back on the trigger never dismisses.
+ */
+function release<T>(
+ pointerType: MenuPressPointerType,
+ event: Extract<MenuPressEvent<T>, {type: 'up'}>,
+): MenuPressStep<T> {
+ if (event.row != null) {
+ return idle({type: 'act', row: event.row});
+ }
+ if (event.isInMenu || event.isOnTrigger) {
+ return idle({type: 'settle', stray: true, dismiss: false});
+ }
+ return idle({type: 'settle', stray: true, dismiss: pointerType === 'mouse'});
+}
+
+/**
+ * Advance the gesture by one event. Pure: same inputs, same output.
+ */
+export function menuPressStep<T>(
+ gesture: MenuPressGesture<T>,
+ event: MenuPressEvent<T>,
+): MenuPressStep<T> {
+ switch (gesture.phase) {
+ case 'idle':
+ return stepIdle(gesture, event);
+ case 'tracking':
+ return stepTracking(gesture, event);
+ }
+}
+
+function stepIdle<T>(
+ gesture: Extract<MenuPressGesture<T>, {phase: 'idle'}>,
+ event: MenuPressEvent<T>,
+): MenuPressStep<T> {
+ if (event.type !== 'down') {
+ return {gesture, effect: NONE};
+ }
+ return {
+ gesture: {
+ phase: 'tracking',
+ pointerType: event.pointerType,
+ row: event.row,
+ },
+ effect: highlightEffect(event.row),
+ };
+}
+
+function stepTracking<T>(
+ gesture: Extract<MenuPressGesture<T>, {phase: 'tracking'}>,
+ event: MenuPressEvent<T>,
+): MenuPressStep<T> {
+ switch (event.type) {
+ case 'move': {
+ if (event.row === gesture.row) {
+ return {gesture, effect: NONE};
+ }
+ return {
+ gesture: {...gesture, row: event.row},
+ effect: highlightEffect(event.row),
+ };
+ }
+ case 'up':
+ return release(gesture.pointerType, event);
+ case 'cancel':
+ // The browser took the gesture (a scroll, a second finger): nothing
+ // acts, the menu stays, and no click follows a cancelled pointer.
+ return idle({type: 'settle', stray: false, dismiss: false});
+ case 'down':
+ return {gesture, effect: NONE};
+ }
+}
diff --git a/packages/core/src/hooks/useMenuPress.doc.mjs b/packages/core/src/hooks/useMenuPress.doc.mjs
new file mode 100644
index 0000000000..b386a6565d
--- /dev/null
+++ b/packages/core/src/hooks/useMenuPress.doc.mjs
@@ -0,0 +1,183 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').HookDoc} */
+export const docs = {
+ name: 'useMenuPress',
+ displayName: 'useMenuPress',
+ keywords: [
+ 'menu',
+ 'press',
+ 'release',
+ 'touch',
+ 'finger',
+ 'drag',
+ 'highlight',
+ 'pointer',
+ 'gesture',
+ 'listbox',
+ 'macos',
+ 'ios',
+ ],
+ params: [
+ {
+ name: 'options',
+ type: 'UseMenuPressOptions',
+ description: 'Configuration object.',
+ required: true,
+ },
+ {
+ name: 'options.menuRef',
+ type: 'RefObject<HTMLElement | null>',
+ description:
+ 'The menu or listbox root — the surface whose rows a press picks from.',
+ required: true,
+ },
+ {
+ name: 'options.itemSelector',
+ type: 'string',
+ description:
+ 'Selector matching the ENABLED rows. A pointer over anything else inside the menu (a divider, a heading, a disabled row) highlights nothing.',
+ required: true,
+ },
+ {
+ name: 'options.triggerRef',
+ type: 'RefObject<HTMLElement | null>',
+ description:
+ 'The control that opens the menu. A release over it is not outside: it acts on nothing and leaves the menu open under every pointer.',
+ },
+ {
+ name: 'options.onHighlight',
+ type: '(row: HTMLElement | null) => void',
+ description:
+ 'Move the highlight; null clears it. Defaults to moving DOM focus with preventScroll onto the row, and onto the menu root when there is no row. A picker that highlights through aria-activedescendant supplies its own.',
+ },
+ {
+ name: 'options.onActivate',
+ type: '(row: HTMLElement, release: PointerEvent) => void',
+ description:
+ 'Act on the row under the release. Defaults to dispatching a click on the row that carries the release button and modifier keys.',
+ },
+ {
+ name: 'options.onDismiss',
+ type: '() => void',
+ description:
+ 'A MOUSE was released outside the menu with nothing acting: close it. A finger released outside leaves the menu open, so this is never called then.',
+ },
+ {
+ name: 'options.getScroller',
+ type: '() => HTMLElement | null',
+ description:
+ 'The element to scroll while a tracked pointer rests near its top or bottom edge. Defaults to the menu root when it overflows.',
+ },
+ {
+ name: 'options.isEnabled',
+ type: 'boolean',
+ description: 'Whether the model is live.',
+ default: 'true',
+ },
+ ],
+ returns: [
+ {
+ name: 'menuProps',
+ type: '{onPointerDown; "data-astryx-menu-press": ""}',
+ description:
+ 'Spread onto the menu root. Claims presses that begin inside it and marks the root as carrying the press model.',
+ },
+ {
+ name: 'cancel',
+ type: '() => void',
+ description:
+ 'End the gesture in flight with nothing acting, for when the menu closes under it.',
+ },
+ ],
+ usage: {
+ description:
+ 'The press model of macOS and iOS menus, for any pointer: the row under the pointer when it is RELEASED is the row that acts, and the highlight follows the pointer while it is held. The pointer is tracked at document level by pointerId, so a finger that slid off the row it landed on is still followed; the click the browser reports at the end of a touch, aimed at the row where the touch began, is swallowed so nothing acts twice. DropdownMenu, ContextMenu, DropdownMenuSubMenu, Selector and the menu bottom sheet already mount it; reach for it directly only when building a menu-like surface of your own.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Pass a selector for ENABLED rows only, so a disabled row or a divider under the pointer clears the highlight instead of lighting up.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Let the default highlight move focus in a menu; supply onHighlight only for a listbox that must keep focus on its combobox and highlight through aria-activedescendant.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Declare touch-action on the menu root: none when its rows fit, pan-y when it scrolls, so the browser — not the hook — decides when a finger is scrolling.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Act on a row from its own pointerdown or pointerup handler as well; the hook already activates the row under the release, and a second path acts twice.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Read a row click with detail 0 as a keyboard activation; the hook dispatches its pointer activation with detail 0 too. Use isMenuPressActivation() to tell them apart.',
+ },
+ ],
+ },
+ relatedComponents: ['DropdownMenu', 'ContextMenu', 'Selector'],
+ relatedHooks: ['useListFocus', 'useTypeahead', 'useLongPress'],
+ importPath: '@astryxdesign/core/hooks',
+ category: 'interaction',
+};
+
+/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
+export const docsDense = {
+ description:
+ 'macOS/iOS menu press model for any pointer: the row under the RELEASE acts, the highlight follows a held pointer. Document-level pointerId tracking; the browser stray click after a touch is swallowed. Already mounted by DropdownMenu / ContextMenu / DropdownMenuSubMenu / Selector / menu bottom sheet.',
+ paramDescriptions: {
+ options: 'config.',
+ 'options.menuRef': 'menu / listbox root.',
+ 'options.itemSelector': 'selector for ENABLED rows; anything else clears.',
+ 'options.triggerRef':
+ 'the control that opens the menu; a release over it is not outside.',
+ 'options.onHighlight':
+ 'move highlight (null clears); default = focus w/ preventScroll, menu root when no row.',
+ 'options.onActivate':
+ 'act on row under release; default = dispatch click w/ release button + modifiers.',
+ 'options.onDismiss': 'MOUSE released outside: close. Finger: never called.',
+ 'options.getScroller':
+ 'element to edge-autoscroll while tracking; default = menu root if it overflows.',
+ 'options.isEnabled': 'false = inert.',
+ },
+ returnDescriptions: {
+ menuProps: 'spread on menu root (claims presses, marks the root).',
+ cancel: 'end the gesture w/o acting.',
+ },
+ usage: {
+ description:
+ 'Release decides; highlight follows the pointer. Use directly only for a menu-like surface of your own.',
+ bestPractices: [
+ {
+ guidance: true,
+ description: 'itemSelector = ENABLED rows only.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Default focus highlight in menus; onHighlight only for aria-activedescendant listboxes.',
+ },
+ {
+ guidance: true,
+ description:
+ 'touch-action on the root: none when rows fit, pan-y when it scrolls.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Also act on pointerdown / pointerup in the row; the hook already acts on release.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Treat a detail-0 row click as keyboard; the hook dispatches w/ detail 0 too — use isMenuPressActivation().',
+ },
+ ],
+ },
+};
diff --git a/packages/core/src/hooks/useMenuPress.test.tsx b/packages/core/src/hooks/useMenuPress.test.tsx
new file mode 100644
index 0000000000..d9bc80d4e6
--- /dev/null
+++ b/packages/core/src/hooks/useMenuPress.test.tsx
@@ -0,0 +1,377 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useMenuPress.test.tsx
+ * @input vitest, @testing-library/react, useMenuPress
+ * @output Unit tests for the DOM half of the menu press model: tracking,
+ * highlight, activation, the stray-click swallower, dismissal and edge
+ * autoscroll
+ * @position Testing; validates useMenuPress.ts. The transition table itself
+ * is covered by menuPressGesture.test.ts.
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {act, fireEvent, render, screen} from '@testing-library/react';
+import {useRef, useState} from 'react';
+import {
+ MENU_PRESS_AUTOSCROLL_ZONE_PX,
+ MENU_PRESS_STRAY_CLICK_MS,
+ __resetMenuPressForTest,
+ useMenuPress,
+} from './useMenuPress';
+
+const ITEM_SELECTOR = '[role="menuitem"]:not([aria-disabled="true"])';
+
+interface HarnessProps {
+ onSelect?: (label: string) => void;
+ onDismiss?: () => void;
+ onOpenChange?: (isOpen: boolean) => void;
+ hitTest?: (x: number, y: number) => Element | null;
+ getScroller?: () => HTMLElement | null;
+ onHighlight?: (row: HTMLElement | null) => void;
+}
+
+function Harness({
+ onSelect,
+ onDismiss,
+ onOpenChange,
+ hitTest,
+ getScroller,
+ onHighlight,
+}: HarnessProps) {
+ const menuRef = useRef<HTMLDivElement>(null);
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ const [isOpen, setIsOpen] = useState(false);
+ const open = (next: boolean) => {
+ setIsOpen(next);
+ onOpenChange?.(next);
+ };
+ const press = useMenuPress({
+ menuRef,
+ triggerRef,
+ itemSelector: ITEM_SELECTOR,
+ onDismiss,
+ hitTest,
+ getScroller,
+ onHighlight,
+ });
+ return (
+ <>
+ <button
+ type="button"
+ ref={triggerRef}
+ aria-expanded={isOpen}
+ onClick={() => open(!isOpen)}>
+ Open
+ </button>
+ <div ref={menuRef} role="menu" tabIndex={-1} {...press.menuProps}>
+ {['A', 'B', 'C'].map(label => (
+ <div
+ key={label}
+ role="menuitem"
+ tabIndex={-1}
+ onClick={() => onSelect?.(label)}>
+ {label}
+ </div>
+ ))}
+ <div
+ role="menuitem"
+ aria-disabled="true"
+ onClick={() => onSelect?.('D')}>
+ D (disabled)
+ </div>
+ <div role="separator" data-testid="divider" />
+ </div>
+ <button type="button" data-testid="outside">
+ Outside
+ </button>
+ </>
+ );
+}
+
+const row = (label: string) => screen.getByRole('menuitem', {name: label});
+const touch = (pointerId = 1) => ({pointerType: 'touch', pointerId});
+const mouse = (pointerId = 1) => ({pointerType: 'mouse', pointerId, button: 0});
+
+beforeEach(() => {
+ __resetMenuPressForTest();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+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();
+ render(<Harness onSelect={onSelect} />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerMove(row('B'), touch());
+ fireEvent.pointerUp(row('B'), touch());
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ expect(onSelect).toHaveBeenCalledWith('B');
+ });
+
+ it('resolves the row through the hit test, not the event target (a finger stays with the element it landed on)', () => {
+ const onSelect = vi.fn();
+ render(
+ <Harness
+ onSelect={onSelect}
+ hitTest={(_x, y) => (y > 50 ? row('C') : row('A'))}
+ />,
+ );
+ // Every event is aimed at A, as a real finger's would be.
+ fireEvent.pointerDown(row('A'), {...touch(), clientY: 10});
+ fireEvent.pointerMove(row('A'), {...touch(), clientY: 80});
+ expect(row('C')).toHaveFocus();
+ fireEvent.pointerUp(row('A'), {...touch(), clientY: 80});
+ expect(onSelect).toHaveBeenCalledWith('C');
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ });
+
+ it('moves the highlight as focus with preventScroll', () => {
+ render(<Harness />);
+ const b = row('B');
+ const focusSpy = vi.spyOn(b, 'focus');
+ fireEvent.pointerDown(row('A'), touch());
+ expect(row('A')).toHaveFocus();
+ fireEvent.pointerMove(b, touch());
+ expect(b).toHaveFocus();
+ expect(focusSpy).toHaveBeenCalledWith({preventScroll: true});
+ });
+
+ it('clears the highlight over a disabled row or a divider and acts on nothing there', () => {
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ const menu = screen.getByRole('menu');
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerMove(row('D (disabled)'), touch());
+ expect(menu).toHaveFocus();
+ fireEvent.pointerMove(screen.getByTestId('divider'), touch());
+ expect(menu).toHaveFocus();
+ fireEvent.pointerUp(screen.getByTestId('divider'), touch());
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+
+ it('drives a custom highlight callback instead of focus when given one (a picker)', () => {
+ const onHighlight = vi.fn<(row: HTMLElement | null) => void>();
+ render(<Harness onHighlight={onHighlight} />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerMove(row('B'), touch());
+ fireEvent.pointerMove(screen.getByTestId('divider'), touch());
+ expect(
+ onHighlight.mock.calls.map(([el]) => el?.textContent ?? null),
+ ).toEqual(['A', 'B', null]);
+ expect(row('A')).not.toHaveFocus();
+ });
+
+ it('carries the release button and modifiers on the dispatched activation', () => {
+ const clicks: MouseEvent[] = [];
+ render(<Harness />);
+ const b = row('B');
+ b.addEventListener('click', e => clicks.push(e));
+ fireEvent.pointerDown(row('A'), mouse());
+ fireEvent.pointerUp(b, {...mouse(), metaKey: true, shiftKey: true});
+ expect(clicks).toHaveLength(1);
+ expect(clicks[0].metaKey).toBe(true);
+ expect(clicks[0].shiftKey).toBe(true);
+ expect(clicks[0].detail).toBe(0);
+ });
+});
+
+describe('useMenuPress — one gesture, one activation', () => {
+ it('a tap on a row acts once even though the browser also reports a click', () => {
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerUp(row('A'), touch());
+ // The WebKit tail: a click at the touch-start point.
+ fireEvent.click(row('A'), {detail: 1});
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ expect(onSelect).toHaveBeenCalledWith('A');
+ });
+
+ it('swallows the stray click at the window before any document listener sees it', () => {
+ const onSelect = vi.fn();
+ const documentListener = vi.fn();
+ document.addEventListener('click', documentListener, true);
+ try {
+ render(<Harness onSelect={onSelect} />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerMove(row('B'), touch());
+ fireEvent.pointerUp(row('B'), touch());
+ documentListener.mockClear();
+ const clickEvent = new MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ detail: 1,
+ });
+ row('A').dispatchEvent(clickEvent);
+ expect(clickEvent.defaultPrevented).toBe(true);
+ expect(documentListener).not.toHaveBeenCalled();
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ expect(onSelect).toHaveBeenCalledWith('B');
+ } finally {
+ document.removeEventListener('click', documentListener, true);
+ }
+ });
+
+ it('lets a click with detail 0 (a keyboard or screen reader activation) through', () => {
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerUp(row('A'), touch());
+ fireEvent.click(row('B'), {detail: 0});
+ expect(onSelect).toHaveBeenCalledTimes(2);
+ expect(onSelect).toHaveBeenLastCalledWith('B');
+ });
+
+ it('lets a click with no tracked gesture behind it act as it always did', () => {
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ fireEvent.click(row('A'), {detail: 1});
+ expect(onSelect).toHaveBeenCalledWith('A');
+ });
+
+ it('disarms the swallower at the next pointer press, so a later tap is never eaten', () => {
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerUp(row('A'), touch());
+ // A new gesture begins elsewhere before the stray click ever arrived.
+ fireEvent.pointerDown(screen.getByTestId('outside'), touch(2));
+ fireEvent.click(row('B'), {detail: 1});
+ expect(onSelect).toHaveBeenCalledTimes(2);
+ expect(onSelect).toHaveBeenLastCalledWith('B');
+ });
+
+ it('disarms the swallower after the short window', () => {
+ vi.useFakeTimers();
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerUp(row('A'), touch());
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_STRAY_CLICK_MS + 1);
+ });
+ fireEvent.click(row('B'), {detail: 1});
+ expect(onSelect).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe('useMenuPress — release outside and cancellation', () => {
+ it('a mouse released outside acts on nothing and dismisses the menu', () => {
+ const onSelect = vi.fn();
+ const onDismiss = vi.fn();
+ render(<Harness onSelect={onSelect} onDismiss={onDismiss} />);
+ fireEvent.pointerDown(row('A'), mouse());
+ fireEvent.pointerMove(screen.getByTestId('outside'), mouse());
+ fireEvent.pointerUp(screen.getByTestId('outside'), mouse());
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ });
+
+ it('a finger released outside acts on nothing and leaves the menu open', () => {
+ const onSelect = vi.fn();
+ const onDismiss = vi.fn();
+ render(<Harness onSelect={onSelect} onDismiss={onDismiss} />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerMove(screen.getByTestId('outside'), touch());
+ fireEvent.pointerUp(screen.getByTestId('outside'), touch());
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(onDismiss).not.toHaveBeenCalled();
+ });
+
+ it('a pointercancel ends the gesture without acting', () => {
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ fireEvent.pointerDown(row('A'), touch());
+ fireEvent.pointerMove(row('B'), touch());
+ fireEvent.pointerCancel(row('A'), touch());
+ fireEvent.pointerUp(row('B'), touch());
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+
+ it('a second pointer ends the gesture and does not start another', () => {
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ fireEvent.pointerDown(row('A'), touch(1));
+ fireEvent.pointerDown(row('B'), touch(2));
+ fireEvent.pointerUp(row('B'), touch(2));
+ fireEvent.pointerUp(row('C'), touch(1));
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+
+ it('ignores a pointer of another id while one is tracked', () => {
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ fireEvent.pointerDown(row('A'), touch(1));
+ fireEvent.pointerMove(row('C'), touch(7));
+ expect(row('A')).toHaveFocus();
+ fireEvent.pointerUp(row('C'), touch(7));
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+});
+
+describe('useMenuPress — the trigger and the marker', () => {
+ it('a mouse released back on the trigger acts on nothing and leaves the menu open', () => {
+ const onSelect = vi.fn();
+ const onDismiss = vi.fn();
+ render(<Harness onSelect={onSelect} onDismiss={onDismiss} />);
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(row('A'), mouse());
+ fireEvent.pointerMove(trigger, mouse());
+ fireEvent.pointerUp(trigger, mouse());
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(onDismiss).not.toHaveBeenCalled();
+ });
+
+ it('marks the menu root as carrying the press model', () => {
+ render(<Harness />);
+ expect(screen.getByRole('menu')).toHaveAttribute('data-astryx-menu-press');
+ });
+});
+
+describe('useMenuPress — edge autoscroll', () => {
+ it('a pointer resting near the bottom edge scrolls the menu down and stops when it leaves the zone', () => {
+ vi.useFakeTimers();
+ render(<Harness getScroller={() => screen.getByRole('menu')} />);
+ const menu = screen.getByRole('menu');
+ vi.spyOn(menu, 'getBoundingClientRect').mockReturnValue({
+ top: 0,
+ bottom: 100,
+ left: 0,
+ right: 200,
+ width: 200,
+ height: 100,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ });
+ fireEvent.pointerDown(row('A'), {...touch(), clientY: 50});
+ expect(menu.scrollTop).toBe(0);
+ fireEvent.pointerMove(row('A'), {
+ ...touch(),
+ clientY: 100 - MENU_PRESS_AUTOSCROLL_ZONE_PX / 2,
+ });
+ const afterFirst = menu.scrollTop;
+ expect(afterFirst).toBeGreaterThan(0);
+ act(() => {
+ vi.advanceTimersByTime(100);
+ });
+ expect(menu.scrollTop).toBeGreaterThan(afterFirst);
+
+ fireEvent.pointerMove(row('A'), {...touch(), clientY: 50});
+ const atRest = menu.scrollTop;
+ act(() => {
+ vi.advanceTimersByTime(100);
+ });
+ expect(menu.scrollTop).toBe(atRest);
+
+ fireEvent.pointerUp(row('A'), {...touch(), clientY: 50});
+ act(() => {
+ vi.advanceTimersByTime(100);
+ });
+ expect(menu.scrollTop).toBe(atRest);
+ });
+});
diff --git a/packages/core/src/hooks/useMenuPress.ts b/packages/core/src/hooks/useMenuPress.ts
new file mode 100644
index 0000000000..a80b29c4de
--- /dev/null
+++ b/packages/core/src/hooks/useMenuPress.ts
@@ -0,0 +1,663 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useMenuPress.ts
+ * @input The menu root, its trigger, the enabled-row selector, and callbacks
+ * for opening, highlighting, activating and dismissing
+ * @output Exports useMenuPress, the marker attribute, and the module-level
+ * activation mark
+ * @position Core hook; mounted by DropdownMenu, ContextMenu,
+ * DropdownMenuSubMenu, Selector and MenuBottomSheetActionList. The pure
+ * transition table lives in menuPressGesture.ts.
+ *
+ * One press inside a menu, owned end to end:
+ *
+ * - The pointer is tracked at DOCUMENT level by `pointerId`. A finger's
+ * pointer events stay with the element it landed on (implicit capture), so a
+ * menu container never sees a finger that slid onto it — the document does.
+ * - The highlight follows the pointer (DOM focus with `preventScroll` in a
+ * menu; a callback for a picker that highlights by index).
+ * - The row under the RELEASE acts, the way its own click would, carrying the
+ * release's button and modifier keys.
+ * - The browser's stray `click` for a tracked gesture is swallowed at the
+ * window in the capture phase, ahead of React's own listener. It arms at a
+ * tracked release and disarms at the next pointer press or after a short
+ * window; a click with `detail === 0` (a keyboard's or a screen reader's)
+ * always passes.
+ * - `pointercancel`, a second pointer, or the window losing focus end the
+ * gesture with nothing acting; the model never re-implements scrolling.
+ * - While a press is tracked in an overflowing menu, a pointer resting near
+ * the top or bottom edge scrolls the menu toward that edge.
+ *
+ * The menu root is marked `data-astryx-menu-press` so a nested flyout (a DOM
+ * descendant of its parent menu) can tell which level owns a press, and so a
+ * surface can be recognised as carrying this model.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/hooks/index.ts
+ * - /packages/core/src/hooks/useMenuPress.doc.mjs
+ * - /packages/core/src/hooks/useMenuPress.test.tsx
+ * - /packages/core/src/hooks/menuPressGesture.ts
+ */
+
+import {useCallback, useEffect, useMemo, useRef, type RefObject} from 'react';
+import {
+ IDLE_MENU_PRESS,
+ menuPressStep,
+ type MenuPressEffect,
+ type MenuPressEvent,
+ type MenuPressGesture,
+ type MenuPressPointerType,
+} from './menuPressGesture';
+
+/** Marks a menu root that carries this press model. */
+export const MENU_PRESS_MARKER = 'data-astryx-menu-press';
+const MENU_PRESS_ROOT_SELECTOR = `[${MENU_PRESS_MARKER}]`;
+
+/** How long after a tracked release the browser's click is still swallowed. */
+export const MENU_PRESS_STRAY_CLICK_MS = 400;
+/** Distance from a scrolling menu's edge within which a resting pointer scrolls. */
+export const MENU_PRESS_AUTOSCROLL_ZONE_PX = 24;
+const AUTOSCROLL_STEP_PX = 6;
+const AUTOSCROLL_INTERVAL_MS = 16;
+
+const FOCUSABLE_ROW_SELECTOR =
+ '[tabindex], a[href], button, input, select, textarea, [contenteditable]';
+const INNER_CONTROL_SELECTOR = 'a[href], button, [tabindex]';
+
+// =============================================================================
+// Module state: the activation mark and the stray-click swallower
+// =============================================================================
+
+let isModelActivation = false;
+
+/**
+ * Whether a menu row activation dispatched by the press model is in flight.
+ * True for the synchronous extent of that dispatch, so a row that forwards
+ * the activation to a control inside it (a link) can tell the model's click
+ * from the browser's stray one.
+ */
+export function isMenuPressActivation(): boolean {
+ return isModelActivation;
+}
+
+interface StrayClickSwallower {
+ doc: Document;
+ isArmed: boolean;
+ timer: ReturnType<typeof setTimeout> | null;
+}
+
+let swallower: StrayClickSwallower | null = null;
+
+function disarmStrayClick(): void {
+ if (swallower == null) {
+ return;
+ }
+ swallower.isArmed = false;
+ if (swallower.timer != null) {
+ clearTimeout(swallower.timer);
+ swallower.timer = null;
+ }
+}
+
+function onWindowClickCapture(event: MouseEvent): void {
+ if (swallower == null || !swallower.isArmed) {
+ return;
+ }
+ // A keyboard's or a screen reader's activation reports detail 0, as does the
+ // model's own dispatch. Those are never the browser's stray click.
+ if (event.detail === 0 || isModelActivation) {
+ return;
+ }
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ disarmStrayClick();
+}
+
+function armStrayClick(doc: Document): void {
+ const view = doc.defaultView;
+ if (view == null) {
+ return;
+ }
+ if (swallower == null || swallower.doc !== doc) {
+ if (swallower != null) {
+ swallower.doc.defaultView?.removeEventListener(
+ 'click',
+ onWindowClickCapture,
+ true,
+ );
+ swallower.doc.removeEventListener('pointerdown', disarmStrayClick, true);
+ }
+ // The window, capture phase: ahead of React's root listener and of any
+ // document listener, so no framework sees the click.
+ view.addEventListener('click', onWindowClickCapture, true);
+ // The next press is a new gesture; its click must never be eaten.
+ doc.addEventListener('pointerdown', disarmStrayClick, true);
+ swallower = {doc, isArmed: false, timer: null};
+ }
+ disarmStrayClick();
+ swallower.isArmed = true;
+ swallower.timer = setTimeout(disarmStrayClick, MENU_PRESS_STRAY_CLICK_MS);
+}
+
+/** Test-only: forget an armed swallower between cases. */
+export function __resetMenuPressForTest(): void {
+ disarmStrayClick();
+}
+
+// =============================================================================
+// Options
+// =============================================================================
+
+export interface UseMenuPressOptions {
+ /** The menu (or listbox) root: the surface whose rows the press picks from. */
+ menuRef: RefObject<HTMLElement | null>;
+ /**
+ * The control that opens the menu. A release over it is not "outside":
+ * it acts on nothing and leaves the menu open under every pointer.
+ */
+ triggerRef?: RefObject<HTMLElement | null>;
+ /**
+ * Selector matching the ENABLED rows. A pointer over anything else inside
+ * the menu — a divider, a heading, a disabled row — highlights nothing.
+ */
+ itemSelector: string;
+ /**
+ * Move the highlight. `null` clears it. Defaults to moving DOM focus with
+ * `preventScroll` onto the row (or the control inside it), and onto the
+ * menu root when there is no row — a picker that highlights through
+ * `aria-activedescendant` supplies its own.
+ */
+ onHighlight?: (row: HTMLElement | null) => void;
+ /**
+ * Act on the row under the release. Defaults to dispatching a click on the
+ * row that carries the release's button and modifier keys, so the row acts
+ * exactly as its own click would.
+ */
+ onActivate?: (row: HTMLElement, release: PointerEvent) => void;
+ /** A MOUSE was released outside the menu with nothing acting: close it. */
+ onDismiss?: () => void;
+ /**
+ * The element to scroll while a tracked pointer rests near its edge.
+ * Defaults to the menu root when it overflows; return `null` for none.
+ */
+ getScroller?: () => HTMLElement | null;
+ /**
+ * Resolve the element under a viewport point. Defaults to
+ * `document.elementFromPoint`, falling back to the event target where the
+ * document lacks it (jsdom). A test seam.
+ */
+ hitTest?: (x: number, y: number) => Element | null;
+ /** Whether the model is live. @default true */
+ isEnabled?: boolean;
+}
+
+export interface UseMenuPressReturn {
+ /** Spread onto the menu root: claims presses that begin inside it. */
+ menuProps: {
+ onPointerDown: (event: React.PointerEvent<HTMLElement>) => void;
+ [MENU_PRESS_MARKER]: '';
+ };
+ /** End the gesture in flight with nothing acting (the menu closed). */
+ cancel: () => void;
+}
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+function normalizePointerType(type: string): MenuPressPointerType | null {
+ return type === 'mouse' || type === 'touch' || type === 'pen' ? type : null;
+}
+
+function isRowFocusable(row: HTMLElement): boolean {
+ return row.matches(FOCUSABLE_ROW_SELECTOR);
+}
+
+/** The outermost marked root: a flyout is a DOM descendant of its parent menu. */
+function getOutermostRoot(menu: HTMLElement): HTMLElement {
+ let root = menu;
+ for (;;) {
+ const parent = root.parentElement?.closest<HTMLElement>(
+ MENU_PRESS_ROOT_SELECTOR,
+ );
+ if (parent == null) {
+ return root;
+ }
+ root = parent;
+ }
+}
+
+interface ResolvedPoint {
+ row: HTMLElement | null;
+ isInMenu: boolean;
+ isOnTrigger: boolean;
+}
+
+// =============================================================================
+// Hook
+// =============================================================================
+
+/**
+ * The press model for a menu: the row under the release acts and the
+ * highlight follows a held pointer. See the file header.
+ *
+ * @example
+ * ```
+ * const menuPress = useMenuPress({
+ * menuRef: listRef,
+ * triggerRef: buttonRef,
+ * itemSelector: MENU_ITEM_SELECTOR,
+ * onDismiss: closeMenu,
+ * });
+ * <div ref={listRef} role="menu" {...menuPress.menuProps}>…</div>
+ * ```
+ */
+export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
+ const optionsRef = useRef(options);
+ optionsRef.current = options;
+
+ const gestureRef = useRef<MenuPressGesture<HTMLElement>>(IDLE_MENU_PRESS);
+ const pointerIdRef = useRef<number | null>(null);
+ const detachRef = useRef<(() => void) | null>(null);
+ const autoscrollRef = useRef<{
+ timer: ReturnType<typeof setInterval>;
+ direction: 1 | -1;
+ } | null>(null);
+ const lastPointerEventRef = useRef<PointerEvent | null>(null);
+ // The second pointer that ended a gesture must not start the next one.
+ const ignoredPointerIdRef = useRef<number | null>(null);
+
+ const getDocument = useCallback((): Document => {
+ return (
+ optionsRef.current.menuRef.current?.ownerDocument ??
+ optionsRef.current.triggerRef?.current?.ownerDocument ??
+ document
+ );
+ }, []);
+
+ const resolvePoint = useCallback(
+ (event: PointerEvent): ResolvedPoint => {
+ const {menuRef, triggerRef, itemSelector, hitTest} = optionsRef.current;
+ const menu = menuRef.current;
+ const doc = getDocument();
+ let element: Element | null;
+ if (hitTest != null) {
+ element = hitTest(event.clientX, event.clientY);
+ } else if (typeof doc.elementFromPoint === 'function') {
+ element = doc.elementFromPoint(event.clientX, event.clientY);
+ } else {
+ element = event.target instanceof Element ? event.target : null;
+ }
+ const root = menu == null ? null : getOutermostRoot(menu);
+ const isInMenu =
+ root != null && element != null && root.contains(element);
+ const trigger = triggerRef?.current ?? null;
+ const isOnTrigger =
+ trigger != null && element != null && trigger.contains(element);
+ let row: HTMLElement | null = null;
+ if (isInMenu && element != null) {
+ row = element.closest<HTMLElement>(itemSelector);
+ if (row != null && !root.contains(row)) {
+ row = null;
+ }
+ }
+ return {row, isInMenu, isOnTrigger};
+ },
+ [getDocument],
+ );
+
+ const stopAutoscroll = useCallback(() => {
+ if (autoscrollRef.current != null) {
+ clearInterval(autoscrollRef.current.timer);
+ autoscrollRef.current = null;
+ }
+ }, []);
+
+ const endGesture = useCallback(() => {
+ stopAutoscroll();
+ detachRef.current?.();
+ detachRef.current = null;
+ pointerIdRef.current = null;
+ lastPointerEventRef.current = null;
+ gestureRef.current = IDLE_MENU_PRESS;
+ }, [stopAutoscroll]);
+
+ const highlight = useCallback(
+ (row: HTMLElement | null) => {
+ const {onHighlight, menuRef} = optionsRef.current;
+ if (onHighlight != null) {
+ onHighlight(row);
+ return;
+ }
+ // In a menu the highlight IS focus. A row whose root takes no
+ // focus is highlighted through the control inside it; over nothing,
+ // the menu root holds focus so no row is lit.
+ const target =
+ row == null
+ ? menuRef.current
+ : isRowFocusable(row)
+ ? row
+ : row.querySelector<HTMLElement>(INNER_CONTROL_SELECTOR);
+ if (target != null && target !== getDocument().activeElement) {
+ target.focus({preventScroll: true});
+ }
+ },
+ [getDocument],
+ );
+
+ const activate = useCallback((row: HTMLElement, release: PointerEvent) => {
+ const {onActivate} = optionsRef.current;
+ isModelActivation = true;
+ try {
+ if (onActivate != null) {
+ onActivate(row, release);
+ return;
+ }
+ // The row acts as its own click would. `detail: 0` marks a dispatched
+ // activation, as a keyboard's does, so the stray-click swallower lets
+ // it through; the button and modifiers are the release's.
+ row.dispatchEvent(
+ new MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ detail: 0,
+ button: release.button,
+ clientX: release.clientX,
+ clientY: release.clientY,
+ screenX: release.screenX,
+ screenY: release.screenY,
+ ctrlKey: release.ctrlKey,
+ shiftKey: release.shiftKey,
+ altKey: release.altKey,
+ metaKey: release.metaKey,
+ }),
+ );
+ } finally {
+ isModelActivation = false;
+ }
+ }, []);
+
+ // Declared before `step` so the mutual recursion through refs type-checks.
+ const stepRef = useRef<
+ (event: MenuPressEvent<HTMLElement>, native?: PointerEvent) => void
+ >(() => {});
+
+ const applyEffect = useCallback(
+ (
+ effect: MenuPressEffect<HTMLElement>,
+ native: PointerEvent | undefined,
+ ) => {
+ const doc = getDocument();
+ switch (effect.type) {
+ case 'none':
+ return;
+ case 'highlight':
+ highlight(effect.row);
+ return;
+ case 'clear':
+ highlight(null);
+ return;
+ case 'act': {
+ // Detach before acting: the activation usually closes the menu.
+ endGesture();
+ armStrayClick(doc);
+ if (native != null) {
+ activate(effect.row, native);
+ }
+ return;
+ }
+ case 'settle': {
+ endGesture();
+ if (effect.stray) {
+ armStrayClick(doc);
+ }
+ if (effect.dismiss) {
+ optionsRef.current.onDismiss?.();
+ }
+ return;
+ }
+ }
+ },
+ [activate, endGesture, getDocument, highlight],
+ );
+
+ const step = useCallback(
+ (event: MenuPressEvent<HTMLElement>, native?: PointerEvent) => {
+ const result = menuPressStep(gestureRef.current, event);
+ gestureRef.current = result.gesture;
+ applyEffect(result.effect, native);
+ },
+ [applyEffect],
+ );
+ stepRef.current = step;
+
+ // --- Edge autoscroll -----------------------------------------------
+
+ const getScroller = useCallback((): HTMLElement | null => {
+ const {getScroller: custom, menuRef} = optionsRef.current;
+ if (custom != null) {
+ return custom();
+ }
+ const menu = menuRef.current;
+ if (menu == null) {
+ return null;
+ }
+ return menu.scrollHeight > menu.clientHeight + 1 ? menu : null;
+ }, []);
+
+ const updateAutoscroll = useCallback(
+ (event: PointerEvent) => {
+ if (gestureRef.current.phase !== 'tracking') {
+ stopAutoscroll();
+ return;
+ }
+ const scroller = getScroller();
+ if (scroller == null) {
+ stopAutoscroll();
+ return;
+ }
+ const rect = scroller.getBoundingClientRect();
+ if (rect.height <= 0) {
+ stopAutoscroll();
+ return;
+ }
+ let direction: 1 | -1 | 0 = 0;
+ if (event.clientY <= rect.top + MENU_PRESS_AUTOSCROLL_ZONE_PX) {
+ direction = -1;
+ } else if (event.clientY >= rect.bottom - MENU_PRESS_AUTOSCROLL_ZONE_PX) {
+ direction = 1;
+ }
+ if (direction === 0) {
+ stopAutoscroll();
+ return;
+ }
+ if (autoscrollRef.current?.direction === direction) {
+ return;
+ }
+ stopAutoscroll();
+ const tick = () => {
+ const before = scroller.scrollTop;
+ scroller.scrollTop = before + direction * AUTOSCROLL_STEP_PX;
+ if (scroller.scrollTop === before) {
+ // The edge is reached; nothing more to reveal.
+ stopAutoscroll();
+ return;
+ }
+ // The rows moved under the resting pointer: re-read the row under it.
+ const last = lastPointerEventRef.current;
+ if (last != null) {
+ const point = resolvePoint(last);
+ stepRef.current(
+ {
+ type: 'move',
+ row: point.row,
+ isInMenu: point.isInMenu,
+ time: Date.now(),
+ },
+ last,
+ );
+ }
+ };
+ autoscrollRef.current = {
+ direction,
+ timer: setInterval(tick, AUTOSCROLL_INTERVAL_MS),
+ };
+ tick();
+ },
+ [getScroller, resolvePoint, stopAutoscroll],
+ );
+
+ // --- Document-level tracking ----------------------------------------------
+
+ const attach = useCallback(
+ (pointerId: number) => {
+ detachRef.current?.();
+ const doc = getDocument();
+ const view = doc.defaultView;
+ pointerIdRef.current = pointerId;
+
+ const onMove = (event: PointerEvent) => {
+ if (event.pointerId !== pointerIdRef.current) {
+ return;
+ }
+ lastPointerEventRef.current = event;
+ const point = resolvePoint(event);
+ stepRef.current(
+ {
+ type: 'move',
+ row: point.row,
+ isInMenu: point.isInMenu,
+ time: Date.now(),
+ },
+ event,
+ );
+ updateAutoscroll(event);
+ };
+ const onUp = (event: PointerEvent) => {
+ if (event.pointerId !== pointerIdRef.current) {
+ return;
+ }
+ const point = resolvePoint(event);
+ stepRef.current(
+ {
+ type: 'up',
+ row: point.row,
+ isInMenu: point.isInMenu,
+ isOnTrigger: point.isOnTrigger,
+ time: Date.now(),
+ },
+ event,
+ );
+ };
+ const onCancel = (event: PointerEvent) => {
+ if (event.pointerId !== pointerIdRef.current) {
+ return;
+ }
+ stepRef.current({type: 'cancel'});
+ };
+ const onOtherPointerDown = (event: PointerEvent) => {
+ // A second pointer ends the gesture: two fingers are a pinch or a
+ // scroll, never a pick.
+ if (event.pointerId !== pointerIdRef.current) {
+ ignoredPointerIdRef.current = event.pointerId;
+ stepRef.current({type: 'cancel'});
+ }
+ };
+ const onBlur = () => {
+ stepRef.current({type: 'cancel'});
+ };
+
+ doc.addEventListener('pointermove', onMove, true);
+ doc.addEventListener('pointerup', onUp, true);
+ doc.addEventListener('pointercancel', onCancel, true);
+ doc.addEventListener('pointerdown', onOtherPointerDown, true);
+ view?.addEventListener('blur', onBlur);
+ detachRef.current = () => {
+ doc.removeEventListener('pointermove', onMove, true);
+ doc.removeEventListener('pointerup', onUp, true);
+ doc.removeEventListener('pointercancel', onCancel, true);
+ doc.removeEventListener('pointerdown', onOtherPointerDown, true);
+ view?.removeEventListener('blur', onBlur);
+ };
+ },
+ [getDocument, resolvePoint, updateAutoscroll],
+ );
+
+ // --- Handlers ------------------------------------------------------------
+
+ const handleMenuPointerDown = useCallback(
+ (event: React.PointerEvent<HTMLElement>) => {
+ const {menuRef, isEnabled = true} = optionsRef.current;
+ const menu = menuRef.current;
+ if (!isEnabled || menu == null) {
+ return;
+ }
+ if (event.pointerId === ignoredPointerIdRef.current) {
+ ignoredPointerIdRef.current = null;
+ return;
+ }
+ if (gestureRef.current.phase !== 'idle') {
+ // A second pointer landed inside the menu.
+ step({type: 'cancel'});
+ return;
+ }
+ const pointerType = normalizePointerType(event.pointerType);
+ if (pointerType == null) {
+ return;
+ }
+ if (pointerType === 'mouse' && event.button !== 0) {
+ return;
+ }
+ // The innermost model owns the press: a flyout is a DOM descendant of
+ // its parent menu, and both would otherwise track the same pointer.
+ const target = event.target as Element | null;
+ if (target?.closest(MENU_PRESS_ROOT_SELECTOR) !== menu) {
+ return;
+ }
+ if (pointerType !== 'mouse') {
+ // Cancelling pointerdown suppresses the compatibility mouse events a
+ // finger would otherwise fire at the row it LANDED on when it lifts —
+ // the mousedown that would light the origin row a second time.
+ // Scrolling is governed by touch-action and is unaffected.
+ event.preventDefault();
+ }
+ const native = event.nativeEvent;
+ attach(native.pointerId);
+ lastPointerEventRef.current = native;
+ const point = resolvePoint(native);
+ step(
+ {type: 'down', pointerType, row: point.row, time: Date.now()},
+ native,
+ );
+ },
+ [attach, resolvePoint, step],
+ );
+
+ const cancel = useCallback(() => {
+ if (gestureRef.current.phase !== 'idle') {
+ step({type: 'cancel'});
+ }
+ endGesture();
+ }, [endGesture, step]);
+
+ useEffect(() => {
+ return () => {
+ endGesture();
+ };
+ }, [endGesture]);
+
+ return useMemo<UseMenuPressReturn>(
+ () => ({
+ menuProps: {
+ onPointerDown: handleMenuPointerDown,
+ [MENU_PRESS_MARKER]: '',
+ },
+ cancel,
+ }),
+ [handleMenuPointerDown, cancel],
+ );
+}