Skip to content

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

TypeScript

feat(DropdownMenu): a mouse opens the menu on press and can drag into it; a held finger opens it (#6826)

Christopher Chedeau0e1fbdbe0fb7
diff --git a/.changeset/menu-press-trigger.md b/.changeset/menu-press-trigger.md
new file mode 100644
index 0000000000..90cb1fa8b5
--- /dev/null
+++ b/.changeset/menu-press-trigger.md
@@ -0,0 +1,18 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] A mouse opens a DropdownMenu on press and can drag straight into it; a finger held on the trigger opens it with the finger down.
+
+A `DropdownMenu` trigger now opens its menu on a mouse press-down, and a
+drag from the trigger into the menu that lets go over a row picks it, as
+macOS menus do. The release of the opening press acts only after the
+pointer has entered the menu or the press has lasted about a third of a
+second, so a menu that opens under the pointer never picks a row nobody
+chose. Pressing the trigger of an open menu closes it without reopening in
+the same gesture. A tap still opens through its click; a finger held on the
+trigger for half a second opens the menu with the finger down, and a slide
+then picks. `useMenuPress` gains `onTriggerPress`, `triggerProps`,
+`isTriggerClickFromPress` and `longPressDelayMs`.
+
+@vjeux
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
index 36995840c8..24eb54bff6 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
+++ b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs
@@ -258,7 +258,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. 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.',
+ '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, the highlight follows a held mouse or finger, a mouse opens it on press and can drag straight into it, and a finger held on the trigger opens it with the finger down.',
bestPractices: [
{
guidance: true,
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.spec.md b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
index ac484bfc05..351b381a40 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.spec.md
+++ b/packages/core/src/DropdownMenu/DropdownMenu.spec.md
@@ -51,7 +51,8 @@ highlight follows the pointer — is contracted by
- Compatibility class: additive documentation; the press-model behavior
delta is recorded in `module:DropdownMenu/useMenuPress`
- Controlled/uncontrolled behavior: unchanged
-- Migration decision: `module:DropdownMenu/useMenuPress/DEC-3`
+- Migration decision: `module:DropdownMenu/useMenuPress/DEC-3`; proposed
+ `module:DropdownMenu/useMenuPress/DEC-4`
Consumer migration instructions belong in consumer docs and release notes.
@@ -66,8 +67,9 @@ 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`.
+- Mounting the shared press model on both menu surfaces and (proposed) on
+ the Trigger button for mouse press-open and held-finger open; the model
+ itself is owned by `module:DropdownMenu/useMenuPress`.
**Does not own / non-goals**
@@ -99,6 +101,7 @@ component-local concept is added by DEC-3; it keeps its released default.
| 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 |
| FR6 | When the pointer menu closes, focus returns to the Trigger button with a visible ring only when the menu was driven by keyboard; a press outside that landed on a focusable control keeps focus there. | `architecture:interaction-modality` INV1; proposed in this change; `DropdownMenu.test.tsx` closing suite | Proposed; verified in jsdom, pending owner review |
| FR7 | `menuMaxHeight` MUST replace the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | `component:DropdownMenu/DEC-3` | Proposed; verified in jsdom; owner to confirm DEC-3 |
+| FR8 | The Trigger button opens the pointer menu on a mouse press-down and on a finger held for the long-press delay, with the module's settle rule on the opening release; pressing the trigger of an open menu closes it without reopening in the same gesture; a tap and the keyboard open as before (`module:DropdownMenu/useMenuPress` proposed FR8, FR9). | Proposed `module:DropdownMenu/useMenuPress/DEC-4`; `DropdownMenu.test.tsx` press model suite | Proposed; verified in jsdom, pending owner review |
### Allowed variation
@@ -236,16 +239,17 @@ 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` |
-| 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` |
-| FR6 | `DropdownMenu.test.tsx` dismissal and closing suites | keyboard dismissal, pointer dismissal, press outside on a control, pointer pick, closed menu | Focus left on the body after a pointer pick, or a ring after pointer input, fails. | `audit:DropdownMenu/behavior` |
-| FR7 | `menuMaxHeight` MUST replace the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | `component:DropdownMenu/DEC-3` | Proposed; verified in jsdom; owner to confirm DEC-3 |
-| 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` |
+| FR6 | `DropdownMenu.test.tsx` dismissal and closing suites | keyboard dismissal, pointer dismissal, press outside on a control, pointer pick, closed menu | Focus left on the body after a pointer pick, or a ring after pointer input, fails. | `audit:DropdownMenu/behavior` |
+| FR7 | `menuMaxHeight` MUST replace the 300px term of the menu's and its popover viewport's block-size cap while the viewport gutters still bound both; the touch sheet ignores it. | `component:DropdownMenu/DEC-3` | Proposed; verified in jsdom; owner to confirm DEC-3 |
+| 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` |
+| FR8 | `DropdownMenu.test.tsx` press model suite (trigger cases) | Press-open + drag-release, unsettled opening release, trigger toggle, held touch, tap | A menu that does not open on a mouse press, an unsettled release that acts, or a trigger that reopens in the same gesture fails. | `audit:DropdownMenu/behavior` |
## Decision log
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
index f3279215a2..8332519925 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.test.tsx
@@ -2354,6 +2354,101 @@ describe('DropdownMenu press model', () => {
expect(menu).toHaveClass(hash(touchStyles.none));
expect(menu).not.toHaveClass(hash(touchStyles.panY));
});
+
+ it('a mouse press on the trigger opens the menu and a drag-release acts on the row under it', () => {
+ const onPick = vi.fn();
+ const trigger = renderMenu(onPick);
+ fireEvent.pointerDown(trigger, mouse);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1);
+
+ fireEvent.pointerMove(item('Duplicate'), mouse);
+ expect(item('Duplicate')).toHaveFocus();
+ fireEvent.pointerUp(item('Duplicate'), mouse);
+ expect(onPick).toHaveBeenCalledTimes(1);
+ expect(onPick).toHaveBeenCalledWith('Duplicate');
+ expect(HTMLElement.prototype.hidePopover).toHaveBeenCalled();
+ });
+
+ it('the opening release before the settle time acts on nothing and the menu stays', () => {
+ vi.useFakeTimers();
+ try {
+ const onPick = vi.fn();
+ const trigger = renderMenu(onPick);
+ fireEvent.pointerDown(trigger, mouse);
+ fireEvent.pointerUp(trigger, mouse);
+ fireEvent.click(trigger, {detail: 1});
+ expect(onPick).not.toHaveBeenCalled();
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ expect(HTMLElement.prototype.hidePopover).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('pressing the trigger of an open menu closes it and does not reopen it in the same gesture', () => {
+ const trigger = renderMenu();
+ fireEvent.pointerDown(trigger, mouse);
+ fireEvent.pointerUp(trigger, mouse);
+ fireEvent.click(trigger, {detail: 1});
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ fireEvent.pointerDown(trigger, mouse);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ fireEvent.pointerUp(trigger, mouse);
+ fireEvent.click(trigger, {detail: 1});
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1);
+ });
+
+ it('a held touch on the trigger opens with the finger down and a slide picks', () => {
+ vi.useFakeTimers();
+ try {
+ const onPick = vi.fn();
+ const trigger = renderMenu(onPick);
+ fireEvent.pointerDown(trigger, touch);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ act(() => {
+ vi.advanceTimersByTime(500);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ fireEvent.pointerMove(item('Delete'), touch);
+ expect(item('Delete')).toHaveFocus();
+ fireEvent.pointerUp(item('Delete'), touch);
+ expect(onPick).toHaveBeenCalledWith('Delete');
+ // The click the browser aims at the trigger for this gesture is spent.
+ fireEvent.click(trigger, {detail: 1});
+ expect(HTMLElement.prototype.showPopover).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('a tap on the trigger still opens through its click', () => {
+ const trigger = renderMenu();
+ fireEvent.pointerDown(trigger, touch);
+ fireEvent.pointerUp(trigger, touch);
+ fireEvent.click(trigger, {detail: 1});
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+});
+
+describe('DropdownMenu trigger handler composition', () => {
+ it('still calls a consumer onClickCapture passed through button', () => {
+ // The press model needs its own click-capture handler on the trigger to
+ // swallow the click that follows a press-open. Setting it directly after
+ // spreading the caller's button props dropped theirs silently, while the
+ // pointer and context-menu handlers either side composed correctly.
+ const onClickCapture = vi.fn();
+ render(
+ <DropdownMenu
+ button={{label: 'Actions', onClickCapture}}
+ items={[{label: 'Edit'}]}
+ />,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Actions'}));
+ expect(onClickCapture).toHaveBeenCalled();
+ });
});
describe('DropdownMenu menuMaxHeight', () => {
diff --git a/packages/core/src/DropdownMenu/DropdownMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenu.tsx
index e21dc4d864..53b1615f76 100644
--- a/packages/core/src/DropdownMenu/DropdownMenu.tsx
+++ b/packages/core/src/DropdownMenu/DropdownMenu.tsx
@@ -58,6 +58,7 @@ import {
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {useListFocus} from '../hooks/useListFocus';
import {useMenuPress} from '../hooks/useMenuPress';
+import type {MenuPressPointerType} from '../hooks/menuPressGesture';
import {useTypeahead} from '../hooks/useTypeahead';
import {useFocusReturnVisibility} from '../hooks/useFocusReturnVisibility';
import {useMenuOverflow} from './useMenuOverflow';
@@ -98,6 +99,13 @@ const styles = stylex.create({
triggerOpen: {
backgroundImage: MENU_TRIGGER_OPEN_BACKGROUND,
},
+ // A finger held on the trigger opens the menu; the browser's own held-press
+ // affordances — the link preview callout, text selection — must not compete
+ // with it.
+ triggerPressable: {
+ WebkitTouchCallout: 'none',
+ userSelect: 'none',
+ },
dropdown: {
boxSizing: 'border-box',
display: 'flex',
@@ -395,6 +403,33 @@ export type DropdownMenuProps =
// locale.
const DEFAULT_BUTTON_I18N_KEY = '@astryx.dropdownMenu.label' as const;
+/**
+ * Keep `control` the invoker of popover `popoverId` for the rest of the press
+ * in flight, so the native light dismiss of a `popover="auto"` does not read
+ * the release over the trigger as a dismissal. The attribute is dropped a
+ * task after the release, once light dismiss has run.
+ */
+function holdInvokerThroughPress(
+ control: HTMLElement | null,
+ popoverId: string,
+): void {
+ if (control == null) {
+ return;
+ }
+ const doc = control.ownerDocument;
+ control.setAttribute('popovertarget', popoverId);
+ const onPressEnd = () => {
+ doc.removeEventListener('pointerup', onPressEnd, true);
+ doc.removeEventListener('pointercancel', onPressEnd, true);
+ // Light dismiss runs as the pointerup default action after listeners.
+ doc.defaultView?.setTimeout(() => {
+ control.removeAttribute('popovertarget');
+ }, 0);
+ };
+ doc.addEventListener('pointerup', onPressEnd, true);
+ doc.addEventListener('pointercancel', onPressEnd, true);
+}
+
function DropdownMenuBottomSheet({
button: buttonFromProps,
isMenuOpen: controlledIsOpen,
@@ -874,6 +909,43 @@ function DropdownMenuPopover({
[isControlled, popover],
);
+ const isMenuOpenNow = isControlled
+ ? controlledIsOpen === true
+ : popover.isOpen;
+
+ // A mouse opens on press-down; a finger held on the trigger opens after
+ // the long-press delay. Pressing the trigger of an open menu closes it, and
+ // the click of that same gesture — reported by `isTriggerClickFromPress` —
+ // neither toggles nor reopens.
+ const handleTriggerPress = useCallback(
+ (pointerType: MenuPressPointerType): boolean => {
+ if (isMenuOpenNow) {
+ if (pointerType !== 'mouse') {
+ // A finger's tap toggles through its click, as it always did.
+ return false;
+ }
+ onClick?.();
+ if (isControlled) {
+ onOpenChange?.(false);
+ } else {
+ popover.hide();
+ }
+ return false;
+ }
+ const didOpen = openAndFocus('pointer', true);
+ if (didOpen && pointerType === 'mouse') {
+ // The menu is `popover="auto"`: the browser's light dismiss would
+ // read the release of this very press, on the trigger outside the
+ // popover, as a dismissal. Holding the invoker relationship through
+ // the press exempts the trigger, the way useKeepLayerOpenProps does
+ // for controls beside an open layer.
+ holdInvokerThroughPress(buttonRef.current, popover.id);
+ }
+ return didOpen;
+ },
+ [isMenuOpenNow, isControlled, onClick, onOpenChange, openAndFocus, 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.
@@ -881,12 +953,17 @@ function DropdownMenuPopover({
menuRef: listRef,
triggerRef: buttonRef,
itemSelector: MENU_ITEM_SELECTOR,
+ onTriggerPress: handleTriggerPress,
onDismiss: closeMenu,
});
cancelMenuPressRef.current = menuPress.cancel;
const handleButtonClick = useCallback(
(e: React.MouseEvent<HTMLButtonElement>) => {
+ // The press already opened or closed the menu; its click is spent.
+ if (menuPress.isTriggerClickFromPress()) {
+ return;
+ }
// detail === 0 marks a synthesized click (screen reader / AT
// activation): treat it as keyboard so those users still land on the
// first item. Real pointer clicks report detail >= 1.
@@ -906,6 +983,7 @@ function DropdownMenuPopover({
}
},
[
+ menuPress,
onClick,
isControlled,
onOpenChange,
@@ -915,6 +993,19 @@ function DropdownMenuPopover({
],
);
+ const handleTriggerClickCapture = useCallback(
+ (e: React.MouseEvent<HTMLButtonElement>) => {
+ const control = e.currentTarget;
+ if (control.hasAttribute('popovertarget')) {
+ // Still the invoker from a press-open: the browser would toggle the
+ // menu shut on this click.
+ e.preventDefault();
+ control.removeAttribute('popovertarget');
+ }
+ },
+ [],
+ );
+
const handleButtonKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (!popover.isOpen) {
@@ -991,6 +1082,7 @@ function DropdownMenuPopover({
}
}}
xstyle={[
+ styles.triggerPressable,
isOpen && styles.triggerOpen,
button.xstyle,
isFocusRingSuppressed && focusOutlineStyles.suppressed,
@@ -998,7 +1090,19 @@ function DropdownMenuPopover({
tooltip={isOpen ? undefined : button.tooltip}
endContent={resolvedEndContent}
onClick={handleButtonClick}
+ onClickCapture={event => {
+ button.onClickCapture?.(event);
+ handleTriggerClickCapture(event);
+ }}
onKeyDown={handleButtonKeyDown}
+ onPointerDown={event => {
+ button.onPointerDown?.(event);
+ menuPress.triggerProps.onPointerDown(event);
+ }}
+ onContextMenu={event => {
+ button.onContextMenu?.(event);
+ menuPress.triggerProps.onContextMenu(event);
+ }}
onFocus={event => {
button.onFocus?.(event);
onFocusReturnTargetFocus();
diff --git a/packages/core/src/DropdownMenu/modules/useMenuPress.spec.md b/packages/core/src/DropdownMenu/modules/useMenuPress.spec.md
index 9dead61944..d45204af43 100644
--- a/packages/core/src/DropdownMenu/modules/useMenuPress.spec.md
+++ b/packages/core/src/DropdownMenu/modules/useMenuPress.spec.md
@@ -34,15 +34,15 @@ references:
## 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. |
+| 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; PROPOSED in this change: the hook's trigger half (`onTriggerPress`, `triggerProps`, `isTriggerClickFromPress`, `longPressDelayMs`). 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. PROPOSED (FR8, FR9, DEC-4): a mouse opens a DropdownMenu on press-down and a finger held on its trigger opens it after the long-press delay, with a settle rule on the opening release. |
+| 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. PROPOSED: a mouse can press the trigger, drag into the menu and let go on a row in one gesture; a finger held on the trigger opens the menu without lifting. Keyboard behavior 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 behavior unchanged. Shipped-behavior changes: DEC-3 (current; a mouse released outside a menu dismisses it) and PROPOSED DEC-4 (a mouse opens the menu on press rather than click; a tap is unchanged). 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 for FR1–FR7, DEC-3, DEC-6, DEC-7 (`cixzhang`, 2026-10-02); FR8, FR9 and DEC-4 are proposed in this change and await the same owner (OQ1). |
+| 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; an opening release that acts before the pointer entered the menu or the press settled; a trigger whose press and click both toggle in one gesture. |
+| 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.
@@ -52,13 +52,15 @@ Astryx menus and pickers previously answered the basic pointer questions on thei
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
+press model: the release decides, the highlight follows the pointer, and
+(proposed here) a mouse opens on press. 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.
+presentation policy, keyboard navigation and item semantics stay with the
+owning component records; trigger opening by keyboard and by a finger's tap
+stays with the component that renders the trigger.
### Adoption eligibility
@@ -82,7 +84,8 @@ adopter.
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`
+- Migration decision: `module:DropdownMenu/useMenuPress/DEC-3`; proposed
+ `module:DropdownMenu/useMenuPress/DEC-4` (pending owner review)
Consumer migration instructions belong in consumer docs and release notes.
@@ -90,7 +93,8 @@ Consumer migration instructions belong in consumer docs and release notes.
**Owns**
-- The gesture state machine (`menuPressStep`): tracking, release and cancel.
+- The gesture state machine (`menuPressStep`): tracking, release and cancel;
+ proposed: trigger press, open, and the settle rule.
- 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.
@@ -100,6 +104,8 @@ Consumer migration instructions belong in consumer docs and release notes.
- 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.
+- Proposed: opening the parent menu on a mouse press and on a held finger,
+ and telling the trigger that the click of that gesture is spent.
- The marker `data-astryx-menu-press` on the menu root.
**Does not own / non-goals**
@@ -114,7 +120,7 @@ Consumer migration instructions belong in consumer docs and release notes.
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
+- Opening a menu from its trigger by keyboard or by a finger's tap — owned by the
component that renders the trigger.
- Keyboard navigation, typeahead and Enter/Space activation — owned by
`useListFocus`, `useTypeahead` and the component records.
@@ -123,28 +129,32 @@ Consumer migration instructions belong in consumer docs and release notes.
## 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 |
+| Concept | Closed values or states | Meaning | Default | Owner | Stability |
+| ------------------------ | -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | ---------------------------------- | --------- |
+| gesture phase | `idle`, `tracking`; proposed `triggerPress`, `open` | where the press in flight stands | `idle` | `module:DropdownMenu/useMenuPress` | stable |
+| effect | `none`, `highlight`, `clear`, `act`, `settle`; proposed `open` | what one event makes the host do; `open` asks the trigger to open the menu under the held pointer; `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 |
+| settle time | 300 ms | proposed: how long an opening press must last before its release may act | `MENU_PRESS_SETTLE_MS` | `module:DropdownMenu/useMenuPress` | proposed |
+| long-press delay | 500 ms | proposed: how long a finger rests on the trigger before the menu opens under it | `longPressDelayMs` | `module:DropdownMenu/useMenuPress` | proposed |
+| `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 |
+| 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 |
+| FR8 | On a mouse a DropdownMenu trigger MUST open its menu on press-down (button 0, no Control), and a drag from the trigger into the menu that releases over an enabled row MUST act on it. The opening gesture's release MUST act only if the pointer entered the menu or the press lasted the settle time; otherwise nothing acts and the menu stays open. Pressing the trigger of an open menu MUST close it and MUST NOT reopen it in the same gesture. | Proposed DEC-4; `DropdownMenu.test.tsx` press model suite, `menuPressGesture.test.ts` trigger states | proposed; pending owner review |
+| FR9 | Under a finger a tap on the trigger MUST open the menu through its click. A press held on the trigger for the long-press delay MUST open the menu with the finger down, prevent the default of the finger's later `touchmove`s until the gesture ends, and continue under FR1–FR4 with the same settle rule. | Proposed DEC-4; `DropdownMenu.test.tsx` held-touch case, `useMenuPress.test.tsx` | proposed; pending owner review |
### Transformation and precedence order
@@ -155,7 +165,10 @@ Consumer migration instructions belong in consumer docs and release notes.
- **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
+- **ORD3 — Trigger click (proposed).** The press model's open or close on
+ the trigger runs first; the trigger's own click for that same gesture (by
+ gesture counter) is a no-op; any other click keeps its toggle.
+- **ORD4 — 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
@@ -207,18 +220,22 @@ owned by the item components.
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.
+ through the browser. Proposed FR8 holds the trigger as the popover's
+ invoker for the extent of a press-open so the release over the trigger is
+ not read as a dismissal, the same mechanism the layer runtime's keep-open
+ props use.
- `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 |
+| 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 |
+| FR8, FR9 (proposed) | `menuPressGesture.test.ts` trigger states; `useMenuPress.test.tsx` trigger suite; `DropdownMenu.test.tsx` press-open cases | mouse opens at once, finger tap, held finger, settle before/after, cancel; press-open + drag-release, unsettled release, trigger toggle, held touch, tap | A menu that does not open on a mouse press, an unsettled release that acts, or a trigger that reopens in the same gesture fails |
## Decision log
@@ -233,6 +250,18 @@ 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-4 (proposed) — A mouse opens on press-down, a finger on a tap, with a settle rule
+
+**Reference:** `module:DropdownMenu/useMenuPress/DEC-4`
+**Decider:** proposed by `vjeux`, `2026-09-27`; pending owner review
+
+Press-to-open with drag-release is the macOS menu. A finger opens on a tap
+because a page under a finger must stay scrollable; a held press opens with
+the finger down so the fast path exists too. The release of the opening
+gesture acts only after the pointer has entered the menu or the press has
+settled (300 ms), as a native pop-up button's does; otherwise a menu that
+opens under the pointer would pick a row nobody chose.
+
### DEC-6 — The highlight is DOM focus in a menu, `aria-activedescendant` in a picker
**Reference:** `module:DropdownMenu/useMenuPress/DEC-6`
@@ -260,7 +289,13 @@ availability alone does not make a component an adopter.
## Open questions
-None. OQ1 (browser-only evidence) is resolved: the touch pan, the finger
+- **OQ1 — Is press-to-open the menu family's trigger model?** (`human-design`)
+ The one owner decision this change needs: proposed FR8, FR9 and DEC-4 — a
+ mouse opens a DropdownMenu on press-down with the settle rule, a finger on
+ a tap or a held press. Until the owner rules, the current record's FR1–FR7
+ stand on their own.
+
+The former browser-evidence question 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`.
diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.ts
index 24603d4524..52594de0aa 100644
--- a/packages/core/src/hooks/index.ts
+++ b/packages/core/src/hooks/index.ts
@@ -44,7 +44,7 @@ export {
isMenuPressActivation,
} from './useMenuPress';
export type {UseMenuPressOptions, UseMenuPressReturn} from './useMenuPress';
-export {menuPressStep} from './menuPressGesture';
+export {menuPressStep, MENU_PRESS_SETTLE_MS} from './menuPressGesture';
export type {
MenuPressEffect,
MenuPressEvent,
diff --git a/packages/core/src/hooks/menuPressGesture.test.ts b/packages/core/src/hooks/menuPressGesture.test.ts
index 43bb2e0117..8ec3f80468 100644
--- a/packages/core/src/hooks/menuPressGesture.test.ts
+++ b/packages/core/src/hooks/menuPressGesture.test.ts
@@ -3,14 +3,14 @@
/**
* @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)
+ * @output One test per transition of the press-model state diagram
* @position Testing; validates menuPressGesture.ts without a browser
*/
import {describe, it, expect} from 'vitest';
import {
IDLE_MENU_PRESS,
+ MENU_PRESS_SETTLE_MS,
menuPressStep,
type MenuPressEvent,
type MenuPressGesture,
@@ -32,7 +32,9 @@ function run(events: MenuPressEvent<Row>[]) {
const downInMenu = (
row: Row | null,
pointerType: 'mouse' | 'touch' = 'touch',
-) => ({type: 'down', pointerType, row, time: 0}) as const;
+) => ({type: 'down', target: 'menu', pointerType, row, time: 0}) as const;
+const downOnTrigger = (pointerType: 'mouse' | 'touch', time = 0) =>
+ ({type: 'down', target: 'trigger', pointerType, row: null, time}) as const;
const move = (row: Row | null, isInMenu = true, time = 10) =>
({type: 'move', row, isInMenu, time}) as const;
const up = (
@@ -125,3 +127,127 @@ describe('menuPressStep — inside the menu', () => {
});
});
});
+
+describe('menuPressStep — the trigger', () => {
+ it('Idle → Open: a mouse press on the trigger opens the menu at once', () => {
+ const {gesture, last} = run([downOnTrigger('mouse')]);
+ expect(gesture.phase).toBe('open');
+ expect(last).toEqual({type: 'open'});
+ });
+
+ it('Idle → TriggerPress: a finger on the trigger opens nothing yet', () => {
+ const {gesture, last} = run([downOnTrigger('touch')]);
+ expect(gesture.phase).toBe('triggerPress');
+ expect(last).toEqual({type: 'none'});
+ });
+
+ it('TriggerPress → Idle: a finger that lifts before the delay is a tap; the browser click opens the menu', () => {
+ const {gesture, last} = run([
+ downOnTrigger('touch'),
+ up(null, {isInMenu: false, isOnTrigger: true}),
+ ]);
+ expect(gesture.phase).toBe('idle');
+ expect(last).toEqual({type: 'settle', stray: false, dismiss: false});
+ });
+
+ it('TriggerPress → Open: the menu opens under a finger held for the delay', () => {
+ const {gesture, last} = run([
+ downOnTrigger('touch'),
+ {type: 'opened', time: 500},
+ ]);
+ expect(gesture.phase).toBe('open');
+ expect(last).toEqual({type: 'none'});
+ });
+
+ it('TriggerPress → Idle: a cancel before the delay ends the gesture', () => {
+ // The effect has to be a settle, not nothing: a held finger installs a
+ // document touchmove preventer for the gesture, and only the end of a
+ // gesture takes it back off. Returning `none` here left the page unable
+ // to scroll after an interrupted press.
+ const {gesture, last} = run([downOnTrigger('touch'), {type: 'cancel'}]);
+ expect(gesture.phase).toBe('idle');
+ expect(last).toEqual({type: 'settle', stray: false, dismiss: false});
+ });
+
+ it('Open → Tracking: the pointer moving onto the menu starts tracking from the trigger', () => {
+ const {gesture, last} = run([downOnTrigger('mouse'), move('A', true)]);
+ expect(gesture).toMatchObject({
+ phase: 'tracking',
+ origin: 'trigger',
+ row: 'A',
+ });
+ expect(last).toEqual({type: 'highlight', row: 'A'});
+ });
+
+ it('Open → Open: a move that stays outside the menu changes nothing', () => {
+ const {gesture, last} = run([downOnTrigger('mouse'), move(null, false)]);
+ expect(gesture.phase).toBe('open');
+ expect(last).toEqual({type: 'none'});
+ });
+
+ it('Open → Idle: the opening release before the settle time, without entering, acts on nothing and the menu stays', () => {
+ const {gesture, last} = run([
+ downOnTrigger('mouse', 0),
+ up(null, {
+ isInMenu: false,
+ isOnTrigger: true,
+ time: MENU_PRESS_SETTLE_MS - 1,
+ }),
+ ]);
+ expect(gesture.phase).toBe('idle');
+ expect(last).toEqual({type: 'settle', stray: true, dismiss: false});
+ });
+
+ it('Open → Acted: a drag from the trigger into the menu that releases over a row acts on it', () => {
+ const {last} = run([
+ downOnTrigger('mouse', 0),
+ move('B', true, 50),
+ up('B', {time: 60}),
+ ]);
+ expect(last).toEqual({type: 'act', row: 'B'});
+ });
+
+ it('Open → Acted: after the settle time the opening release acts on the row under it', () => {
+ const {last} = run([
+ downOnTrigger('mouse', 0),
+ up('A', {time: MENU_PRESS_SETTLE_MS}),
+ ]);
+ expect(last).toEqual({type: 'act', row: 'A'});
+ });
+
+ it('Open → Idle: releasing on the trigger after the settle time leaves the menu open', () => {
+ const {last} = run([
+ downOnTrigger('mouse', 0),
+ up(null, {
+ isInMenu: false,
+ isOnTrigger: true,
+ time: MENU_PRESS_SETTLE_MS,
+ }),
+ ]);
+ expect(last).toEqual({type: 'settle', stray: true, dismiss: false});
+ });
+
+ it('Open → Released → Idle: a settled mouse release outside dismisses; a finger leaves the menu open', () => {
+ expect(
+ run([
+ downOnTrigger('mouse', 0),
+ up(null, {isInMenu: false, time: MENU_PRESS_SETTLE_MS}),
+ ]).last,
+ ).toEqual({type: 'settle', stray: true, dismiss: true});
+ expect(
+ run([
+ downOnTrigger('touch', 0),
+ {type: 'opened', time: 500},
+ up(null, {isInMenu: false, time: 500 + MENU_PRESS_SETTLE_MS}),
+ ]).last,
+ ).toEqual({type: 'settle', stray: true, dismiss: false});
+ });
+
+ it('Open → Idle: a cancel while open ends the gesture and keeps the menu', () => {
+ // As above: the gesture's document listeners come off, and the menu is
+ // left open because a cancelled pointer never asked to close it.
+ const {gesture, last} = run([downOnTrigger('mouse'), {type: 'cancel'}]);
+ expect(gesture.phase).toBe('idle');
+ expect(last).toEqual({type: 'settle', stray: false, dismiss: false});
+ });
+});
diff --git a/packages/core/src/hooks/menuPressGesture.ts b/packages/core/src/hooks/menuPressGesture.ts
index 6ddc353313..d33c49ba22 100644
--- a/packages/core/src/hooks/menuPressGesture.ts
+++ b/packages/core/src/hooks/menuPressGesture.ts
@@ -14,8 +14,17 @@
*
* States:
* - `idle` — no gesture is live.
- * - `tracking` — a pointer is held inside the menu and the highlight follows
- * it.
+ * - `triggerPress` — a finger rests on the trigger; the menu is not open yet.
+ * A mouse skips this state: a mouse press on the trigger opens at once.
+ * - `open` — the menu opened under a held pointer (a mouse press, or a finger
+ * held for the long-press delay) and the pointer has not entered it yet.
+ * - `tracking` — the pointer is held and the highlight follows it.
+ *
+ * The settle rule: the release of the gesture that OPENED the menu acts only
+ * once the pointer has entered the menu or the press has lasted
+ * `MENU_PRESS_SETTLE_MS`; otherwise it acts on nothing and the menu stays
+ * open. Without it a menu that opens under the pointer would pick a row
+ * nobody chose.
*
* 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
@@ -26,13 +35,28 @@
* - /packages/core/src/hooks/useMenuPress.ts
*/
+/** How long the opening press must last before its release may act. */
+export const MENU_PRESS_SETTLE_MS = 300;
+
export type MenuPressPointerType = 'mouse' | 'touch' | 'pen';
export type MenuPressGesture<T> =
| {phase: 'idle'}
+ | {
+ phase: 'triggerPress';
+ pointerType: MenuPressPointerType;
+ startedAt: number;
+ }
+ | {
+ phase: 'open';
+ pointerType: MenuPressPointerType;
+ openedAt: number;
+ }
| {
phase: 'tracking';
pointerType: MenuPressPointerType;
+ /** Where the press began. */
+ origin: 'trigger' | 'menu';
/** The enabled row currently under the pointer, if any. */
row: T | null;
};
@@ -40,11 +64,14 @@ export type MenuPressGesture<T> =
export type MenuPressEvent<T> =
| {
type: 'down';
+ target: 'trigger' | 'menu';
pointerType: MenuPressPointerType;
- /** The enabled row under the press, if any. */
+ /** The enabled row under the press when it lands inside the menu. */
row: T | null;
time: number;
}
+ /** The menu opened while the trigger press is still held. */
+ | {type: 'opened'; time: number}
| {type: 'move'; row: T | null; isInMenu: boolean; time: number}
| {
type: 'up';
@@ -58,6 +85,8 @@ export type MenuPressEvent<T> =
export type MenuPressEffect<T> =
| {type: 'none'}
+ /** A mouse pressed the trigger: open the menu now, under the held pointer. */
+ | {type: 'open'}
| {type: 'highlight'; row: T}
| {type: 'clear'}
| {type: 'act'; row: T}
@@ -114,6 +143,10 @@ export function menuPressStep<T>(
switch (gesture.phase) {
case 'idle':
return stepIdle(gesture, event);
+ case 'triggerPress':
+ return stepTriggerPress(gesture, event);
+ case 'open':
+ return stepOpen(gesture, event);
case 'tracking':
return stepTracking(gesture, event);
}
@@ -126,16 +159,105 @@ function stepIdle<T>(
if (event.type !== 'down') {
return {gesture, effect: NONE};
}
+ if (event.target === 'menu') {
+ return {
+ gesture: {
+ phase: 'tracking',
+ pointerType: event.pointerType,
+ origin: 'menu',
+ row: event.row,
+ },
+ effect: highlightEffect(event.row),
+ };
+ }
+ if (event.pointerType === 'mouse') {
+ return {
+ gesture: {
+ phase: 'open',
+ pointerType: 'mouse',
+ openedAt: event.time,
+ },
+ effect: {type: 'open'},
+ };
+ }
return {
gesture: {
- phase: 'tracking',
+ phase: 'triggerPress',
pointerType: event.pointerType,
- row: event.row,
+ startedAt: event.time,
},
- effect: highlightEffect(event.row),
+ effect: NONE,
};
}
+function stepTriggerPress<T>(
+ gesture: Extract<MenuPressGesture<T>, {phase: 'triggerPress'}>,
+ event: MenuPressEvent<T>,
+): MenuPressStep<T> {
+ switch (event.type) {
+ case 'opened':
+ return {
+ gesture: {
+ phase: 'open',
+ pointerType: gesture.pointerType,
+ openedAt: event.time,
+ },
+ effect: NONE,
+ };
+ case 'up':
+ // A tap. The browser's click on the trigger is what opens the menu, so
+ // it must pass, and no gesture is live afterwards.
+ return idle({type: 'settle', stray: false, dismiss: false});
+ case 'cancel':
+ // The browser took the gesture (an incoming call, a system gesture).
+ // Settle rather than going quiet: a held finger has already installed
+ // the document's touchmove preventer, and only the end of a gesture
+ // takes it back off. No click follows a cancelled pointer.
+ return idle({type: 'settle', stray: false, dismiss: false});
+ case 'down':
+ case 'move':
+ return {gesture, effect: NONE};
+ }
+}
+
+function stepOpen<T>(
+ gesture: Extract<MenuPressGesture<T>, {phase: 'open'}>,
+ event: MenuPressEvent<T>,
+): MenuPressStep<T> {
+ switch (event.type) {
+ case 'move':
+ if (!event.isInMenu) {
+ return {gesture, effect: NONE};
+ }
+ return {
+ gesture: {
+ phase: 'tracking',
+ pointerType: gesture.pointerType,
+ origin: 'trigger',
+ row: event.row,
+ },
+ effect: highlightEffect(event.row),
+ };
+ case 'up': {
+ const hasSettled = event.time - gesture.openedAt >= MENU_PRESS_SETTLE_MS;
+ if (!hasSettled) {
+ // The pointer never entered the menu and the press was short: the
+ // menu stays open and nothing acts. The trigger's own click for this
+ // gesture must not toggle it shut either.
+ return idle({type: 'settle', stray: true, dismiss: false});
+ }
+ return release(gesture.pointerType, event);
+ }
+ case 'cancel':
+ // As above: the gesture ends, so its document listeners come off. The
+ // menu stays open — a cancelled pointer did not ask to close it.
+ return idle({type: 'settle', stray: false, dismiss: false});
+ case 'down':
+ case 'opened':
+ return {gesture, effect: NONE};
+ }
+}
+
function stepTracking<T>(
gesture: Extract<MenuPressGesture<T>, {phase: 'tracking'}>,
event: MenuPressEvent<T>,
@@ -157,6 +279,7 @@ function stepTracking<T>(
// acts, the menu stays, and no click follows a cancelled pointer.
return idle({type: 'settle', stray: false, dismiss: false});
case 'down':
+ case 'opened':
return {gesture, effect: NONE};
}
}
diff --git a/packages/core/src/hooks/useLongPress.ts b/packages/core/src/hooks/useLongPress.ts
index 0f7ad340de..021a2c9801 100644
--- a/packages/core/src/hooks/useLongPress.ts
+++ b/packages/core/src/hooks/useLongPress.ts
@@ -5,16 +5,25 @@
/**
* @file useLongPress.ts
* @input Long-press options: onLongPress callback, disabled, delayMs, moveCancelPx
- * @output Touch handlers to spread onto an element
- * @position Core hook for touch long-press invocation; used by ContextMenu
+ * @output Touch handlers to spread onto an element, plus the same detection
+ * driven by hand for a caller already observing pointer events
+ * @position Core hook for long-press invocation; used by ContextMenu and by
+ * `useMenuPress` for the held-finger menu open
*
* SYNC: When modified, update the hooks barrel /packages/core/src/hooks/index.ts
*
- * Detects a single-finger long-press: fires `onLongPress` with the touch
+ * Detects a single-finger long-press: fires `onLongPress` with the press
* start point after `delayMs`. Cancels if the finger moves past
* `moveCancelPx` (treated as a scroll/drag), lifts, or the touch is
* cancelled. The pending timer is also cleared on unmount.
*
+ * Two ways in, one detector. Spread the touch handlers onto an element, or —
+ * when the caller already runs its own pointer-event machine, as
+ * `useMenuPress` does — call `start`, `moveTo` and `cancel` from it. Either
+ * way the hold duration, the movement tolerance and the timer are this
+ * hook's, so a long press cannot come to mean one thing on a context menu
+ * and another on a menu trigger.
+ *
* Motivation: iOS Safari never synthesizes a `contextmenu` event on
* long-press, so long-press is the only touch affordance for opening
* cursor-positioned surfaces.
@@ -42,6 +51,19 @@ export interface UseLongPressHandlers {
onTouchMove: (e: React.TouchEvent) => void;
onTouchEnd: () => void;
onTouchCancel: () => void;
+ /**
+ * Begin detection at a point, for a caller driving this from its own
+ * pointer events rather than the touch handlers above.
+ */
+ start: (point: {x: number; y: number}) => void;
+ /**
+ * Report the pointer's new position. Past `moveCancelPx` the press is off.
+ * Returns whether a press is still pending, so a caller running its own
+ * state machine can react to the cancellation in the same step.
+ */
+ moveTo: (point: {x: number; y: number}) => boolean;
+ /** Drop any pending press (a lift, a cancel, or the gesture moving on). */
+ cancel: () => void;
}
export function useLongPress(
@@ -68,53 +90,75 @@ export function useLongPress(
startRef.current = null;
}, []);
- const onTouchStart = useCallback(
- (e: React.TouchEvent) => {
+ const start = useCallback(
+ (point: {x: number; y: number}) => {
if (disabled) {
return;
}
- if (e.touches.length !== 1) {
- // Multi-touch cancels any pending long-press.
- clear();
- return;
- }
- const touch = e.touches[0];
// Clear any stale timer first, THEN record the start point — clearing
// also nulls startRef, so order matters.
clear();
- startRef.current = {x: touch.clientX, y: touch.clientY};
+ startRef.current = {x: point.x, y: point.y};
timerRef.current = setTimeout(() => {
- const start = startRef.current;
- if (start == null) {
+ const from = startRef.current;
+ if (from == null) {
return;
}
- onLongPressRef.current({x: start.x, y: start.y});
+ onLongPressRef.current({x: from.x, y: from.y});
}, delayMs);
},
[disabled, delayMs, clear],
);
- const onTouchMove = useCallback(
+ const moveTo = useCallback(
+ (point: {x: number; y: number}): boolean => {
+ const from = startRef.current;
+ if (from == null) {
+ return false;
+ }
+ if (
+ Math.abs(point.x - from.x) > moveCancelPx ||
+ Math.abs(point.y - from.y) > moveCancelPx
+ ) {
+ // Treat as a scroll/drag, not a long-press.
+ clear();
+ return false;
+ }
+ return true;
+ },
+ [moveCancelPx, clear],
+ );
+
+ const onTouchStart = useCallback(
(e: React.TouchEvent) => {
- const start = startRef.current;
- if (start == null) {
+ if (disabled) {
return;
}
if (e.touches.length !== 1) {
- // Multi-touch cancels the pending long-press.
+ // Multi-touch cancels any pending long-press.
clear();
return;
}
const touch = e.touches[0];
- if (
- Math.abs(touch.clientX - start.x) > moveCancelPx ||
- Math.abs(touch.clientY - start.y) > moveCancelPx
- ) {
- // Treat as a scroll/drag, not a long-press.
+ start({x: touch.clientX, y: touch.clientY});
+ },
+ [disabled, clear, start],
+ );
+
+ const onTouchMove = useCallback(
+ (e: React.TouchEvent) => {
+ if (startRef.current == null) {
+ return;
+ }
+ if (e.touches.length !== 1) {
+ // Multi-touch cancels the pending long-press.
clear();
+ return;
}
+ const touch = e.touches[0];
+ moveTo({x: touch.clientX, y: touch.clientY});
},
- [moveCancelPx, clear],
+ [clear, moveTo],
);
// Cancel any pending long-press timer on unmount.
@@ -125,5 +169,8 @@ export function useLongPress(
onTouchMove,
onTouchEnd: clear,
onTouchCancel: clear,
+ start,
+ moveTo,
+ cancel: clear,
};
}
diff --git a/packages/core/src/hooks/useMenuPress.doc.mjs b/packages/core/src/hooks/useMenuPress.doc.mjs
index b386a6565d..25743c24e3 100644
--- a/packages/core/src/hooks/useMenuPress.doc.mjs
+++ b/packages/core/src/hooks/useMenuPress.doc.mjs
@@ -43,7 +43,13 @@ export const docs = {
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.',
+ 'The control that opens the menu, when a press may start there.',
+ },
+ {
+ name: 'options.onTriggerPress',
+ type: '(pointerType: MenuPressPointerType) => boolean',
+ description:
+ 'A mouse pressed the trigger, or a finger rested on it for the long-press delay: open the menu under the held pointer and return whether it opened. Return false when the press closed an open menu instead.',
},
{
name: 'options.onHighlight',
@@ -69,6 +75,13 @@ export const docs = {
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.longPressDelayMs',
+ type: 'number',
+ description:
+ 'How long a finger must rest on the trigger before the menu opens under it.',
+ default: '500',
+ },
{
name: 'options.isEnabled',
type: 'boolean',
@@ -83,6 +96,18 @@ export const docs = {
description:
'Spread onto the menu root. Claims presses that begin inside it and marks the root as carrying the press model.',
},
+ {
+ name: 'triggerProps',
+ type: '{onPointerDown; onContextMenu}',
+ description:
+ 'Spread onto the trigger: a mouse press opens the menu at once; a finger held for the delay opens it with the finger still down.',
+ },
+ {
+ name: 'isTriggerClickFromPress',
+ type: '() => boolean',
+ description:
+ 'Whether the click reaching the trigger belongs to the gesture that just pressed it. That press already opened or closed the menu, so the click must neither toggle nor reopen.',
+ },
{
name: 'cancel',
type: '() => void',
@@ -92,7 +117,7 @@ export const docs = {
],
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.',
+ '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, the highlight follows the pointer while it is held, a mouse opens the menu on press and can drag straight into it, and a finger held on the trigger opens it with the finger still down. 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,
@@ -130,13 +155,14 @@ export const docs = {
/** @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.',
+ 'macOS/iOS menu press model for any pointer: the row under the RELEASE acts, the highlight follows a held pointer, a mouse opens on press and drags in, a held finger opens with the finger down. 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.triggerRef': 'the control that opens the menu.',
+ 'options.onTriggerPress':
+ 'mouse press / held finger on trigger: open, return whether it opened (false = the press closed it).',
'options.onHighlight':
'move highlight (null clears); default = focus w/ preventScroll, menu root when no row.',
'options.onActivate':
@@ -144,15 +170,19 @@ export const docsDense = {
'options.onDismiss': 'MOUSE released outside: close. Finger: never called.',
'options.getScroller':
'element to edge-autoscroll while tracking; default = menu root if it overflows.',
+ 'options.longPressDelayMs': 'finger hold before open, ms.',
'options.isEnabled': 'false = inert.',
},
returnDescriptions: {
menuProps: 'spread on menu root (claims presses, marks the root).',
+ triggerProps: 'spread on trigger (press-open, held-finger open).',
+ isTriggerClickFromPress:
+ 'true = the trigger click belongs to the press that already opened / closed; ignore it.',
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.',
+ 'Release decides; highlight follows the pointer; mouse press-opens; held finger opens. Use directly only for a menu-like surface of your own.',
bestPractices: [
{
guidance: true,
diff --git a/packages/core/src/hooks/useMenuPress.test.tsx b/packages/core/src/hooks/useMenuPress.test.tsx
index d9bc80d4e6..0d5646c72c 100644
--- a/packages/core/src/hooks/useMenuPress.test.tsx
+++ b/packages/core/src/hooks/useMenuPress.test.tsx
@@ -4,8 +4,8 @@
* @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
+ * highlight, activation, the stray-click swallower, dismissal, the trigger
+ * press and edge autoscroll
* @position Testing; validates useMenuPress.ts. The transition table itself
* is covered by menuPressGesture.test.ts.
*/
@@ -15,10 +15,12 @@ import {act, fireEvent, render, screen} from '@testing-library/react';
import {useRef, useState} from 'react';
import {
MENU_PRESS_AUTOSCROLL_ZONE_PX,
+ MENU_PRESS_LONG_PRESS_MS,
MENU_PRESS_STRAY_CLICK_MS,
__resetMenuPressForTest,
useMenuPress,
} from './useMenuPress';
+import {MENU_PRESS_SETTLE_MS} from './menuPressGesture';
const ITEM_SELECTOR = '[role="menuitem"]:not([aria-disabled="true"])';
@@ -50,6 +52,14 @@ function Harness({
menuRef,
triggerRef,
itemSelector: ITEM_SELECTOR,
+ onTriggerPress: () => {
+ if (isOpen) {
+ open(false);
+ return false;
+ }
+ open(true);
+ return true;
+ },
onDismiss,
hitTest,
getScroller,
@@ -60,8 +70,14 @@ function Harness({
<button
type="button"
ref={triggerRef}
+ {...press.triggerProps}
aria-expanded={isOpen}
- onClick={() => open(!isOpen)}>
+ onClick={() => {
+ if (press.isTriggerClickFromPress()) {
+ return;
+ }
+ open(!isOpen);
+ }}>
Open
</button>
<div ref={menuRef} role="menu" tabIndex={-1} {...press.menuProps}>
@@ -313,7 +329,7 @@ describe('useMenuPress — release outside and cancellation', () => {
});
});
-describe('useMenuPress — the trigger and the marker', () => {
+describe('useMenuPress — the trigger', () => {
it('a mouse released back on the trigger acts on nothing and leaves the menu open', () => {
const onSelect = vi.fn();
const onDismiss = vi.fn();
@@ -326,6 +342,119 @@ describe('useMenuPress — the trigger and the marker', () => {
expect(onDismiss).not.toHaveBeenCalled();
});
+ it('a mouse press on the trigger opens the menu, and that gesture’s click does not toggle it', () => {
+ const onOpenChange = vi.fn();
+ render(<Harness onOpenChange={onOpenChange} />);
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(trigger, mouse());
+ expect(onOpenChange).toHaveBeenLastCalledWith(true);
+ fireEvent.pointerUp(trigger, mouse());
+ fireEvent.click(trigger, {detail: 1});
+ expect(onOpenChange).toHaveBeenCalledTimes(1);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('a mouse press on the trigger of an open menu closes it and does not reopen it in the same gesture', () => {
+ const onOpenChange = vi.fn();
+ render(<Harness onOpenChange={onOpenChange} />);
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(trigger, mouse());
+ fireEvent.pointerUp(trigger, mouse());
+ fireEvent.click(trigger, {detail: 1});
+ fireEvent.pointerDown(trigger, mouse());
+ expect(onOpenChange).toHaveBeenLastCalledWith(false);
+ fireEvent.pointerUp(trigger, mouse());
+ fireEvent.click(trigger, {detail: 1});
+ expect(onOpenChange).toHaveBeenCalledTimes(2);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('a drag from the trigger into the menu that releases over a row acts on it', () => {
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(trigger, mouse());
+ fireEvent.pointerMove(row('B'), mouse());
+ expect(row('B')).toHaveFocus();
+ fireEvent.pointerUp(row('B'), mouse());
+ expect(onSelect).toHaveBeenCalledWith('B');
+ });
+
+ it('the opening release before the settle time acts on nothing; after it, it acts', () => {
+ vi.useFakeTimers();
+ const onSelect = vi.fn();
+ render(<Harness onSelect={onSelect} />);
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(trigger, mouse());
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_SETTLE_MS - 1);
+ });
+ fireEvent.pointerUp(row('B'), mouse());
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ fireEvent.pointerDown(trigger, mouse());
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ fireEvent.pointerUp(trigger, mouse());
+ fireEvent.pointerDown(trigger, mouse());
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_SETTLE_MS);
+ });
+ fireEvent.pointerUp(row('B'), mouse());
+ expect(onSelect).toHaveBeenCalledWith('B');
+ });
+
+ it('a finger held on the trigger opens after the long-press delay and then tracks', () => {
+ vi.useFakeTimers();
+ const onSelect = vi.fn();
+ const onOpenChange = vi.fn();
+ render(<Harness onSelect={onSelect} onOpenChange={onOpenChange} />);
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(trigger, touch());
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_LONG_PRESS_MS - 1);
+ });
+ expect(onOpenChange).not.toHaveBeenCalled();
+ act(() => {
+ vi.advanceTimersByTime(1);
+ });
+ expect(onOpenChange).toHaveBeenLastCalledWith(true);
+ fireEvent.pointerMove(row('C'), touch());
+ expect(row('C')).toHaveFocus();
+ fireEvent.pointerUp(row('C'), touch());
+ expect(onSelect).toHaveBeenCalledWith('C');
+ });
+
+ it('a finger that lifts before the delay is a tap: the browser click opens the menu', () => {
+ vi.useFakeTimers();
+ const onOpenChange = vi.fn();
+ render(<Harness onOpenChange={onOpenChange} />);
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(trigger, touch());
+ fireEvent.pointerUp(trigger, touch());
+ fireEvent.click(trigger, {detail: 1});
+ expect(onOpenChange).toHaveBeenCalledTimes(1);
+ expect(onOpenChange).toHaveBeenLastCalledWith(true);
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_LONG_PRESS_MS);
+ });
+ expect(onOpenChange).toHaveBeenCalledTimes(1);
+ });
+
+ it('a finger that travels on the trigger is a scroll, not a held press', () => {
+ vi.useFakeTimers();
+ const onOpenChange = vi.fn();
+ render(<Harness onOpenChange={onOpenChange} />);
+ const trigger = screen.getByRole('button', {name: 'Open'});
+ fireEvent.pointerDown(trigger, {...touch(), clientX: 0, clientY: 0});
+ fireEvent.pointerMove(trigger, {...touch(), clientX: 0, clientY: 40});
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_LONG_PRESS_MS);
+ });
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+
it('marks the menu root as carrying the press model', () => {
render(<Harness />);
expect(screen.getByRole('menu')).toHaveAttribute('data-astryx-menu-press');
@@ -374,4 +503,34 @@ describe('useMenuPress — edge autoscroll', () => {
});
expect(menu.scrollTop).toBe(atRest);
});
+
+ it('gives the page back its scroll when a held finger is cancelled', () => {
+ // A held finger installs a document-level touchmove preventer so the page
+ // does not scroll under the opening menu. Only the end of a gesture takes
+ // it off again, and a pointercancel is ordinary on touch — an incoming
+ // call, a system gesture. Cancelling used to leave the preventer live and
+ // the page unable to scroll at all.
+ vi.useFakeTimers();
+ render(<Harness />);
+ const trigger = screen.getByRole('button', {name: 'Open'});
+
+ fireEvent.pointerDown(trigger, {...touch(), clientX: 10, clientY: 10});
+ act(() => {
+ vi.advanceTimersByTime(MENU_PRESS_LONG_PRESS_MS);
+ });
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ const held = new Event('touchmove', {bubbles: true, cancelable: true});
+ document.dispatchEvent(held);
+ expect(held.defaultPrevented).toBe(true);
+
+ fireEvent.pointerCancel(trigger, touch());
+
+ const afterCancel = new Event('touchmove', {
+ bubbles: true,
+ cancelable: true,
+ });
+ document.dispatchEvent(afterCancel);
+ expect(afterCancel.defaultPrevented).toBe(false);
+ });
});
diff --git a/packages/core/src/hooks/useMenuPress.ts b/packages/core/src/hooks/useMenuPress.ts
index a80b29c4de..bc28f2fb72 100644
--- a/packages/core/src/hooks/useMenuPress.ts
+++ b/packages/core/src/hooks/useMenuPress.ts
@@ -12,7 +12,7 @@
* DropdownMenuSubMenu, Selector and MenuBottomSheetActionList. The pure
* transition table lives in menuPressGesture.ts.
*
- * One press inside a menu, owned end to end:
+ * One press in a menu, from the trigger or from inside, 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
@@ -26,6 +26,9 @@
* 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.
+ * - A mouse press on the trigger opens the menu at once; a finger held on the
+ * trigger opens it after the long-press delay. The settle rule decides
+ * whether the opening gesture's release may act (see menuPressGesture.ts).
* - `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
@@ -43,6 +46,7 @@
*/
import {useCallback, useEffect, useMemo, useRef, type RefObject} from 'react';
+import {currentGesture} from '../Layer/gestureCounter';
import {
IDLE_MENU_PRESS,
menuPressStep,
@@ -51,6 +55,7 @@ import {
type MenuPressGesture,
type MenuPressPointerType,
} from './menuPressGesture';
+import {useLongPress, type UseLongPressHandlers} from './useLongPress';
/** Marks a menu root that carries this press model. */
export const MENU_PRESS_MARKER = 'data-astryx-menu-press';
@@ -58,6 +63,8 @@ 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;
+/** How long a finger must rest on the trigger before the menu opens under it. */
+export const MENU_PRESS_LONG_PRESS_MS = 500;
/** 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;
@@ -154,16 +161,22 @@ export function __resetMenuPressForTest(): void {
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.
- */
+ /** The control that opens the menu, when the press may start there. */
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;
+ /**
+ * A mouse pressed the trigger, or a finger has rested on it for the
+ * long-press delay: open the menu under the held pointer. Return whether
+ * it opened; a `false` (the press closed an open menu instead) ends the
+ * gesture. The click the trigger receives for this same gesture is reported
+ * by {@link UseMenuPressReturn.isTriggerClickFromPress} so the caller can
+ * leave it alone.
+ */
+ onTriggerPress?: (pointerType: MenuPressPointerType) => boolean;
/**
* Move the highlight. `null` clears it. Defaults to moving DOM focus with
* `preventScroll` onto the row (or the control inside it), and onto the
@@ -190,6 +203,8 @@ export interface UseMenuPressOptions {
* document lacks it (jsdom). A test seam.
*/
hitTest?: (x: number, y: number) => Element | null;
+ /** @default 500 */
+ longPressDelayMs?: number;
/** Whether the model is live. @default true */
isEnabled?: boolean;
}
@@ -200,6 +215,17 @@ export interface UseMenuPressReturn {
onPointerDown: (event: React.PointerEvent<HTMLElement>) => void;
[MENU_PRESS_MARKER]: '';
};
+ /** Spread onto the trigger: a mouse press opens; a held finger opens. */
+ triggerProps: {
+ onPointerDown: (event: React.PointerEvent<HTMLElement>) => void;
+ onContextMenu: (event: React.MouseEvent<HTMLElement>) => void;
+ };
+ /**
+ * Whether the click reaching the trigger belongs to the gesture that just
+ * pressed it — the press already opened or closed the menu, so the click
+ * must neither toggle nor reopen it.
+ */
+ isTriggerClickFromPress: () => boolean;
/** End the gesture in flight with nothing acting (the menu closed). */
cancel: () => void;
}
@@ -241,8 +267,8 @@ interface ResolvedPoint {
// =============================================================================
/**
- * The press model for a menu: the row under the release acts and the
- * highlight follows a held pointer. See the file header.
+ * The press model for a menu: the row under the release acts, the highlight
+ * follows a held pointer, a mouse opens on press. See the file header.
*
* @example
* ```
@@ -250,8 +276,13 @@ interface ResolvedPoint {
* menuRef: listRef,
* triggerRef: buttonRef,
* itemSelector: MENU_ITEM_SELECTOR,
+ * onTriggerPress: () => openMenu(),
* onDismiss: closeMenu,
* });
+ * <button {...menuPress.triggerProps} onClick={e => {
+ * if (menuPress.isTriggerClickFromPress()) return;
+ * toggle();
+ * }} />
* <div ref={listRef} role="menu" {...menuPress.menuProps}>…</div>
* ```
*/
@@ -262,11 +293,19 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
const gestureRef = useRef<MenuPressGesture<HTMLElement>>(IDLE_MENU_PRESS);
const pointerIdRef = useRef<number | null>(null);
const detachRef = useRef<(() => void) | null>(null);
+ // The held finger is detected by `useLongPress`, the same hook ContextMenu
+ // uses, so the hold duration and the movement tolerance have one home. The
+ // handle is held in a ref because the pointer handlers below are stable
+ // callbacks and the hook is created further down, once `fireLongPress`
+ // exists.
+ const longPressApiRef = useRef<UseLongPressHandlers | null>(null);
+ const touchMovePreventerRef = useRef<(() => void) | null>(null);
const autoscrollRef = useRef<{
timer: ReturnType<typeof setInterval>;
direction: 1 | -1;
} | null>(null);
const lastPointerEventRef = useRef<PointerEvent | null>(null);
+ const triggerGestureRef = useRef<number | null>(null);
// The second pointer that ended a gesture must not start the next one.
const ignoredPointerIdRef = useRef<number | null>(null);
@@ -317,6 +356,9 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
}, []);
const endGesture = useCallback(() => {
+ longPressApiRef.current?.cancel();
+ touchMovePreventerRef.current?.();
+ touchMovePreventerRef.current = null;
stopAutoscroll();
detachRef.current?.();
detachRef.current = null;
@@ -389,12 +431,24 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
const applyEffect = useCallback(
(
effect: MenuPressEffect<HTMLElement>,
+ gesture: MenuPressGesture<HTMLElement>,
native: PointerEvent | undefined,
) => {
const doc = getDocument();
switch (effect.type) {
case 'none':
return;
+ case 'open': {
+ const pointerType =
+ gesture.phase === 'open' ? gesture.pointerType : 'mouse';
+ triggerGestureRef.current = currentGesture();
+ const didOpen =
+ optionsRef.current.onTriggerPress?.(pointerType) ?? false;
+ if (!didOpen) {
+ endGesture();
+ }
+ return;
+ }
case 'highlight':
highlight(effect.row);
return;
@@ -429,7 +483,7 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
(event: MenuPressEvent<HTMLElement>, native?: PointerEvent) => {
const result = menuPressStep(gestureRef.current, event);
gestureRef.current = result.gesture;
- applyEffect(result.effect, native);
+ applyEffect(result.effect, result.gesture, native);
},
[applyEffect],
);
@@ -525,6 +579,19 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
return;
}
lastPointerEventRef.current = event;
+ const gesture = gestureRef.current;
+ if (gesture.phase === 'triggerPress') {
+ // A finger that travels is scrolling, not holding. The tolerance is
+ // the shared hook's, so it cannot drift from ContextMenu's.
+ const isPending = longPressApiRef.current?.moveTo({
+ x: event.clientX,
+ y: event.clientY,
+ });
+ if (isPending === false) {
+ stepRef.current({type: 'cancel'});
+ }
+ return;
+ }
const point = resolvePoint(event);
stepRef.current(
{
@@ -587,6 +654,44 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
[getDocument, resolvePoint, updateAutoscroll],
);
+ // --- The held finger on the trigger ----------------------------
+
+ const fireLongPress = useCallback(() => {
+ const gesture = gestureRef.current;
+ if (gesture.phase !== 'triggerPress') {
+ return;
+ }
+ triggerGestureRef.current = currentGesture();
+ const didOpen =
+ optionsRef.current.onTriggerPress?.(gesture.pointerType) ?? false;
+ if (!didOpen) {
+ step({type: 'cancel'});
+ return;
+ }
+ // `touch-action` on the trigger was decided when the finger landed; the
+ // page must not scroll under a finger that is now driving a menu.
+ const doc = getDocument();
+ const prevent = (event: TouchEvent) => {
+ if (event.cancelable) {
+ event.preventDefault();
+ }
+ };
+ doc.addEventListener('touchmove', prevent, {passive: false, capture: true});
+ touchMovePreventerRef.current = () => {
+ doc.removeEventListener('touchmove', prevent, true);
+ };
+ step({type: 'opened', time: Date.now()});
+ }, [getDocument, step]);
+
+ // One long-press detector for the system: the same hook ContextMenu spreads
+ // onto its trigger, driven here from the pointer stream this model already
+ // observes. Its touch handlers go unused; the hold duration, the movement
+ // tolerance and the timer are what matter, and they now have one home.
+ longPressApiRef.current = useLongPress({
+ onLongPress: fireLongPress,
+ delayMs: options.longPressDelayMs ?? MENU_PRESS_LONG_PRESS_MS,
+ });
+
// --- Handlers ------------------------------------------------------------
const handleMenuPointerDown = useCallback(
@@ -630,13 +735,76 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
lastPointerEventRef.current = native;
const point = resolvePoint(native);
step(
- {type: 'down', pointerType, row: point.row, time: Date.now()},
+ {
+ type: 'down',
+ target: 'menu',
+ pointerType,
+ row: point.row,
+ time: Date.now(),
+ },
native,
);
},
[attach, resolvePoint, step],
);
+ const handleTriggerPointerDown = useCallback(
+ (event: React.PointerEvent<HTMLElement>) => {
+ const {isEnabled = true} = optionsRef.current;
+ if (event.pointerId === ignoredPointerIdRef.current) {
+ ignoredPointerIdRef.current = null;
+ return;
+ }
+ if (!isEnabled || gestureRef.current.phase !== 'idle') {
+ return;
+ }
+ const pointerType = normalizePointerType(event.pointerType);
+ if (pointerType == null || event.button !== 0) {
+ return;
+ }
+ if (pointerType === 'mouse' && event.ctrlKey) {
+ // Control-click is the context menu's on macOS.
+ return;
+ }
+ const native = event.nativeEvent;
+ attach(native.pointerId);
+ lastPointerEventRef.current = native;
+ if (pointerType !== 'mouse') {
+ longPressApiRef.current?.start({x: native.clientX, y: native.clientY});
+ }
+ step(
+ {
+ type: 'down',
+ target: 'trigger',
+ pointerType,
+ row: null,
+ time: Date.now(),
+ },
+ native,
+ );
+ },
+ [attach, step],
+ );
+
+ const handleTriggerContextMenu = useCallback(
+ (event: React.MouseEvent<HTMLElement>) => {
+ // A finger held on the trigger is opening the menu, not asking for the
+ // browser's own context menu.
+ const gesture = gestureRef.current;
+ if (gesture.phase !== 'idle' && gesture.pointerType !== 'mouse') {
+ event.preventDefault();
+ }
+ },
+ [],
+ );
+
+ const isTriggerClickFromPress = useCallback((): boolean => {
+ return (
+ triggerGestureRef.current != null &&
+ triggerGestureRef.current === currentGesture()
+ );
+ }, []);
+
const cancel = useCallback(() => {
if (gestureRef.current.phase !== 'idle') {
step({type: 'cancel'});
@@ -645,6 +813,8 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
}, [endGesture, step]);
useEffect(() => {
+ // Install the gesture counter's listeners before the first press.
+ currentGesture();
return () => {
endGesture();
};
@@ -656,8 +826,19 @@ export function useMenuPress(options: UseMenuPressOptions): UseMenuPressReturn {
onPointerDown: handleMenuPointerDown,
[MENU_PRESS_MARKER]: '',
},
+ triggerProps: {
+ onPointerDown: handleTriggerPointerDown,
+ onContextMenu: handleTriggerContextMenu,
+ },
+ isTriggerClickFromPress,
cancel,
}),
- [handleMenuPointerDown, cancel],
+ [
+ handleMenuPointerDown,
+ handleTriggerPointerDown,
+ handleTriggerContextMenu,
+ isTriggerClickFromPress,
+ cancel,
+ ],
);
}